Skip to the page

DBMS · core

Keys and ER design

Keys identify rows and link tables. An ER diagram turns a real situation into entities, relationships and tables.

The notes

What you must know

  • Super key: any set of columns that identifies a row uniquely. Candidate key: a minimal super key, with no column to remove.
  • Primary key: the candidate key you choose. It is unique and NOT NULL, and a table has one. The other candidate keys are alternate keys.
  • Foreign key: a column that refers to a key in another table (dept_id in student refers to department). The database refuses a value that does not exist there: referential integrity.
  • Composite key: two or more columns together, such as (roll_no, course_code) in an enrolment table.
  • A unique key is not the same as a primary key. A table can have many unique keys but one primary key.
  • ER steps: find entities, their attributes, and the relationships with their type: one-to-one, one-to-many or many-to-many.
  • Many-to-many needs a junction table such as book_author(book_id, author_id), with both columns as the key. Never store authors in a comma-separated column.
  • Keep history in its own table: a Loan table (member, copy, issue date, due date, return date) gives history; a single borrowed_by column on the book does not. A book and a copy are different things.

The red pen

Common traps: mistake → fix

  • Mistake: A table can have many primary keys

    Fix: only one, but it can have many candidate keys.

  • Mistake: Super key and candidate key are the same

    Fix: a candidate key is a minimal super key.

  • Mistake: One table for everything is simpler

    Fix: it repeats data and causes anomalies.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain super, candidate, primary, alternate and foreign keys for a student table.
  2. What is a composite key? Give an example.
  3. Draw an ER diagram for a college library.
  4. How do you model a many-to-many relationship?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview