What is the difference between PRIMARY KEY and UNIQUE constraints?

Beginner

Answer

Both ensure uniqueness, but with key differences:

PRIMARY KEY:

  • Cannot contain NULL values
  • Only one per table
  • Automatically creates a unique index
  • Used for table relationships

UNIQUE:

  • Can contain NULL values (multiple NULLs allowed)
  • Multiple unique constraints per table
  • Creates a unique index
CREATE TABLE users (
    id SERIAL PRIMARY KEY,        -- Cannot be NULL
    email VARCHAR(255) UNIQUE,    -- Can have one NULL
    username VARCHAR(50) UNIQUE   -- Multiple unique constraints allowed
);