Creating and Altering a Constraint With SQL

Previous
Previous
Next
Next

To add, alter, or drop a constraint on a table, use the SQL ALTER statement, as shown in Example: Creating, Altering, and Dropping Constraints Using SQL. For information about primary key, foreign key, unique, and check constraints, see "Ensuring Data Integrity in Tables With Constraints".

Creating, Altering, and Dropping Constraints Using SQL

-- add a primary key constraint 
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_pkey 
  PRIMARY KEY (employee_id);

-- add a foreign key constraint
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_fkey 
  FOREIGN KEY (employee_id) REFERENCES employees (employee_id) 
  ON DELETE CASCADE;

-- add a unique constraint
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_unique_con 
  UNIQUE (social_security_id);

-- add a check constraint
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_check_con 
  CHECK ( dependents_claimed > 0);

-- disable a constraint
ALTER TABLE personal_info 
  DISABLE CONSTRAINT personal_info_check_con;

-- enable a constraint
ALTER TABLE personal_info 
  ENABLE CONSTRAINT personal_info_check_con;

-- drop a constraint
ALTER TABLE personal_info 
  DROP CONSTRAINT personal_info_check_con;

For information about adding a constraint with the Object Browser page, see "Adding a Primary Key Constraint", "Adding a Foreign Key Constraint", "Adding a Unique Constraint", and "Adding a Check Constraint".