Unit 2 SQL Constraints
Unit 2 SQL Constraints
Database systems
SCSE
Constraints can be specified when the
table is created with the CREATE
TABLE statement, or after the table is
created with the ALTER TABLE
statement.
SQL constraints are used to specify rules
for the data in a table.
Constraints 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 table.
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
NOT NULL - Ensures that a column cannot have
a NULL value
UNIQUE - Ensures that all values in a column
are different
PRIMARY KEY - A combination of a NOT
NULL and UNIQUE. Uniquely identifies each
row in a table
FOREIGN KEY - Uniquely identifies a
row/record in another table
CHECK - Ensures that all values in a column
satisfies a specific condition
DEFAULT - Provides a default value for a
column
NOT NULL
By default, a column can hold NULL
values.
The NOT NULL constraint enforces a
column to NOT accept NULL values.
CREATE TABLE Doctor_Info
(
Doctor_ID INT NOT NULL,
Doctor_Name VARCHAR (100),
Doctor_Specialisation VARCHAR (80),
Doctor_Gender Varchar (20) not,
Doctor_Country Varchar (80)) ;
Field Type NULL Key Default Extra
Doctor_Na INT NO - - -
me
Doctor_Spe Varchar(20 NO - - -
cialist )
Doctor_Ge Varchar(20 NO - - -
nder )
Doctor_Co INT N0 - - -
untry
Example:-
CREATE TABLE Employees09(
Emp_ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Deparment varchar(255) NOT NULL,
Acct_No varchar(255) NOT NULL
);
UNIQUE Constraint