← Back to SQL, page 10

sql-0199 · Medium mid

Explain second normal form with an example of a partial dependency.

A table is in 2NF when it is in 1NF and no non-key column depends on only part of a composite key. In enrolments(student_id, course_id, marks, course_title), course_title depends on course_id alone, which is a partial dependency. Move course_title into a courses table keyed by course_id.

Full answer

Take a table keyed by (student_id, course_id):

text
student_id | course_id | marks | course_title
1          | 10        | 88    | Databases
2          | 10        | 75    | Databases

marks depends on the whole key: it is one student's mark in one course. course_title depends only on course_id, so it repeats for every student in the course. Renaming the course means updating many rows, which is the update anomaly again.

The 2NF fix splits the table: enrolments(student_id, course_id, marks) and courses(course_id, title).

2NF only matters for composite keys. A table with a single-column key that is in 1NF is automatically in 2NF, because there is no "part" of the key to depend on.

Key points

  • 2NF removes partial dependencies on a composite key
  • Every non-key column must depend on the whole key
  • Move partially dependent columns into their own table
  • Single-column keys cannot have partial dependencies

Common mistakes

  • Confusing partial dependencies with transitive ones
  • Claiming a single-column key table can violate 2NF

Follow-ups

  • What does 3NF add?
  • Is a surrogate id a way to avoid 2NF?

Tips

  • Point at the key part each column depends on