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 | 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
SQLite CHECK Constraint
SQLite is a lightweight and embedded Relational Database Management System (commonly known as RDBMS). It is written in C Language. It supports standard SQL syntax. It is a server-less application which means it requires less configuration than any other client-server database (any database that acce
5 min read
PL/SQL CHECK Constraint
In Oracle's PL/SQL, the CHECK constraint is an essential feature that enforces data integrity by ensuring that the values stored in a table's columns meet specific conditions. By applying logical rules to the data, this constraint helps maintain the validity and consistency of the database, preventi
4 min read
MySQL UNIQUE Constraint
A UNIQUE constraint in MySQL ensures that all values in a column or a set of columns are distinct from one another. This constraint is used to prevent duplicate entries in a column or combination of columns, maintaining data integrity. UNIQUE Constraint in MySQLA UNIQUE constraint in MySQL prevents
4 min read
SQLite UNIQUE Constraint
SQLite is a lightweight relational database management system (RDBMS). It requires minimal configuration and it is self-contained. It is an embedded database written in C language. It operates a server-less, file-based database engine making it a good fit for mobile applications and simple desktop a
4 min read
MySQL NOT NULL Constraint
In the database management system maintaining data reliability and data accuracy is very important. MySQL is a popular relational database management system, which offers various constraints to provide security and ensure the integrity of the stored data. There are various key constraints present in
4 min read
PL/SQL DEFAULT Constraint
In PL/SQL the DEFAULT constraint is used to automatically assign a default value to a column when an explicit value is not provided during the insertion of a new row. This feature is particularly useful for ensuring that columns always have a meaningful value even when the user or application provid
5 min read