TechnicalEasy SQL & Databases

What is the difference between a primary key, a foreign key and a unique key?

Asked for Backend Developer, Full-Stack Developer

Why they ask this: Core relational design knowledge for any backend role.

Answer

  • Primary key: uniquely identifies each row. It cannot be NULL, and a table has only one (it can span several columns, a composite key).
  • Foreign key: a column that references the primary key of another table. It enforces referential integrity, so you cannot add a job for a company that does not exist. Use ON DELETE CASCADE or SET NULL to decide what happens when the parent row is deleted.
  • Unique key: guarantees no duplicate values in a column, such as email. A table can have many. In MySQL and PostgreSQL a unique column can hold several NULLs.
sql
CREATE TABLE jobs (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  company_id BIGINT NOT NULL,
  slug VARCHAR(255) NOT NULL UNIQUE,
  FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
);

Can you explain this in your own words?

Back to question bank