Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
222 views

I. Create Table Using Constraints What Is Constraint?

Uploaded by

Heini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
222 views

I. Create Table Using Constraints What Is Constraint?

Uploaded by

Heini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

I.

Create Table using Constraints

What is constraint?
- Rule governs how database data is inserted or manipulated.
- Rule enforced on data columns on table.
- used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the database.
 - If there is any violation between the constraint and the data action, the action is aborted by
the constraint.
Add constraints on one or more table columns using the following SQL commands:
CREATE TABLE—Add a constraint on one or more columns.
ALTER TABLE—Add or drop a constraint on one or more columns.

There are two syntax definitions you can use to add or change a constraint:

1) Column-Constraint—Use this syntax when you add a constraint on a column definition


in a CREATE TABLE statement.

E.g., oracle

CREATE TABLE member (


member_id number(4) PRIMARY KEY,
fname varchar2(20),
lname varchar2(20) NOT NULL,
member_type varchar2(10) NOT NULL
);

2) Table-Constraint—Use this syntax when you add a constraint after a column definition
in a CREATE TABLE statement, or when you add, alter, or drop a constraint on a column
using ALTER TABLE.

E.g., oracle
CREATE TABLE employee (
e_id number(4),
fname varchar2(20),
lname varchar2(20),
dob date,
salary number(6,2),

1
PRIMARY KEY (e_id) ); /* This is called unnamed constraint. */
ALTER TABLE Persons DROP e_id; /* Drop Unnamed constraint column */

Named and Unnamed Constraints


CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL, /* unnamed constraint */
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
/* named constraint */
);

CREATE TABLE member ( /* Oracle */


member_id number(4)
CONSTRAINT pk_mem PRIMARY KEY, /*named constraint */
fname varchar2(20),
lname varchar2(20) NOT NULL, /* unnamed constraint */
member_type varchar2(10)
CONSTRAINT nn_mem NOT NULL, /* named constraint */
price_paid number(5,2)
CONSTRAINT ch_mem CHECK(price_paid >= 0.0), /* named constraint */
start_date date DEFAULT sysdate); /* default constraint */

ALTER TABLE Persons


ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName);

ALTER TABLE Persons DROP CONSTRAINT pk_PersonID; /* drop named constraint */

Note:
Unnamed Constraints: by default constraint name will be defined.
Named Constraints: Constraint can be drop by its name.

2
1. NOT NULL Constraint

By default, a table column can hold NULL values. The NOT NULL constraint enforces a
column to NOT accept NULL values. The NOT NULL constraint enforces a field to always
contain a value.

CREATE TABLE PNotNull


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

2. UNIQUE Constraint

The UNIQUE constraint uniquely identifies each record in a database table. Unique
constraint columns can contain NULL values. Unique constraints columns can be modified or
updated. Unlike PRIMARY KEY, UNIQUE constraints cannot be used to define FOREIGN
KEY.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE
constraint defined on it. Note that you can have many UNIQUE constraints per table, but
only one PRIMARY KEY constraint per table.
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)

ALTER TABLE Persons


ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

3. PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values.
A primary key column cannot contain NULL values.

3
Most tables should have a primary key, and each table can have only ONE primary key.
CREATE TABLE PPersons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Or

CREATE TABLE Persons (


P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);

4. FOREIGN KEY Constraint

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

CREATE TABLE Orders /* MySQL */


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
);

5. CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column. If you
define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based
on values in other columns in the row.

CREATE TABLE Persons1 /* Oracle */


(
P_Id NUMBER(4) NOT NULL,
LastName varchar2(255) NOT NULL,
FirstName varchar2(255),
Address varchar2(255),

4
City varchar2(255),
CHECK (P_Id>0)
);

Create Table Boat /* Oracle */


(BoatID number NOT NULL,
BoatName varchar2(30) NOT NULL,
BoatType varchar2(20),
Primary Key (BoatID),
Check (BoatType IN('Yatch','Cruiser','Rawer')));

6. DEFAULT Constraint

The DEFAULT constraint is used to insert a default value into a column. The default value
will be added to all new records, if no other value is specified.
CREATE TABLE CityPersons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Yangon'
)

II. Creating Indexes


Indexes allow the database application to find data fast; without reading the whole table.
An index can be created in a table to find data more quickly and efficiently. The users cannot
see the indexes; they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because
the indexes also need an update). So you should only create indexes on columns (and
tables) that will be frequently searched against.

Creates an index on a table.

CREATE INDEX index_name /* Duplicate values are allowed */


ON table_name (column_name)

Creates a unique index on a table.


/* Duplicate values are not allowed. You cannot insert duplicate values in column_name */

CREATE UNIQUE INDEX index_name


ON table_name (column_name)
5
E.g.,
CREATE INDEX PIndex /* create index */
ON Persons (LastName)

/* using Index with Index hint */


SELECT * from persons USE INDEX (PIndex) WHERE LastName='Kong';

ALTER TABLE Persons DROP INDEX PIndex; /* Remove index */

CREATE INDEX PIndex /* create index */


ON Persons (LastName, FirstName)

For more information about index, visit to http://dev.mysql.com/doc/refman/5.7/en/index-


hints.html

III. Creating Views


Views are virtual tables. They do not contain data but instead, they contain queries that
retrieve data as needed. Views provide a level of encapsulation around SQL SELECT
statements and can be used to simplify data manipulation, as well as reformat or secure
underlying data.

Why using Views

- To reuse SQL Statements.

- To expose parts of a table instead of complete tables.

- To change data formatting and representation.

Views Rules and Restrictions

- Like tables views must be uniquely named. (They cannot be named with the name of any
other table of views.)

- Views cannot be indexed, nor can they have triggers or default values associated with
them.)

- You can present different views of the same data according to their particular criteria.

- Many DBMS prohibit the user of ORDER BY clause in view queries.

- To create views, you must have security access. This is usually granted by the database
administrator.

( grant create view to <username> /* for view SQLPlus in Oracle */

grant create trigger to <username> /* for trigger SQLPlus in Oracle */ )

6
1)

CREATE VIEW empview AS


SELECT empno, ename, deptno
FROM emp WHERE deptno=20;

2)
CREATE VIEW dept_view AS SELECT * FROM dept;

3)
CREATE VIEW emp_det AS
SELECT e.empno, e.ename, e.sal, e.deptno, d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno;

Using Views with calculated fields

/* Creating View */
CREATE VIEW myview AS
SELECT empno EMPLOYEE_NO, ename NAME, sal SALARY, job JOB
FROM emp
WHERE deptno=20;

/* Modifying View */
CREATE OR REPLACE VIEW myview
AS SELECT empno EMPLOYEE_NO, ename NAME, sal SALARY
FROM emp
WHERE deptno=10;

/* Retrieving Data from View */


SELECT * FROM myview;

/* Removing a view */
DROP VIEW view;

For browsing database and table definitions


1. To find out which database is currently selected.

SELECT DATABASE ( ); /* MySQL */

select ora_database_name from dual; /* Oracle */

SELECT USER FROM DUAL; /* current user Oracle */

7
2. To show tables of using database.

SHOW TABLES /* MySQL */

SELECT table_name FROM user_tables; /* Oracle */

3. To show table definition

DESCRIBE persons; /* MySQL */

DESC persons; /*MySQL */

DESC persons; /*Oracle */

4. To show create table statement

SHOW CREATE TABLE persons; /* MySQL getting create table statement of “person” table*/

SELECT DBMS_METADATA.GET_DDL('TABLE','PERSONS') from DUAL;

/* Oracle *** Use Upper Case in Table Name***/

*Note: The DUAL table is a special one-row, one-column table present by default in Oracle and other
database installations. In Oracle, the table has a single VARCHAR2(1) column called DUMMY that
has a value of 'X'. It is suitable for use in selecting a pseudo column such as SYSDATE or USER.
https://en.wikipedia.org/wiki/DUAL_table

Refs:

[1] Sams Teach yourself SQL in 10 mins, Fourth Edition, Copyright@ 2013 by Pearson
Education, Inc.

https://my.vertica.com/docs/7.1.x/HTML/index.htm#Authoring/AdministratorsGuide/Const
raints/AddingConstraints.htm

http://www.w3schools.com/sql/sql_constraints.asp

http://www.tutorialspoint.com/sql/sql-constraints.htm

http://www.w3resource.com/sql/creating-and-maintaining-tables/creating-table-
constraint.php

// Database Book from MCC

You might also like