Monday, January 7, 2013

[SQL / PLSQL] SQL Constraints


SQL Constraints

 

Constraints are the rules enforced on data columns on table. These are 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. 

Contraints could be column level or table level. Column level constraints are applied only to one column where as table level constraints are applied to the whole table.

Following are commonly used constraints available in SQL:
  • NOT NULL Constraint: Ensures that a column cannot have NULL value.
  • DEFAULT Constraint : Provides a default value for a column when none is specified.
  • UNIQUE Constraint: Ensures that all values in a column are different.
  • PRIMARY Key: Uniquely identified each rows/records in a database table.
  • FOREIGN Key: Uniquely identified a rows/records in any another database table.
  • CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain conditions.
  • INDEX: Use to create and retrieve data from the database very quickly.
  • By default, a column can hold NULL values. If you do not want a column to have a NULL value then you need to define such constraint on this column specifying that NULL is now not allowed for that column.
  • A NULL is not the same as no data, rather, it represents unknown data.


NOT NULL Constraint


For example, the following SQL creates a new table called CUSTOMERS and adds five columns, three of which, ID and NAME and AGE, specify not to accept NULLs:
CREATE TABLE CUSTOMERS(
       ID   Number              NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number             NOT NULL,
       ADDRESS  VARCHAR (25) ,
       SALARY   Number(18, 2),      
       PRIMARY KEY (ID)
     );

If CUSTOMERS table has already been created, then to add a NOT NULL constraint to SALARY column in Oracle and MySQL, you would write a statement similar to the following:
 
ALTER TABLE CUSTOMERS
   MODIFY SALARY  Number (18, 2) NOT NULL;
 

DEFAULT Constraint
 
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value.

For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here SALARY column is set to 5000.00 by default, so in case INSERT INTPO statement does not provide a value for this column then by default this column would be set to 5000.00.


CREATE TABLE CUSTOMERS(
       ID   Number           NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number            NOT NULL,
       ADDRESS  CHAR (25) ,
       SALARY   Number (18, 2) DEFAULT 5000.00,      
       PRIMARY KEY (ID)
);
  

If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
   MODIFY SALARY  Number (18, 2) DEFAULT 5000.00;


Drop Default Constraint:

 
To drop a DEFAULT constraint, use the following SQL: 

 ALTER TABLE CUSTOMERS
   ALTER COLUMN SALARY DROP DEFAULT;


UNIQUE Constraint


The UNIQUE Constraint prevents two records from having identical values in a particular column. In the CUSTOMERS table, for example, you might want to prevent two or more people from having identical age.

For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here AGE column is set to UNIQUE, so that you can not have two records with same age:

CREATE TABLE CUSTOMERS(
       ID   Number            NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number           NOT NULL UNIQUE,
       ADDRESS  VARCHAR (25) ,
       SALARY   DECIMAL (18, 2),      
       PRIMARY KEY (ID)
);

 
If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE column, you would write a statement similar to the following:

ALTER TABLE CUSTOMERS
   MODIFY AGE Number NOT NULL UNIQUE;
 
You can also use following syntax, which supports naming the constraint and multiple columns as well:

ALTER TABLE CUSTOMERS
   ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);
 
Drop a UNIQUE Constraint:


To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE CUSTOMERS
   DROP CONSTRAINT myUniqueConstraint;

PRIMARY Key


A primary key is a field in a table which uniquely identifies the each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.

A table can have only one primary key which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a  
composite key.

If a table has a primary key defined on any field(s) then you can not have two records having the same value of that field(s).

Note: You would use these concepts while creating database tables.

Here is the syntax to define ID attribute as a primary key in a CUSTOMERS table.
CREATE TABLE CUSTOMERS(
       ID   Number             NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number             NOT NULL,
       ADDRESS  VARCHAR (25) ,
       SALARY   Number (18, 2),      
       PRIMARY KEY (ID)
);

To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).

For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE CUSTOMERS(
       ID   Number              NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number              NOT NULL,
       ADDRESS  VARCHAR (25) ,
       SALARY   Number (18, 2),       
       PRIMARY KEY (ID, NAME)
);
  
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS
   ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);

Delete Primary Key:


You can clear the primary key constraints from the table, Use Syntax:

ALTER TABLE CUSTOMERS DROP PRIMARY KEY ;


FOREIGN Key 
 
A foreign key is a key used to link two tables together. This is sometimes called a referencing key.

Primary key field from one table and insert it into the other table where it becomes a foreign key ie. Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table. 

The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table. 

If a table has a primary key defined on any field(s) then you can not have two records having the same value of that field(s). 

Consider the structure of the two tables as follows:

CUSTOMERS table:
CREATE TABLE CUSTOMERS(
       ID   Number          NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number              NOT NULL,
       ADDRESS  VARCHAR (25) ,
       SALARY   Number (18, 2),      
       PRIMARY KEY (ID)
);

ORDERS table:
CREATE TABLE ORDERS (
       ID          Number        NOT NULL,
       DATE        DATETIME,
       CUSTOMER_ID Number references CUSTOMERS(ID),
       AMOUNT     double,
       PRIMARY KEY (ID)
);

If ORDERS table has already been created, and the foreign key has not yet been, use the syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
   ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);

DROP a FOREIGN KEY Constraint:

 
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS
   DROP FOREIGN KEY;
CHECK Constraint

The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn.t entered into the table.

For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here we add a CHECK with AGE column, so that you can not have any CUSTOMER below 18 years:
CREATE TABLE CUSTOMERS(
       ID   Number           NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number              NOT NULL CHECK (AGE >= 18),
       ADDRESS  VARCHAR (25) ,
       SALARY   Number (18, 2),      
       PRIMARY KEY (ID)
);
 
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
   MODIFY AGE Number NOT NULL CHECK (AGE >= 18 );
 
You can also use following syntax, which supports naming the constraint and multiple columns as well: 
ALTER TABLE CUSTOMERS
   ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);
 
DROP a CHECK Constraint: 
 

To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL: 
ALTER TABLE CUSTOMERS
   DROP CONSTRAINT myCheckConstraint;
 
INDEX 


The INDEX is used to create and retrieve data from the database very quickly. Index can be created by using single or group of columns in a table. When index is created it is assigned a ROWID for each rows before it sort out the data.

Proper indexes are good for performance in large databases but you need to be careful while creating index. Selection of fields depends on what you are using in your SQL queries.

For example, the following SQL creates a new table called CUSTOMERS and adds five columns:

CREATE TABLE CUSTOMERS(
       ID   Number              NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  Number              NOT NULL,
       ADDRESS  VARCHAR (25) ,
       SALARY   Number (18, 2),      
       COMMISSION Number,      
       PRIMARY KEY (ID)
);



Now you can create index on single or multiple columns using the folloiwng syntax:

CREATE INDEX index_name
    ON table_name ( column1, column2.....);

To create an INDEX on Commission column, to optimize the search on customers for a particular commission, following is the SQL syntax:
CREATE INDEX idx_commission
    ON CUSTOMERS ( commission );
 
DROP a INDEX Constraint

To drop a INDEX constraint, use the following SQL:

ALTER TABLE CUSTOMERS
   DROP INDEX idx_commission;

No comments:

Post a Comment