Dbms Constraints
Dbms Constraints
SQL CONSTRAINTS
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
CREATE INDEX
SQL CREATE CONSTRAINTS
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.
SYNTAX
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
…
);
SQL CONSTRAINTS
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. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level.
Column level constraints apply to a column, and table level constraints apply to
the whole table.
DIFFERENT CONSTRAINTS COMMONLY USED IN SQL
The following SQL ensures that the “ID”, “LastName”, and “FirstName” columns
will NOT accept NULL values when the “Persons” table is created:
EXAMPLE
INPUT
CREATE TABLE Persons (
OUTPUT
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL NOT NULL ON ALTER TABLE
To create a NOT NULL constraint on the “Age” column when the “Persons” table is
already created, use the following SQL:
EXAMPLE
OUTPUT
INPUT
ALTER TABLE Persons
MODIFY COLUMN Age int NOT NULL;
SQL UNIQUE CONSTRAINT
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.
PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.
SQL UNIQUE CONSTRAINT ON CREATE TABLE
The following SQL creates a UNIQUE constraint on the “ID” column when the
“Persons” table is created:
EXAMPLE
INPUT
OUTPUT
SQL UNIQUE CONSTRAINT ON CREATE TABLE
To create a UNIQUE constraint on the “ID” column when the table is already
created, use the following SQL:
EXAMPLE
INPUT
OUTPUT
SQL UNIQUE CONSTRAINT ON ALTER TABLE
To create a UNIQUE constraint on the “ID” column when the table is already
created, use the following SQL:
EXAMPLE
INPUT
OUTPUT
DROP A UNIQUE CONSTRAINT
EXAMPLE
INPUT
OUTPUT