SQL Constraints
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.
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:
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:
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.