Constraints in SQL | SQL Constraint - sql - sql tutorial - learn sql
- Constraints defines the way the Database Engine automatically enforces the integrity of a database.
- Constraints define rules regarding the values allowed in columns & are the standard mechanism for enforcing integrity.
- Using constraints is preferred to using DML Triggers , rules , & defaults .
- The query optimizer also uses constraint definitions to build high-performance query execution plans.
- You can place constraints to limit the type of data that can go into a table.
- Such constraints can be specified when the table when the table is first created via the CREATE TABLE statement, or after the table is already created via the ALTER TABLE statement.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Common types of constraints include the following:
- NOT NULL Constraint: Ensures that a column cannot have NULL value.
- DEFAULT Constraint: Provides a default value for a column when none is specified.
- UNIQUE Constraint: Ensures that all values in a column are different.
- CHECK Constraint: Makes sure that all values in a column satisfy certain criteria.
- Primary Key Constraint: Used to uniquely identify a row in the table.
- Foreign Key Constraint: Used to ensure referential integrity of the data.