Sub topic 11
Finding Candidate Keys from Functional Dependencies
Prerequisites and the Working Model
Assume you know basic set notation, tables, attributes, and introductory SQL. A functional dependency (FD) X → Y says that matching values of attribute set X must have matching values of attribute set Y.
A superkey is an attribute set that determines every attribute in the relation. A candidate key is a minimal superkey: removing any attribute from it makes it stop determining the whole relation.
For a relation R(A, B, C, D, E), write X+ for the attribute closure of X. The closure is every attribute that can be determined from X using the given FDs. If X+ = {A, B, C, D, E}, then X is a superkey. It is a candidate key only if no proper subset of X has the same property.
A Reliable Procedure
Use this process:
- Start with attributes that cannot be derived from any FD right-hand side. Such attributes must occur in every candidate key.
- Add other attributes one at a time.
- Compute the closure of each promising set.
- Keep a set when its closure contains all relation attributes.
- Test minimality by removing each attribute and recomputing the closure.
- Continue searching for other minimal combinations. Finding one key does not prove that it is the only key.
The closure algorithm repeatedly applies an FD when its entire left side is already in the current set.
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
fds = [
({"A"}, {"B"}),
({"B"}, {"C"}),
({"C", "D"}, {"E"}),
]
print(sorted(closure({"A", "D"}, fds)))
# ['A', 'B', 'C', 'D', 'E']Here, AD+ contains every attribute, so AD is a superkey. A+ lacks D and E, and D+ contains only D; therefore AD is minimal and is a candidate key.
Worked Example
Let R(A, B, C, D, E) have:
A → BB → CCD → E
A and D never appear on a right-hand side, so every candidate key must contain both. Compute:
AD+ = {A, D} Using A → B, add B. Using B → C, add C. Using CD → E, add E.
Thus AD+ is the whole relation. Since neither A nor D alone determines all attributes, AD is a candidate key.
Common Errors
- Treating every superkey as a candidate key.
- Checking only one possible key.
- Applying
CD → Ewhen onlyCis known. - Assuming attributes on right-hand sides cannot belong to a candidate key. They may be needed in another minimal combination.
Exercise
For R(A, B, C, D) with FDs A → B, B → C, and C → D, what is the candidate key?
Show answer
A. Its closure is {A, B, C, D}, while the empty set has no determining attributes.