Courses / Databases for Backend Interviews / Chapter 7
Module 4 · The relational model and normalisation · Chapter 7 of 27
Functional Dependencies: Closures, Candidate Keys and Minimal Covers
Builds on The Relational Model: Relations, Keys, Integrity and Relational Algebra. Next up: Normalisation: Anomalies, 1NF to BCNF, and When to Denormalise.
Part 1 · What a functional dependency is
One attribute fixing another
A delivery app that keeps pincode and city in every order row repeats the same pair thousands of times. A functional dependency is the exact way to say why that is wasteful, and it is the tool that normalisation uses to decide how to split tables.
A functional dependency (FD) is a rule written X → Y, where X and Y are sets of attributes of one relation. It says: whenever two tuples have the same values for X, they also have the same values for Y. We say X determines Y, X is the determinant (the left side), and Y is dependent on X. For delivery rows, pincode → city says that one pincode belongs to one city, and order_id → customer_id says that an order belongs to one customer.
Read the arrow as a function: given the left side, there is at most one possible right side. It is not a claim that the left side can be computed, only that it fixes the right side. The reverse need not hold. A city has many pincodes, so city → pincode is false even though pincode → city is true.
An FD is trivial when the right side is already part of the left side, as in {city, qty} → qty. Trivial FDs hold in every relation and tell you nothing. All the others are non-trivial, and those are the ones a designer cares about.
| Dependency | Holds? | Why |
|---|---|---|
| pincode → city | yes | a pincode lies in one city |
| city → pincode | no | a city has many pincodes |
| order_id → customer_id | yes | an order is placed by one customer |
Dependencies and keys
The idea of a key from the previous chapter is a special case. A set of attributes X is a superkey of a relation exactly when X determines every attribute of the relation. A candidate key is a superkey where no attribute can be removed. This is a more useful definition than "unique values", because it also works when you are designing and have no data yet: you decide which dependencies hold in the real world, and the keys follow from them.
Where do dependencies come from? From the meaning of the data, not from the rows. You ask "is it possible for two rows to share this value and differ in that one?" If the answer from the real world is no, you have an FD. If it is yes, you do not, even if your sample rows happen not to show it.
Testing a dependency against data
Data cannot prove a dependency, but it can disprove one. To test X → Y, group the rows by X and look for any group that has more than one value of Y. Such a group is a counterexample. The script below creates six delivery rows and asks the question three ways.
CREATE TABLE deliveries ( order_id int, customer_id int, customer_name text, pincode text, city text, product_id int, product_name text, qty int ); INSERT INTO deliveries (order_id, customer_id, customer_name, pincode, city, product_id, product_name, qty) VALUES (101, 1, 'Meera', '600017', 'Chennai', 11, 'Ghee', 2), (101, 1, 'Meera', '600017', 'Chennai', 12, 'Rice', 1), (102, 2, 'Karthik', '500081', 'Hyderabad', 11, 'Ghee', 1), (103, 1, 'Meera', '600017', 'Chennai', 13, 'Dal', 3), (104, 3, 'Ila', '500032', 'Hyderabad', 12, 'Rice', 2), (105, 4, 'Naveen', '411045', 'Pune', 13, 'Dal', 1);
-- does pincode determine city? pincodes with more than one city: SELECT pincode, count(DISTINCT city) AS cities FROM deliveries GROUP BY pincode HAVING count(DISTINCT city) > 1; -- does city determine pincode? cities with more than one pincode: SELECT city, count(DISTINCT pincode) AS pincodes FROM deliveries GROUP BY city HAVING count(DISTINCT pincode) > 1; -- the rows that break city -> pincode SELECT DISTINCT city, pincode FROM deliveries WHERE city = 'Hyderabad' ORDER BY pincode;
-- does pincode determine city? pincodes with more than one city: (0 rows) -- does city determine pincode? cities with more than one pincode: city | pincodes ----------+--------- Hyderabad | 2 (1 row) -- the rows that break city -> pincode city | pincode ----------+-------- Hyderabad | 500032 Hyderabad | 500081 (2 rows)
No pincode has more than one city, so no counterexample to pincode → city exists in this data. Two pincodes share the city of Hyderabad, so city → pincode fails, and the last query shows the two rows that disprove it.
-- customer_name -> customer_id holds in this data SELECT customer_name, count(DISTINCT customer_id) AS ids FROM deliveries GROUP BY customer_name HAVING count(DISTINCT customer_id) > 1; -- one more customer called Meera, and it stops holding INSERT INTO deliveries (order_id, customer_id, customer_name, pincode, city, product_id, product_name, qty) VALUES (106, 5, 'Meera', '560001', 'Bengaluru', 12, 'Rice', 1); SELECT customer_name, count(DISTINCT customer_id) AS ids FROM deliveries GROUP BY customer_name HAVING count(DISTINCT customer_id) > 1; -- count(DISTINCT) ignores NULL, so missing values need care SELECT count(DISTINCT x) AS distinct_non_null FROM (VALUES (1), (NULL)) AS v (x);
Part 2 · Armstrong's axioms
Three rules that derive every other dependency
Given a few dependencies you know, you can ask which others must also hold. If order_id → customer_id and customer_id → pincode are true, then order_id → pincode must be true too, with no need to look at data. A small set of inference rules, known as Armstrong's axioms, does this work.
| Axiom | Statement | Example |
|---|---|---|
| Reflexivity | if Y is a subset of X, then X → Y | {city, qty} → qty |
| Augmentation | if X → Y, then XZ → YZ for any Z | customer_id → pincode gives {customer_id, qty} → {pincode, qty} |
| Transitivity | if X → Y and Y → Z, then X → Z | order_id → customer_id and customer_id → pincode give order_id → pincode |
They are sound: whatever they derive is true in every relation that satisfies the starting dependencies. They are also complete: every dependency that is true in all such relations can be derived with them. Together this means the axioms capture exactly what "follows from" means for dependencies.
The axioms are small on purpose. Three more rules are convenient, and each follows from the axioms.
Derived rules
| Rule | Statement | How the axioms give it |
|---|---|---|
| Union | X → Y and X → Z give X → YZ | augment X → Y with X to get X → XY, augment X → Z with Y to get XY → YZ, then apply transitivity |
| Decomposition | X → YZ gives X → Y and X → Z | YZ → Y by reflexivity, then transitivity |
| Pseudotransitivity | X → Y and WY → Z give WX → Z | augment X → Y with W to get WX → WY, then transitivity with WY → Z |
Union and decomposition are why you can write the right side of a dependency as a list or split it into single attributes, whichever is easier. Pseudotransitivity is transitivity where the middle part needs a helper attribute, which appears when a key has several parts. The script below uses it as follows: order_id → customer_id and {qty, customer_id} → pincode give {qty, order_id} → pincode, with no new data needed.
One more point matters in practice. The reverse of a valid rule is not a rule. From pincode → city you cannot derive city → pincode, and the data in the previous lesson shows the reverse fails. Learners often assume an FD works both ways because the English sentence "pincode and city go together" sounds symmetric. Another habit worth building: when someone proposes a dependency, try to make up two rows that agree on the left side and differ on the right. If you can imagine such rows in the real business, the dependency does not hold.
Checking the rules on sample data
A proof tells you a rule is valid, and a run on data makes the idea concrete. The helper below takes rows and tests whether X → Y holds by grouping on X and checking that Y never varies. It is the same test as the SQL in the previous lesson, written in TypeScript so it can be reused. The sample rows are the six delivery rows.
type Row = Record<string, string | number> // does X -> Y hold in these rows? Group by X, then Y must not vary. export function holds(rows: Row[], x: string[], y: string[]): boolean { const seen = new Map<string, string>() for (const row of rows) { const key = JSON.stringify(x.map((a) => row[a])) const val = JSON.stringify(y.map((a) => row[a])) if (seen.has(key) && seen.get(key) !== val) return false seen.set(key, val) } return true } export const rows: Row[] = [ [101, 1, '600017', 'Chennai', 11, 2], [101, 1, '600017', 'Chennai', 12, 1], [102, 2, '500081', 'Hyderabad', 11, 1], [103, 1, '600017', 'Chennai', 13, 3], [104, 3, '500032', 'Hyderabad', 12, 2], [105, 4, '411045', 'Pune', 13, 1], ].map(([order_id, customer_id, pincode, city, product_id, qty]) => ({ order_id, customer_id, pincode, city, product_id, qty }))
The script then states each rule as premises and a conclusion. For every rule, if all premises hold in the rows, the conclusion must too. The last line tries the reverse of a valid dependency.
import { holds, rows } from './fd-holds.ts' type FD = [string[], string[]] // if every premise holds in the rows, the conclusion must hold too function rule(name: string, premises: FD[], concl: FD) { const p = premises.map(([x, y]) => holds(rows, x, y)) const c = holds(rows, concl[0], concl[1]) const given = p.join(', ') || 'none' console.log(`${name}: premises ${given}, conclusion ${c}`) } const o: FD = [['order_id'], ['customer_id']] const c: FD = [['customer_id'], ['pincode']] const p: FD = [['pincode'], ['city']] rule('reflexivity', [], [['city', 'qty'], ['qty']]) rule('augmentation', [c], [['customer_id', 'qty'], ['pincode', 'qty']]) rule('transitivity', [o, c], [['order_id'], ['pincode']]) rule('union', [c, [['customer_id'], ['city']]], [['customer_id'], ['pincode', 'city']]) rule('decomposition', [[['customer_id'], ['pincode', 'city']]], [['customer_id'], ['city']]) rule('pseudotransitivity', [o, [['qty', 'customer_id'], ['pincode']]], [['qty', 'order_id'], ['pincode']]) rule('reverse of pincode -> city', [p], [['city'], ['pincode']])
reflexivity: premises none, conclusion true augmentation: premises true, conclusion true transitivity: premises true, true, conclusion true union: premises true, true, conclusion true decomposition: premises true, conclusion true pseudotransitivity: premises true, true, conclusion true reverse of pincode -> city: premises true, conclusion false
Part 3 · Attribute closure and candidate keys
The closure of a set of attributes
Deriving dependencies by hand with the axioms gets tedious. A faster way to answer most questions is the closure of a set of attributes. The closure X+ is the set of all attributes that X determines, directly or through a chain, given a set F of dependencies. Once you can compute X+, you can test whether X → Y follows from F (check that Y is inside X+), and whether X is a key (check that X+ is everything).
The algorithm is short. Start with X+ = X. Scan the dependencies. For any dependency whose left side is inside X+, add its right side to X+. Repeat until a full scan adds nothing. It terminates because the set only grows and has a limited number of attributes.
The running example is a flat delivery relation with eight attributes and seven dependencies. They state that an order has one customer, a customer has one name and pincode, a pincode lies in one city, a product has one name, and an order has one quantity for each product. Two dependencies are redundant on purpose. The next lesson removes them.
export type FD = { lhs: string[]; rhs: string[] } // "a, b -> c" becomes { lhs: ['a', 'b'], rhs: ['c'] } export function fd(text: string): FD { const [l, r] = text.split('->').map((s) => s.split(',').map((a) => a.trim())) return { lhs: l, rhs: r } } export const fmt = (f: FD) => `${f.lhs.join(', ')} -> ${f.rhs.join(', ')}` // attribute closure: fire dependencies until nothing new is added export function closure( start: string[], fds: FD[], log?: (s: string) => void, ) { const out = new Set(start) let grew = true while (grew) { grew = false for (const f of fds) { const added = f.rhs.filter((a) => !out.has(a)) if (f.lhs.every((a) => out.has(a)) && added.length > 0) { added.forEach((a) => out.add(a)) grew = true log?.(`${fmt(f)} adds ${added.join(', ')}`) } } } return out }
Computing a closure
The code above stores a dependency as two lists and fires dependencies in a loop, logging each one that adds something. The next script runs it on four starting sets and then shows the order in which dependencies fire for {order_id}.
import { fd, closure, candidateKeys } from './fd-lib.ts' const all = ['order_id', 'customer_id', 'customer_name', 'pincode', 'city', 'product_id', 'product_name', 'qty'] const fds = [ 'order_id -> customer_id', 'customer_id -> customer_name, pincode', 'pincode -> city', 'customer_id -> city', 'product_id -> product_name', 'order_id, product_id -> qty', 'order_id, customer_id -> customer_name', ].map(fd) for (const start of [['order_id'], ['customer_id'], ['pincode'], ['order_id', 'product_id']]) { const c = [...closure(start, fds)] console.log(`{${start.join(', ')}}+ has ${c.length} of ${all.length}`) for (let i = 0; i < c.length; i += 4) { console.log(` ${c.slice(i, i + 4).join(', ')}`) } } console.log('--- firing order for {order_id}+') closure(['order_id'], fds, console.log) console.log('--- candidate keys') for (const k of candidateKeys(all, fds)) { console.log(`{${k.join(', ')}}`) }
{order_id}+ has 5 of 8
order_id, customer_id, customer_name, pincode
city
{customer_id}+ has 4 of 8
customer_id, customer_name, pincode, city
{pincode}+ has 2 of 8
pincode, city
{order_id, product_id}+ has 8 of 8
order_id, product_id, customer_id, customer_name
pincode, city, product_name, qty
--- firing order for {order_id}+
order_id -> customer_id adds customer_id
customer_id -> customer_name, pincode adds customer_name, pincode
pincode -> city adds city
--- candidate keys
{order_id, product_id}order_id alone reaches five of the eight attributes. It does not reach the product name or the quantity, so it is not a key. customer_id reaches four, pincode two. The pair {order_id, product_id} reaches all eight. The same closure answers implication questions. Does order_id → city follow from the dependency set? Yes, because city is inside the closure of order_id. Does order_id → qty follow? No, because qty is not inside it, and the missing piece is the product. The firing order at the bottom is the story told by the scene below: one dependency enables the next.
Finding candidate keys
A key is a set whose closure is the whole relation, and a candidate key is a key that cannot be shrunk. The simplest search is to try every subset of attributes in order and keep the minimal ones that reach everything. A subset always has a smaller number than any superset of it, so the loop meets a key before its supersets and can skip them. With eight attributes that is 255 subsets, which is nothing. For a table with 30 columns the count is over 100 crore, so real tools use the shortcut that follows.
// every minimal attribute set whose closure is the whole relation export function candidateKeys(all: string[], fds: FD[]) { const keys: string[][] = [] for (let mask = 1; mask < 1 << all.length; mask++) { const set = all.filter((_, i) => mask & (1 << i)) if (keys.some((k) => k.every((a) => set.includes(a)))) continue if (closure(set, fds).size === all.length) keys.push(set) } return keys }
The output of the previous script ends with the result: one candidate key, {order_id, product_id}. It is the only one because neither order_id nor product_id appears on the right side of any dependency, so no chain can ever produce them. Any attribute that never appears on a right side must be in every key. An attribute that appears only on right sides is in no candidate key at all. These two observations prune the search in practice.
A relation can have several candidate keys. If we add the dependency email → customer_id and customer_id → email, then customer_id and email are interchangeable in every key. The closure algorithm handles that without change.
What is the closure of {pincode} in the delivery example, and what does it tell you?
- {pincode, city}.
- A pincode fixes only the city, so pincode is far from a key.
How do you test whether X is a superkey with closures?
- Compute X+. If it contains every attribute, X is a superkey.
- It is a candidate key when removing any attribute stops that from being true.
Why must an attribute that never appears on a right side be part of every key?
Part 4 · Minimal cover
Why shrink a set of dependencies
The same facts can be written as many different dependency sets. A set may contain a dependency that follows from the others, or a left side with an attribute that does no work. Both make the set longer than it needs to be. A minimal cover (also called a canonical cover) of a set F is an equivalent set G with three properties. Every right side is a single attribute. No left side has an extraneous attribute. No dependency is redundant. Two sets are equivalent when each one implies every dependency of the other.
Minimal covers matter because the standard algorithm for designing a third normal form schema starts from one: it groups the dependencies by left side and makes one table per group, then adds a table for a candidate key if none of them holds one. A cover with redundant dependencies would produce tables that need not exist. The next chapter mentions this algorithm.
Three steps produce a cover. First, split every right side, using decomposition, so that X → {Y, Z} becomes X → Y and X → Z. Second, for each dependency with a composite left side, test each left attribute: an attribute A is extraneous if the left side without A still determines the right side, that is if the right side is in the closure of the smaller left side. Remove it. Third, for each dependency, test whether it follows from all the others, by computing the closure of its left side without it. If it does, drop it.
The three steps in code
Both tests use the closure function from the previous lesson. implied asks whether a dependency follows from a set. Step two uses it with the smaller left side, step three with the dependency removed from the set.
import { fmt, closure, type FD } from './fd-lib.ts' const implied = (f: FD, set: FD[]) => f.rhs.every((a) => closure(f.lhs, set).has(a)) export function minimalCover(input: FD[], say: (s: string) => void) { // 1. one attribute on every right side let set = input.flatMap((f) => f.rhs.map((a) => ({ lhs: f.lhs, rhs: [a] }))) say(`1. split right sides: ${set.length} dependencies`) // 2. drop extraneous attributes from left sides set = set.map((f) => { let lhs = f.lhs for (const a of f.lhs) { const smaller = lhs.filter((x) => x !== a) const test = { lhs: smaller, rhs: f.rhs } if (smaller.length > 0 && implied(test, set)) { say(`2. ${a} is extraneous in ${fmt({ lhs, rhs: f.rhs })}`) lhs = smaller } } return { lhs, rhs: f.rhs } })
Step three runs last. Each dependency is tested against the set without it, and removed when the rest already imply it. The loop only moves to the next index when nothing was removed, because removing an entry shifts the others along.
// 3. drop dependencies the others already imply for (let i = 0; i < set.length; ) { const rest = set.filter((_, j) => j !== i) if (implied(set[i], rest)) { say(`3. ${fmt(set[i])} is redundant`) set = rest } else i++ } return set }
Running it on the delivery dependencies
The input is the seven dependencies from the previous lesson. The script prints what each step removes, then the resulting cover, and checks equivalence with the original by testing that each set implies the other.
import { fd, fmt, closure, type FD } from './fd-lib.ts' import { minimalCover } from './cover.ts' const fds = [ 'order_id -> customer_id', 'customer_id -> customer_name, pincode', 'pincode -> city', 'customer_id -> city', 'product_id -> product_name', 'order_id, product_id -> qty', 'order_id, customer_id -> customer_name', ].map(fd) const cover = minimalCover(fds, console.log) console.log('--- minimal cover') for (const f of cover) console.log(fmt(f)) // two sets are equivalent when each implies the other's dependencies const implies = (a: FD[], b: FD[]) => b.every((f) => f.rhs.every((x) => closure(f.lhs, a).has(x))) console.log('equivalent to the original:', implies(cover, fds) && implies(fds, cover))
1. split right sides: 8 dependencies 2. order_id is extraneous in order_id, customer_id -> customer_name 3. customer_id -> customer_name is redundant 3. customer_id -> city is redundant --- minimal cover order_id -> customer_id customer_id -> pincode pincode -> city product_id -> product_name order_id, product_id -> qty customer_id -> customer_name equivalent to the original: true
Eight single-attribute dependencies came out of splitting. Step two found that order_id is extraneous in order_id, customer_id → customer_name, because customer_id → customer_name alone does the job. That turns the dependency into a copy of one that already exists. Step three then removed one of the two copies, and it removed customer_id → city because customer_id → pincode and pincode → city already give it by transitivity. Six dependencies remain, and they are equivalent to the original seven.
Grouping dependencies that share a left side gives a compact form: order_id → customer_id, customer_id → customer_name, pincode, pincode → city, product_id → product_name and {order_id, product_id} → qty. That is five lines, and the design algorithm would turn each into one table: orders, customers, pincodes, products and order lines.
A cover is not unique
Different input orders can lead to different minimal covers. Both are correct, and they are equivalent. The standard small example is a → b, b → a, b → c, a → c. Attributes a and b determine each other, so either of the two dependencies into c is enough, and a cover keeps just one of them. The script below runs the cover on that input and then on the same four dependencies in reverse order.
// a minimal cover is not unique: the order of the input can change it const small = ['a -> b', 'b -> a', 'b -> c', 'a -> c'].map(fd) for (const input of [small, [...small].reverse()]) { console.log('--- input order: ' + input.map(fmt).join('; ')) for (const f of minimalCover(input, () => {})) console.log(fmt(f)) }
--- input order: a -> b; b -> a; b -> c; a -> c a -> b b -> a a -> c --- input order: a -> c; b -> c; b -> a; a -> b b -> c b -> a a -> b
The first order kept a → c and the second kept b → c. Both covers have three dependencies, and each implies everything in the other. For design work this is fine, because either cover gives a correct schema. It does mean that you should not describe "the" minimal cover as if it were a single answer.
Which three conditions make a set of dependencies a minimal cover?
- Every right side has one attribute.
- No left side has an extraneous attribute.
- No dependency follows from the others.
How do you check that attribute A is extraneous in X → B?
- Remove A from X to get X'. A is extraneous if B is in the closure of X' under the whole set.
- In that case X' → B already holds.
Two minimal covers of the same set differ. Is one of them wrong?
- No. Minimal covers are not unique, and any one of them is equivalent to the original set.
All chapters · Previous: The Relational Model: Relations, Keys, Integrity and Relational Algebra