Database Normalization · Lesson 34 of 112

Database Functional Dependencies

What you will learn

  • What a functional dependency (FD) is
  • How to read and write A -> B
  • How to test an FD against data with SQL
  • Why FDs come from the real world, not from the data you happen to have
  • How keys relate to FDs, and how to find them with attribute closure

1. The idea

Normalization is built on one idea: if you know one thing, you can know another.

If you know an employee's ID, you know their name. We write this as

emp_id -> name

and say "emp_id determines name", or "name is functionally dependent on emp_id". Formally: whenever two rows have the same emp_id, they must have the same name.

The left side can be several columns: (order_id, product_id) -> qty means an order and a product together fix the quantity.

The arrow is one-way. dept_id -> dept_name does not automatically mean dept_name -> dept_id.

2. Dependencies come from meaning

An FD is a statement about the real world the table describes, not about the rows you see today. "A department ID has one department name" is a rule of the business. Whether the data looks like it follows a rule proves nothing; a single row cannot show a dependency, and a small sample can look like it follows a rule by luck.

So the order of work is: ask what is true in the real world, then design the tables so the database enforces it. Data can only disprove a guessed FD (by showing two rows that break it), never prove it.

3. Testing an FD with SQL

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own to your browser's copy; run the examples from top to bottom, and press Reset data to start again.

An FD A -> B is broken when one value of A appears with more than one value of B. This query counts such A values. Make a small table of employees and test four guesses (0 means no value of the left side has two different right sides):

CREATE TABLE emp (emp_id INTEGER, name TEXT, dept_id INTEGER, dept_name TEXT, salary INTEGER);
INSERT INTO emp VALUES
    (1, 'Rina', 10, 'Sales', 500), (2, 'Sam', 10, 'Sales', 450), (3, 'Lee', 20, 'Support', 400),
    (4, 'Amy', 20, 'Support', 500), (5, 'Joe', 30, 'Tech', 450);
SELECT 'emp_id -> name' AS fd, COUNT(*) AS broken_values
FROM (SELECT emp_id FROM emp GROUP BY emp_id HAVING COUNT(DISTINCT name) > 1)
UNION ALL
SELECT 'emp_id -> dept_name', COUNT(*)
FROM (SELECT emp_id FROM emp GROUP BY emp_id HAVING COUNT(DISTINCT dept_name) > 1)
UNION ALL
SELECT 'dept_id -> dept_name', COUNT(*)
FROM (SELECT dept_id FROM emp GROUP BY dept_id HAVING COUNT(DISTINCT dept_name) > 1)
UNION ALL
SELECT 'dept_id -> salary', COUNT(*)
FROM (SELECT dept_id FROM emp GROUP BY dept_id HAVING COUNT(DISTINCT salary) > 1);
fd                    broken_values
--------------------  -------------
emp_id -> name                    0
emp_id -> dept_name               0
dept_id -> dept_name              0
dept_id -> salary                 2
(4 rows)
CREATE TABLE emp (emp_id INTEGER, name TEXT, dept_id INTEGER, dept_name TEXT, salary INTEGER);
INSERT INTO emp VALUES
    (1, 'Rina', 10, 'Sales', 500), (2, 'Sam', 10, 'Sales', 450), (3, 'Lee', 20, 'Support', 400),
    (4, 'Amy', 20, 'Support', 500), (5, 'Joe', 30, 'Tech', 450);
SELECT 'emp_id -> name' AS fd, COUNT(*) AS broken_values
FROM (SELECT emp_id FROM emp GROUP BY emp_id HAVING COUNT(DISTINCT name) > 1)
UNION ALL
SELECT 'emp_id -> dept_name', COUNT(*)
FROM (SELECT emp_id FROM emp GROUP BY emp_id HAVING COUNT(DISTINCT dept_name) > 1)
UNION ALL
SELECT 'dept_id -> dept_name', COUNT(*)
FROM (SELECT dept_id FROM emp GROUP BY dept_id HAVING COUNT(DISTINCT dept_name) > 1)
UNION ALL
SELECT 'dept_id -> salary', COUNT(*)
FROM (SELECT dept_id FROM emp GROUP BY dept_id HAVING COUNT(DISTINCT salary) > 1);
fd                    broken_values
--------------------  -------------
emp_id -> name                    0
emp_id -> dept_name               0
dept_id -> dept_name              0
dept_id -> salary                 2
(4 rows)
CREATE TABLE emp (emp_id INTEGER, name TEXT, dept_id INTEGER, dept_name TEXT, salary INTEGER);
INSERT INTO emp VALUES
    (1, 'Rina', 10, 'Sales', 500), (2, 'Sam', 10, 'Sales', 450), (3, 'Lee', 20, 'Support', 400),
    (4, 'Amy', 20, 'Support', 500), (5, 'Joe', 30, 'Tech', 450);
SELECT 'emp_id -> name' AS fd, COUNT(*) AS broken_values
FROM (SELECT emp_id FROM emp GROUP BY emp_id HAVING COUNT(DISTINCT name) > 1)
UNION ALL
SELECT 'emp_id -> dept_name', COUNT(*)
FROM (SELECT emp_id FROM emp GROUP BY emp_id HAVING COUNT(DISTINCT dept_name) > 1)
UNION ALL
SELECT 'dept_id -> dept_name', COUNT(*)
FROM (SELECT dept_id FROM emp GROUP BY dept_id HAVING COUNT(DISTINCT dept_name) > 1)
UNION ALL
SELECT 'dept_id -> salary', COUNT(*)
FROM (SELECT dept_id FROM emp GROUP BY dept_id HAVING COUNT(DISTINCT salary) > 1);
fd                    broken_values
--------------------  -------------
emp_id -> name                    0
emp_id -> dept_name               0
dept_id -> dept_name              0
dept_id -> salary                 2
(4 rows)

The last line is a genuine disproof: department 10 has two different salaries, so a department does not determine a salary. The earlier lines (0) say only that this data does not contradict those rules.

Here is why data is a weak witness. These two also show 0:

SELECT 'dept_name -> dept_id' AS fd, COUNT(*) AS broken_values
FROM (SELECT dept_name FROM emp GROUP BY dept_name HAVING COUNT(DISTINCT dept_id) > 1)
UNION ALL
SELECT 'name -> dept_id', COUNT(*)
FROM (SELECT name FROM emp GROUP BY name HAVING COUNT(DISTINCT dept_id) > 1);
fd                    broken_values
--------------------  -------------
dept_name -> dept_id              0
name -> dept_id                   0
(2 rows)
SELECT 'dept_name -> dept_id' AS fd, COUNT(*) AS broken_values
FROM (SELECT dept_name FROM emp GROUP BY dept_name HAVING COUNT(DISTINCT dept_id) > 1)
UNION ALL
SELECT 'name -> dept_id', COUNT(*)
FROM (SELECT name FROM emp GROUP BY name HAVING COUNT(DISTINCT dept_id) > 1);
fd                    broken_values
--------------------  -------------
dept_name -> dept_id              0
name -> dept_id                   0
(2 rows)
SELECT 'dept_name -> dept_id' AS fd, COUNT(*) AS broken_values
FROM (SELECT dept_name FROM emp GROUP BY dept_name HAVING COUNT(DISTINCT dept_id) > 1)
UNION ALL
SELECT 'name -> dept_id', COUNT(*)
FROM (SELECT name FROM emp GROUP BY name HAVING COUNT(DISTINCT dept_id) > 1);
fd                    broken_values
--------------------  -------------
dept_name -> dept_id              0
name -> dept_id                   0
(2 rows)

name -> dept_id holds only because no two employees share a name yet. In real life two employees can be called Sam, so that FD is not a real rule. Never decide FDs from a sample alone.

On the real data

Join a few tables into one wide table, the kind of table that normalization splits again, and test some guesses on it.

Every order line, with its product and category, in one wide table flat:

CREATE TABLE flat AS
SELECT oi.order_id, oi.line_no, oi.product_id, p.name AS product_name,
       p.category_id, cat.name AS category_name, oi.unit_price
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id;
SELECT 'product_id -> product_name' AS fd, COUNT(*) AS broken_values
FROM (SELECT product_id FROM flat GROUP BY product_id HAVING COUNT(DISTINCT product_name) > 1)
UNION ALL
SELECT 'product_id -> category_name', COUNT(*)
FROM (SELECT product_id FROM flat GROUP BY product_id HAVING COUNT(DISTINCT category_name) > 1)
UNION ALL
SELECT 'category_id -> category_name', COUNT(*)
FROM (SELECT category_id FROM flat GROUP BY category_id HAVING COUNT(DISTINCT category_name) > 1)
UNION ALL
SELECT 'product_id -> unit_price', COUNT(*)
FROM (SELECT product_id FROM flat GROUP BY product_id HAVING COUNT(DISTINCT unit_price) > 1)
UNION ALL
SELECT 'product_name -> product_id', COUNT(*)
FROM (SELECT product_name FROM flat GROUP BY product_name HAVING COUNT(DISTINCT product_id) > 1);
fd                            broken_values
----------------------------  -------------
product_id -> product_name                0
product_id -> category_name               0
category_id -> category_name              0
product_id -> unit_price                 45
product_name -> product_id                0
(5 rows)

The first three hold: a product has one name and one category, and a category has one name. product_id -> unit_price is broken, because the price paid on a line can differ from the list price (a discount), so the price belongs to the line, not to the product. The last line shows 0 as well, but that is only the luck of this data: two different products could share a name, so it is not a rule.

Every account, with its branch and customer, in one wide table flat:

CREATE TABLE flat AS
SELECT a.account_id, a.account_type, b.branch_id, b.name AS branch_name, b.city AS branch_city,
       cu.customer_id, cu.full_name
FROM accounts a
JOIN branches b ON b.branch_id = a.branch_id
JOIN customers cu ON cu.customer_id = a.customer_id;
SELECT 'account_id -> branch_name' AS fd, COUNT(*) AS broken_values
FROM (SELECT account_id FROM flat GROUP BY account_id HAVING COUNT(DISTINCT branch_name) > 1)
UNION ALL
SELECT 'branch_id -> branch_name', COUNT(*)
FROM (SELECT branch_id FROM flat GROUP BY branch_id HAVING COUNT(DISTINCT branch_name) > 1)
UNION ALL
SELECT 'branch_id -> branch_city', COUNT(*)
FROM (SELECT branch_id FROM flat GROUP BY branch_id HAVING COUNT(DISTINCT branch_city) > 1)
UNION ALL
SELECT 'branch_id -> account_type', COUNT(*)
FROM (SELECT branch_id FROM flat GROUP BY branch_id HAVING COUNT(DISTINCT account_type) > 1)
UNION ALL
SELECT 'full_name -> customer_id', COUNT(*)
FROM (SELECT full_name FROM flat GROUP BY full_name HAVING COUNT(DISTINCT customer_id) > 1);
fd                         broken_values
-------------------------  -------------
account_id -> branch_name              0
branch_id -> branch_name               0
branch_id -> branch_city               0
branch_id -> account_type              6
full_name -> customer_id              16
(5 rows)

The first three hold: a branch has one name and one city. branch_id -> account_type is broken, because a branch has both checking and savings accounts. The last line is also broken: some full names belong to more than one customer, so a name is not a safe key, which is exactly the lesson of this section.

Every section, with its course and teacher, in one wide table flat:

CREATE TABLE flat AS
SELECT s.section_id, s.term, co.course_id, co.code AS course_code, co.title AS course_title,
       t.teacher_id, t.name AS teacher_name
FROM sections s
JOIN courses co ON co.course_id = s.course_id
JOIN teachers t ON t.teacher_id = s.teacher_id;
SELECT 'section_id -> course_title' AS fd, COUNT(*) AS broken_values
FROM (SELECT section_id FROM flat GROUP BY section_id HAVING COUNT(DISTINCT course_title) > 1)
UNION ALL
SELECT 'course_id -> course_title', COUNT(*)
FROM (SELECT course_id FROM flat GROUP BY course_id HAVING COUNT(DISTINCT course_title) > 1)
UNION ALL
SELECT 'course_id -> course_code', COUNT(*)
FROM (SELECT course_id FROM flat GROUP BY course_id HAVING COUNT(DISTINCT course_code) > 1)
UNION ALL
SELECT 'course_id -> teacher_id', COUNT(*)
FROM (SELECT course_id FROM flat GROUP BY course_id HAVING COUNT(DISTINCT teacher_id) > 1)
UNION ALL
SELECT 'teacher_name -> teacher_id', COUNT(*)
FROM (SELECT teacher_name FROM flat GROUP BY teacher_name HAVING COUNT(DISTINCT teacher_id) > 1);
fd                          broken_values
--------------------------  -------------
section_id -> course_title              0
course_id -> course_title               0
course_id -> course_code                0
course_id -> teacher_id                15
teacher_name -> teacher_id              1
(5 rows)

The first three hold: a course has one title and one code. course_id -> teacher_id is broken, because the same course is taught by different teachers in different sections. The last line is also broken: one name belongs to two different teachers, so a name is not a safe key.

4. FDs and keys

A column set that determines every other column is called a superkey. A candidate key is a minimal superkey: remove any column from it and it stops determining everything. One candidate key is chosen as the primary key. In emp, emp_id is a candidate key because emp_id -> name, emp_id -> dept_id, emp_id -> dept_name and emp_id -> salary all hold, and one column cannot be made smaller. (emp_id, name) is also a superkey, but not a candidate key, because name adds nothing.

A column that belongs to at least one candidate key is called a prime column; the others are non-prime (non-key) columns. Lessons 5.4 and 5.5 use these words.

Trouble starts with an FD whose left side is not a key: dept_id -> dept_name in emp. dept_id repeats (10 appears twice), so the department name is repeated with it. That is precisely the redundancy of lesson 5.1. The next lessons use FDs to find such cases:

Normal form Problem it removes
1NF cells holding several values
2NF a column depends on only part of a composite key
3NF a column depends on a non-key column
BCNF any FD whose left side is not a key

5. Finding keys: attribute closure

How do you find the candidate keys of a bigger table? Take a set of columns and keep adding every column it determines, using the FDs, until nothing new appears. The result is the closure of the set. If the closure is every column, the set is a superkey.

from itertools import combinations

cols = ["emp_id", "name", "dept_id", "dept_name", "salary"]
fds = [({"emp_id"}, {"name", "dept_id", "salary"}), ({"dept_id"}, {"dept_name"})]

def closure(attrs, fds):
    result = set(attrs)
    changed = True
    while changed:
        changed = False
        for left, right in fds:
            if left <= result and not right <= result:
                result |= right
                changed = True
    return result

def candidate_keys(cols, fds):
    keys = []
    for size in range(1, len(cols) + 1):
        for combo in combinations(cols, size):
            s = set(combo)
            if closure(s, fds) == set(cols) and not any(k <= s for k in keys):
                keys.append(s)
    return keys

print(sorted(closure({"emp_id"}, fds)))
print(sorted(closure({"dept_id"}, fds)))
print([sorted(k) for k in candidate_keys(cols, fds)])
['dept_id', 'dept_name', 'emp_id', 'name', 'salary']
['dept_id', 'dept_name']
[['emp_id']]

From emp_id the closure reaches everything: emp_id gives name, dept_id and salary, and then dept_id gives dept_name. From dept_id it reaches only dept_name, so dept_id is not a key. This brute-force search is fine for small tables and shows exactly what "candidate key" means; a table can have several candidate keys (lesson 5.6 has one).

Worked example: write the FDs

A library table has loan_id, book_id, title, member_id, member_name, loan_date. Real-world rules:

  • Each loan has one book, one member and one date: loan_id -> book_id, member_id, loan_date.
  • A book ID has one title: book_id -> title.
  • A member ID has one name: member_id -> member_name.
  • Title does not determine book ID (two copies may share a title), so title -> book_id is not a rule.

loan_id is the key. book_id -> title and member_id -> member_name have left sides that are not keys, so they mark data to move into books and members tables. Data is made up.

Common mistakes

  • Reading an FD off a small sample. Data can disprove an FD, not prove it.
  • Reading the arrow both ways. A -> B does not mean B -> A.
  • Forgetting that the left side can be several columns.
  • Confusing "determines" with "causes". It only means one value fixes the other.

Key takeaways

  • A -> B means each value of A has exactly one value of B.
  • FDs come from the real-world rules, not from today's rows.
  • GROUP BY a HAVING COUNT(DISTINCT b) > 1 finds rows that break a -> b.
  • A superkey determines every column; a candidate key is a minimal superkey; attribute closure finds them.
  • An FD with a non-key left side signals repeated data and a table to split.

Practice

1. What does isbn -> title mean?

Show answer

Each ISBN has exactly one title; two rows with the same ISBN must have the same title.

2. Does dept_id -> dept_name imply dept_name -> dept_id?

Show answer

No. The arrow is one-way; two departments could share a name in principle.

3. In the emp data, why did dept_id -> salary fail?

Show answer

Department 10 had salaries 500 and 450, and department 20 had 400 and 500, so one department value had several salaries.

4. The query said name -> dept_id holds. Is that a real rule?

Show answer

No. It held only because no two employees shared a name in the sample. Real rules come from the business, and two people can have the same name.

5. Write the query that tests city -> country on a table places.

Show answer

SELECT city FROM places GROUP BY city HAVING COUNT(DISTINCT country) > 1 returns every city that appears with more than one country. No rows means the data does not contradict it.

6. A table (a, b, c) has the FDs a -> b and b -> c. What is the closure of {a}, and is a a candidate key?

Show answer

a gives b, and b gives c, so the closure is {a, b, c}: every column. a is a superkey, and since one column cannot be smaller, it is a candidate key. (b -> c has a non-key left side, which is the warning sign of lesson 5.5: the same c repeats whenever b repeats.)