SQL Constraints
Rules for data in a table can be specified using SQL constraints.
SQL Create Constraints
Limitations can be declared either during the CREATE TABLE statement or using the ALTER TABLE statement after the table has been established.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
Rules for the data in a table can be specified using SQL constraints.
The kinds of data that can be entered into a table are restricted by constraints. This guarantees the data in the table is reliable and accurate. The action is canceled if there is any inconsistency between the data action and the constraint.
Table-level or column-level constraints are both possible. Constraints at the column level affect a single column, while those at the table level affect the entire 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