SQL constraints are essential elements in relational database design that ensure the integrity, accuracy, and reliability of the data stored in a database. By enforcing specific rules on table columns, SQL constraints help maintain data consistency, preventing invalid data entries and optimizing query performance.
In this article, we will explain the most common SQL constraints in detail, providing clear examples and explaining how to implement them effectively.
What Are SQL Constraints?
SQL constraints are rules applied to columns or tables in a relational database to limit the type of data that can be inserted, updated, or deleted. These rules ensure the data is valid, consistent, and adheres to the business logic or database requirements. Constraints can be enforced during table creation or later using the ALTER TABLE
statement. They play a vital role in maintaining the quality and integrity of your database.
Types of SQL Constraints
SQL provides several types of constraints to manage different aspects of data integrity. These constraints are essential for ensuring that data meets the requirements of accuracy, consistency, and validity. Let’s go through each of them with detailed explanations and examples.
1. NOT NULL Constraint
The NOT NULL constraint ensures that a column cannot contain NULL values. This is particularly important for columns where a value is essential for identifying records or performing calculations. If a column is defined as NOT NULL, every row must include a value for that column.
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);
Explanation: In the above example, both the ID
and NAME
columns are defined with the NOT NULL constraint, meaning every student must have an ID
and NAME
value.
2. UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are distinct across all rows in a table. Unlike the PRIMARY KEY, which requires uniqueness and does not allow NULLs, the UNIQUE constraint allows NULL values but still enforces uniqueness for non-NULL entries.
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);
Explanation: Here, the ID
column must have unique values, ensuring that no two students can share the same ID
. We can have more than one UNIQUE constraint in a table.
3. PRIMARY KEY Constraint
A PRIMARY KEY constraint is a combination of the NOT NULL and UNIQUE constraints. It uniquely identifies each row in a table. A table can only have one PRIMARY KEY, and it cannot accept NULL values. This is typically used for the column that will serve as the identifier of records.
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
Explanation: In this case, the ID
column is set as the primary key, ensuring that each student’s ID is unique and cannot be NULL.
4. FOREIGN KEY Constraint
A FOREIGN KEY constraint links a column in one table to the primary key in another table. This relationship helps maintain referential integrity by ensuring that the value in the foreign key column matches a valid record in the referenced table.
Orders Table:
O_ID | ORDER_NO | C_ID |
---|
1 | 2253 | 3 |
2 | 3325 | 3 |
3 | 4521 | 2 |
4 | 8532 | 1 |
Customers Table:
C_ID | NAME | ADDRESS |
---|
1 | RAMESH | DELHI |
2 | SURESH | NOIDA |
3 | DHARMESH | GURGAON |
As we can see clearly that the field C_ID in Orders table is the primary key in Customers table, i.e. it uniquely identifies each row in the Customers table. Therefore, it is a Foreign Key in Orders table.
Example:
CREATE TABLE Orders
(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
)
Explanation: In this example, the C_ID
column in the Orders
table is a foreign key that references the C_ID
column in the Customers
table. This ensures that only valid customer IDs can be inserted into the Orders
table.
5. CHECK Constraint
The CHECK constraint allows us to specify a condition that data must satisfy before it is inserted into the table. This can be used to enforce rules, such as ensuring that a column’s value meets certain criteria (e.g., age must be greater than 18)
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
Explanation: In the above table, the CHECK constraint ensures that only students aged 18 or older can be inserted into the table.
6. DEFAULT Constraint
The DEFAULT constraint provides a default value for a column when no value is specified during insertion. This is useful for ensuring that certain columns always have a meaningful value, even if the user does not provide one
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);
Explanation: Here, if no value is provided for AGE
during an insert, the default value of 18 will be assigned automatically.
How to Specify Constraints in SQL
Constraints can be specified during the table creation process using the CREATE TABLE
statement. Additionally, constraints can be modified or added to existing tables using the ALTER TABLE
statement.
Syntax for Creating Constraints:
CREATE TABLE table_name
(
column1 data_type [constraint_name],
column2 data_type [constraint_name],
column3 data_type [constraint_name],
...
);
We can also add or remove constraints after a table is created:
Example to Add a Constraint:
ALTER TABLE Student
ADD CONSTRAINT unique_student_id UNIQUE (ID);
Conclusion
SQL constraints are essential for maintaining data integrity and ensuring consistency in relational databases. Understanding and implementing these constraints effectively will help in designing robust, error-free databases. By leveraging NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, and INDEX, you can ensure your database is optimized for accuracy and performance.
Similar Reads
SQL DROP CONSTRAINT In SQL, constraints are used to ensure data integrity and define rules for the data in our database tables. These rules include ensuring uniqueness, maintaining referential integrity, and validating data with conditions. By applying constraints such as primary key, foreign key, unique, and check con
4 min read
SQL | CHECK Constraint In SQL, One such constraint is the CHECK constraint, which allows to enforcement of domain integrity by limiting the values that can be inserted or updated in a column. By using CHECK, we can define conditions on a columnâs values and ensure that they adhere to specific rules.In this article, we wil
5 min read
SQL | UNIQUE Constraint In SQL, constraints play a vital role in maintaining the integrity and accuracy of the data stored in a database. One such constraint is the UNIQUE constraint, which ensures that all values in a column (or a combination of columns) are distinct, preventing duplicate entries. This constraint is espec
4 min read
MYSQL CHECK Constraint MySQL is a very famous and widely used open-source RDBMS. It is used to store, retrieve, and manage structured data efficiently. It is used in both types of applications i.e. large and small scale applications. In MySQL, the CHECK constraint enforces a condition on the column(s) of a table. It makes
5 min read
SQL | DEFAULT Constraint In SQL, maintaining data integrity and ensuring consistency across tables is important for effective database management. One way to achieve this is by using constraints. Among the many types of constraints, the DEFAULT constraint plays an important role in automating data insertion and ensuring tha
3 min read