Constraints
Constraints
Constraints
SQL constraints are used to specify rules for data in a table. 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. 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.
The following constraints are commonly used in SQL:
• 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 - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very
quickly
•
1. NOT NULL
Syntax to apply the NOT NULL constraint during table creation:
2. UNIQUE
Syntax to apply the UNIQUE constraint on a single column:
4. FOREIGN KEY
Syntax to apply a foreign key constraint during table creation:
5. CHECK
Syntax to apply check constraint on a single column:
CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnNa
me1 Condition), ColumnName2 datatype,…., ColumnNameN datatype);
Create a student table and apply CHECK constraint to check for the age less than or equal
to 15 while creating a table.
Syntax to apply check constraint on multiple columns:
CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 dat
atype CHECK (ColumnName1 Condition AND ColumnName2 Condition),
…., ColumnNameN datatype);
6. DEFAULT
Syntax to apply default constraint during table creation:
CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, C
olumnName2 datatype,…., ColumnNameN datatype);
7. CREATE INDEX
Syntax to create an index on single column:
CREATE INDEX IndexName ON TableName (ColumnName 1);
Indexes are not visible to the user, but they help the user to speed up the searching speed
or retrieval of data from the database.