The not-null and unique constraints

The not-null constraint

  • Disallow null values in a certain column
  • Must hold true for the current state
  • Must hold true for future state
-- Disallow NULL values in firstname
ALTER TABLE professors 
ALTER COLUMN firstname SET NOT NULL;

How to add or remove a not-null constraint

To add a not-null

ALTER TABLE students
ALTER COLUMN home_phone
SET NOT NULL

To remove a not-null

ALTER TABLE students
ALTER COLUMN San
DROP NOT NULL

The Unique constraints

  • Disallow duplicate values in a certain column
  • Must hold true for the current state
  • Must hold true for future state

You can add the UNIQUE keyword after the column_name that should be unique. This, of course, only works for new tables

CREATE TABLE table_name (
 column_name UNIQUE
);

If you want to add a unique constraint to an existing table, you do it like that:

ALTER TABLE table_name
ADD CONSTRAINT some_name UNIQUE(column_name);

-- Make universities.university_shortname unique
ALTER TABLE universities
ADD CONSTRAINT university_shortname_unq UNIQUE(university_shortname);