How to add constraints in SQL?

In SQL, you can add constraints to a table to enforce rules on the data. Constraints can be added when creating a table or modified later using the ALTER TABLE statement. Here are some common types of constraints and how to add them:

1. Adding Constraints When Creating a Table

CREATE TABLE Employees (
    employee_id INT PRIMARY KEY,          -- Primary Key Constraint
    email VARCHAR(255) UNIQUE,           -- Unique Constraint
    age INT CHECK (age >= 18),            -- Check Constraint
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES Departments(department_id)  -- Foreign Key Constraint
);

2. Adding Constraints to an Existing Table

You can also add constraints to an existing table using the ALTER TABLE statement.

Adding a Unique Constraint

ALTER TABLE Employees
ADD CONSTRAINT unique_email UNIQUE (email);

Adding a Check Constraint

ALTER TABLE Employees
ADD CONSTRAINT check_age CHECK (age >= 18);

Adding a Foreign Key Constraint

ALTER TABLE Employees
ADD CONSTRAINT fk_department
FOREIGN KEY (department_id) REFERENCES Departments(department_id);

3. Dropping Constraints

If you need to remove a constraint, you can use the ALTER TABLE statement as well:

ALTER TABLE Employees
DROP CONSTRAINT unique_email;

Summary

Constraints help maintain data integrity by enforcing rules on the data in your tables. You can define them during table creation or modify existing tables to add constraints as needed.

0 Comments

no data
Be the first to share your comment!