Constraints In SQL
The SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement).
Syntax with Constraints
Types of Constraint:-
Syntax with Constraints
CREATE TABLE table_name ( column_name1 data_type(size) constraint_name, column_name2 data_type(size) constraint_name, column_name3 data_type(size) constraint_name, ...... ...... ...... )
Types of Constraint:-
S.No. | Name | Description |
---|---|---|
1. | NOT NULL | Indicates that a column cannot store NULL value |
2. | UNIQUE | Ensures that each row for a column must have a unique value |
3. | PRIMARY KEY | A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly |
4. | FOREIGN KEY | Ensure the referential integrity of the data in one table to match values in another table |
5. | CHECK | Ensures that the value in a column meets a specific condition |
6. | DEFAULT | Specifies a default value when specified none for this column |