107 SQL Constraints
Summary of the W3Schools "SQL Constraints" Page:
-
SQL constraints are rules applied to columns in a table to ensure the accuracy, validity, and integrity of the data.
-
Constraints can be set when a table is first created (with
CREATE TABLE) or modified afterward (withALTER TABLE). -
Purpose: They limit the type of data that can be stored in the table, and any violation of a constraint will cause the associated action to abort.
-
Types of SQL constraints:
- NOT NULL: Prevents null (missing) values in a column.
- UNIQUE: Ensures all values are different within a column.
- PRIMARY KEY: Uniquely identifies each row in a table (implies NOT NULL and UNIQUE).
- FOREIGN KEY: Maintains referential integrity by enforcing a link between tables.
- CHECK: Ensures all values in a column meet a specific condition.
- DEFAULT: Provides a default value for a column if none is specified.
- CREATE INDEX: Improves speed of data retrieval (not strictly a constraint by all definitions, but included here).
-
Constraints can be either column level (applies to a single column) or table level (applies to the entire table).
-
Key usage: They guarantee correct and reliable data by enforcing rules at the database level. Any action violating a constraint will be blocked.
This page is part of the broader W3Schools SQL tutorial, providing concise examples and links to individual constraint topics for deeper learning.[1]
SQL constraints are used to specify rules for data in a table.
SQL Create Constraints
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.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
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