Wednesday, December 18, 2024

SQL ADD CONSTRAINT Keyword

 In SQL, the ADD CONSTRAINT keyword is used to add a new constraint to an existing table. A constraint is a rule that limits the type of data that can be inserted into a table. Constraints are used to maintain data integrity.

Here’s the general syntax to add a constraint to a table:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type;

Examples of adding constraints:

  1. Adding a Primary Key:
ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
  1. Adding a Foreign Key:
ALTER TABLE orders
ADD CONSTRAINT fk_customer_id FOREIGN KEY (customer_id) 
REFERENCES customers (customer_id);
  1. Adding a Unique Constraint:
ALTER TABLE employees
ADD CONSTRAINT uq_email UNIQUE (email);
  1. Adding a Check Constraint:
ALTER TABLE employees
ADD CONSTRAINT chk_age CHECK (age >= 18);
  1. Adding a Not Null Constraint:
ALTER TABLE employees
ADD CONSTRAINT nn_first_name NOT NULL (first_name);

Notes:

  • constraint_name is the name you want to assign to the constraint.
  • constraint_type can be PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, or NOT NULL, among others.

Each constraint type has specific rules about what it enforces:

  • PRIMARY KEY: Ensures that all values in the column are unique and not null.
  • FOREIGN KEY: Ensures the value in the column corresponds to a valid value in another table.
  • UNIQUE: Ensures all values in the column are unique.
  • CHECK: Ensures that values in the column satisfy a certain condition.
  • NOT NULL: Ensures that the column cannot have null values.

No comments:

Post a Comment