Sub topic 10
Computing Attribute Closure
Assume you know tables, attribute sets, and functional dependencies (FDs). An FD written as X → Y means that whenever two rows agree on every attribute in X, they must also agree on every attribute in Y.
The attribute closure of X, written X⁺, is the set of all attributes that X determines using a given set of FDs. Attribute closure helps you test whether X is a superkey, find candidate keys, and determine whether an FD follows from other FDs.
The Closure Algorithm
Start with the attributes in X. Repeatedly apply any FD whose left side is already contained in the current result. Add its right-side attributes. Stop when no new attribute can be added.
Consider relation R(A, B, C, D, E) with these FDs:
A → BB → CCD → E
To compute {A, D}⁺:
- Start with
{A, D}. A → Bapplies, so addB.B → Capplies, so addC.CD → Eapplies because bothCandDare present, so addE.- No FD adds anything else.
Therefore, {A, D}⁺ = {A, B, C, D, E}. Since the closure contains every attribute in R, {A, D} is a superkey. If neither A nor D can be removed while preserving this property, it is also a candidate key.
A Runnable Implementation
The following program represents each left and right side as a set. The loop continues until a complete pass makes no change.
def closure(attrs, fds):
result = set(attrs)
changed = True
while changed:
changed = False
for lhs, rhs in fds:
if lhs <= result and not rhs <= result:
result |= rhs
changed = True
return result
fds = [
({"A"}, {"B"}),
({"B"}, {"C"}),
({"C", "D"}, {"E"}),
]
print(sorted(closure({"A", "D"}, fds)))
# ['A', 'B', 'C', 'D', 'E']Common Errors
| Error | Why it is wrong | Correct approach |
|---|---|---|
| Applying `CD → E` when only `C` is known | Every attribute on the left side is required | Wait until both `C` and `D` are present |
| Stopping after one pass | A newly added attribute may enable another FD | Repeat until the result no longer changes |
| Calling every superkey a candidate key | A candidate key must be minimal | Test whether removing any attribute still determines all attributes |
A closure can also test FD implication. An FD X → Y follows from the given FDs exactly when every attribute in Y belongs to X⁺.
Exercise
For R(A, B, C, D) with FDs A → B and B → C, what is {A, D}⁺?
Show answer
{A, B, C, D}. A determines B, B determines C, and D is included from the start.