SQL Constraints
In SQL, constraints are rules applied to columns or tables to ensure the integrity,
accuracy, and reliability of the data within the database. Constraints limit the
type of data that can be inserted into a table to maintain consistency and enforce
business rules.
Types of SQL Constraints
NOT NULL:
Ensures that a column cannot have a NULL value.
Used when a column must always contain a value.
Example:
sql
Copy code
CREATE TABLE Students (
student_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
UNIQUE:
Ensures that all values in a column are different from each other.
Does not allow duplicate values in the specified column(s).
Example:
sql
Copy code
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
PRIMARY KEY:
Uniquely identifies each row in a table.
A table can have only one primary key, and it automatically includes a NOT NULL
constraint.
Example:
sql
Copy code
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);
FOREIGN KEY:
A foreign key in one table points to the primary key or unique key in another
table.
Ensures referential integrity by enforcing that values in the foreign key column
exist in the referenced table.
Example:
sql
Copy code
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);
CHECK:
Ensures that the values in a column satisfy a specific condition.
Can be used to enforce business rules or data validation.
Example:
sql
Copy code
CREATE TABLE Products (
product_id INT PRIMARY KEY,
price DECIMAL(10, 2),
CHECK (price > 0)
);
DEFAULT:
Specifies a default value for a column when no value is provided during an insert
operation.
Example:
sql
Copy code
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
status VARCHAR(20) DEFAULT 'Active'
);
INDEX:
Although not technically a "constraint," an index is used to improve the speed of
retrieval operations on a table.
Creates a data structure that improves search performance.
Example:
sql
Copy code
CREATE INDEX idx_name ON Employees(name);
Constraints in Action
Constraints can be added when creating a table using CREATE TABLE, or they can be
added to an existing table using ALTER TABLE. Here’s an example of both:
Using CREATE TABLE:
sql
Copy code
CREATE TABLE Students (
student_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT,
grade CHAR(1),
CHECK (age >= 18)
);
Using ALTER TABLE (to add a constraint after table creation):
sql
Copy code
ALTER TABLE Employees
ADD CONSTRAINT chk_salary CHECK (salary > 0);
Importance of Constraints
Data Integrity: Ensure the accuracy and consistency of the data.
Business Logic Enforcement: Constraints like CHECK enforce business rules.
Data Validation: Ensure that only valid data is stored in the database.
Relationships: Foreign keys maintain the relationships between tables.
By applying these constraints, a database can guarantee valid data, prevent data
anomalies, and support efficient data handling.