SQL CONSTRAINTS

SQL CONSTRAINTS


SQL constraints are used to specify rules or validation for the column value or entire row in a table.

If there is any data violation between the SQL constraint and the input data action, the action is aborted by the SQL constraint.

These are used to limit the unknown value or type of value that can go into a table. This ensures the accuracy and reliability of the column value or row data in the database.





List Of SQL CONSTRAINTS

Following are commonly used sql constraints in SQL.

  • NOT NULL : NOT NULL constraint restricts a column from having a NULL value. For more information pls visit our SQL NOT NULL tutorial page.

  • DEFAULT : The SQL DEFAULT constraint provides a default value to a field when the user did not provide a specific value. For more information pls visit our SQL DEFAULT tutorial page.

  • CHECK : The SQL CHECK constraint is used to limit the value range that can be placed in a table field or column. For more information pls visit our SQL CHECK tutorial page.

  • UNIQUE : The SQL UNIQUE constraint is used to add unique or distinct value in a field and uniquely identifies each row in a database table. For more information pls visit our SQL UNIQUE tutorial page.

  • PRIMARY KEY : The SQL PRIMARY KEY constraint is used to add unique or distinct value in a field and uniquely identifies each row in a database table. For more information pls visit our SQL PRIMARY KEY tutorial page.

  • FOREIGN KEY : A SQL FOREIGN KEY is a reference key used to link or point two tables together. The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table. For more information pls visit our SQL FOREIGN KEY tutorial page.





SQL CONSTRAINT Syntax

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

SQL CREATE TABLE + CONSTRAINT Syntax


CREATE TABLE table_name
(
columnname1 data_type constraint_name,
columnname2 data_type constraint_name,
columnname3 data_type constraint_name,
....
);

SQL ALTER TABLE + CONSTRAINT Syntax


ALTER TABLE table_name
ADD/DROP CONSTRAINT constraint_name

These constraints have been discussed later in this tutorial.