Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 102/ 160
06. Database Design, Normalization & Semi-Structured SQL

Functional Dependencies & Candidate Keys

Identify determinants and candidate keys that drive normalization choices.

IntermediateFunctional Dependency · Candidate Key3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

If knowing one thing always tells you another thing, the second depends on the first.

Think of it like…

A postcode determines the city: if two letters have the same postcode, they're for the same city. But the city doesn't determine the postcode, because a city has many postcodes.

Where you’ve seen it

order_lines(order_id, product_id, quantity, product_name, customer_id, customer_email) with rules: order_id → customer_id, customer_id → customer_email, product_id → product_name, and (order_id, product_id) → quantity. The only candidate key is (order_id, product_id). product_name depends on part of the key (a 2NF problem) and customer_email depends on a non-key column (a 3NF problem), which is exactly why products and customers belong in their own tables.

Words you’ll hear

Functional dependency (X → Y)
Equal X values always mean equal Y values.
Determinant
The left side of a dependency, X.
Superkey / candidate key
Columns that determine all others; a candidate key is a minimal superkey.
Attribute closure (X⁺)
Every column X determines, directly or through other dependencies.

Visual diagram

Loading interactive diagram

Theory & example queries

Dependencies and how to find keys

Dependencies describe rules of the business, so ask domain questions: can one email belong to two customers? Can an order have two customers? Sample data can disprove a dependency, but it can't prove one, because a rule might just not have been broken yet. Two derived rules do most of the reasoning: if X → Y and Y → Z then X → Z (transitivity), and anything determines its own columns (reflexivity).

To test whether a set X is a key, compute its closure X⁺: start with X, then repeatedly add the right side of any dependency whose left side is already included. If X⁺ contains every column, X is a superkey; if no proper subset of X is also a superkey, it's a candidate key. Columns that never appear on the right side of any dependency must be part of every candidate key, which narrows the search quickly.

Testing a dependency in existing dataQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id3FROM4  order_lines5GROUP BY6  customer_id7HAVING8  COUNT(DISTINCT customer_email) > 1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
customer_id
42
118

Note: Illustrative data-quality counterexamples whose orders contain more than one distinct email value.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Any rows returned are counterexamples to customer_id → customer_email (or data-quality problems to fix).

Key takeaway: Closure X⁺ = all columns → superkey; minimal superkey → candidate key.

From keys to design decisions

Columns that belong to some candidate key are prime attributes; the rest are non-prime. Normal forms are defined by which dependencies are allowed: 2NF forbids non-prime columns depending on part of a candidate key, 3NF forbids them depending on other non-prime columns, and BCNF requires every determinant to be a superkey. Each violation names the table you should split off.

In the schema, every candidate key becomes a constraint: the chosen one as PRIMARY KEY, the others as UNIQUE NOT NULL. employees with employee_id, email and national_id gets PRIMARY KEY (employee_id) plus UNIQUE (email) and UNIQUE (national_id). Choosing a surrogate primary key doesn't remove the natural candidate keys; leaving them unconstrained is how duplicate customers with the same email appear.

Enforcing all candidate keysQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TABLE employees (2  employee_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3  email text NOT NULL UNIQUE,4  national_id text NOT NULL UNIQUE,5  dept_id bigint NOT NULL REFERENCES departments (dept_id)6);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
CREATE TABLE

Note: Representative PostgreSQL status when departments already exists and identity columns are supported.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Prime vs non-prime drives the normal forms; enforce every candidate key.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Domain

List the business rules

Ask what determines what, and write each rule as X → Y.

Focus at this step

order_id → customer_id · product_id → product_name

What to watch at this step
Source
people, not samples
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A functional dependency X → Y means that whenever two rows have the same X, they must have the same Y: customer_id → customer_email. A candidate key is a minimal set of columns that determines every other column, so no two rows can share it. A table can have several candidate keys (employee_id, email, national_id); you pick one as the primary key and enforce the others with UNIQUE constraints. Dependencies and keys are what normal forms are defined in terms of.

Why it matters: Normalisation advice like "split this table" is only convincing when you can say which dependency causes the problem. Finding candidate keys tells you which UNIQUE constraints to add, which columns can never repeat, and what a row actually represents. Database-design interviews often give a wide table with some business rules and ask for its keys and normal form.

When to reach for it

  • Explaining why a table should be split
  • Deciding which UNIQUE constraints a table needs
  • Answering normal-form questions in design interviews

When to avoid or be careful

  • Inferring dependencies from a small data sample
  • A surrogate key with no UNIQUE on natural keys
  • Calling any unique set of columns a candidate key without checking minimality

Keys and constraints

Primary key
Best for: The chosen candidate key that identifies rows

Strengths: Unique, not null, referenced by foreign keys.

Watch out: Only one per table.

UNIQUE constraints on other candidate keys
Best for: Natural keys like email or national_id

Strengths: Stops duplicates the primary key can't see.

Watch out: An extra index per constraint.

No constraint, rely on the app
Best for: Nothing important

Strengths: Fewer indexes.

Watch out: Duplicates appear through races, imports and bugs.

Interview signals & numbers to know

When this topic comes up

  • “What are the candidate keys of this table?”
  • “Which normal form is this in?”
  • “Can two customers share an email?”
  • Composite keys
  • Natural vs surrogate keys

Benchmarks & rules of thumb

1 -
primary key per table
many -
candidate keys a table can have
X⁺ = all -
the test for a superkey

Common mistakes & follow-ups

Common interview mistakes

  • Seeing that no two rows in a sample share a name and concluding name is a key.
  • Calling (employee_id, email) a candidate key when employee_id alone already determines everything.
  • Adding a surrogate id and dropping the unique constraint on email, allowing duplicate accounts.

Likely interviewer follow-ups

  • Given these dependencies, what are the candidate keys?
  • What's the difference between a superkey and a candidate key?
  • How do functional dependencies relate to 2NF and 3NF?
Interview tip: Work the closure out loud for one or two column sets. Showing the method, not just the answer, is what earns credit in design interviews.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Functional Dependencies & Candidate Keys with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Entity-Relationship Diagrams (ERD) & Conceptual Data Modeling
Next topic
First Normal Form (1NF): Atomic Values & Repeating Groups