\n
\n
\n\n```\n
\nSQL Constraints
\n\n\n
\n\n\n
\nSQL constraints are used to specify rules for data in a table.
\nIf there is a violation between the constraint and the data action, the action is aborted.
\nConstraints can be specified when the table is created (via the CREATE TABLE statement) or after the table is created (via the ALTER TABLE statement).
\nConstraints will be enforced at the column or table level. Column-level constraints apply to a single column, while table-level constraints apply to the entire table.
\nThe syntax for creating constraints is as follows:
\nCREATE TABLE table_name\n(\ncolumn_name1 data_type(size) constraint_name,\ncolumn_name2 data_type(size) constraint_name,\ncolumn_name3 data_type(strongly) constraint_name,\n....\n);\n
In SQL, we have the following constraints:
\n- \n
- NOT NULL - Indicates that a column cannot store NULL values. \n
- UNIQUE - Ensures that each row in a column must have a unique value. \n
- PRIMARY KEY - A combination of NOT NULL and UNIQUE. Uniquely identifies each row in a table. \n
- FOREIGN KEY - Uniquely identifies a row/record in another table. \n
- CHECK - Ensures that the values in a column meet a specific condition. \n
- DEFAULT - Specifies a default value for a column when no value is specified. \n
In the following chapters, we will explain each constraint in detail.
\n
YouTip