PRACTICAL: 4
Aim: To implement DIFFERENT CONSTRAINTS IN RDBMS
1. NOT NULL:
This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL, Age int );
2. UNIQUE: The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
Example:
CREATE TABLE Persons ( ID int NOT NULL UNIQUE, LastName varchar(255) NOT
NULL, FirstName varchar(255), Age int );
Note : Not null and unique together make primary key ,hence key is primary in this
picture.
3. PRIMARY KEY: Primary keys must contain UNIQUE values, and cannot contain NULL
values.A table can have only ONE primary key; and in the table, this primary key can
consist of single or mul ple columns (fields).
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (ID) );
4. FOREIGN KEY: The FOREIGN KEY constraint is used to prevent ac ons that would
destroy links between tables. A FOREIGN KEY is a field (or collec on of fields) in one
table, that refers to the PRIMARY KEY in another table. The table with the foreign
key is called the child table, and the table with the primary key is called the
referenced or parent table.
Example:
CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID
int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
5. CHECK: The CHECK constraint is used to limit the value range that can be placed in a
column.
Example:
CREATE TABLE student ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, CHECK (Age>=18) );
6. DEFAULT: The DEFAULT constraint is used to set a default value for a column. The
default value will be added to all new records, if no other value is specified.
Example:
CREATE TABLE student ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, City varchar(255) DEFAULT 'Sandnes' );
7. CREATE INDEX: The CREATE INDEX statement is used to create indexes in tables.
Indexes are used to retrieve data from the database more quickly than otherwise.
The users cannot see the indexes, they are just used to speed up searches/queries.
Example:
create index try on persons(lastname,firstname);