YouTip LogoYouTip

Sql Constraints

```html\n\n\n\n\nSQL Constraints | Rookie Tutorial\n\n\n\n\n
\n
\n

SQL Constraints

\n
\n\n
\n
\n
\n

SQL constraints are used to specify rules for data in a table.

\n

If there is a violation between the constraint and the data action, the action is aborted.

\n

Constraints can be specified when the table is created (via the CREATE TABLE statement) or after the table is created (via the ALTER TABLE statement).

\n

Constraints 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.

\n

The syntax for creating constraints is as follows:

\n
CREATE 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
\n

In the following chapters, we will explain each constraint in detail.

\n
\n
\n
\n\n
\n
\n
\n \n\n```
← Sql NotnullSql Create Table β†’