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:
- Adding a Primary Key:
ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
- Adding a Foreign Key:
ALTER TABLE orders
ADD CONSTRAINT fk_customer_id FOREIGN KEY (customer_id)
REFERENCES customers (customer_id);
- Adding a Unique Constraint:
ALTER TABLE employees
ADD CONSTRAINT uq_email UNIQUE (email);
- Adding a Check Constraint:
ALTER TABLE employees
ADD CONSTRAINT chk_age CHECK (age >= 18);
- Adding a Not Null Constraint:
ALTER TABLE employees
ADD CONSTRAINT nn_first_name NOT NULL (first_name);
Notes:
constraint_nameis the name you want to assign to the constraint.constraint_typecan bePRIMARY KEY,FOREIGN KEY,UNIQUE,CHECK, orNOT 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