8. Database Concepts
Opening
Big idea: Related facts become easier to manage when their relationships are part of the design.
Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.
- Explain why duplicated files become difficult to maintain.
- Distinguish a database, a DBMS, a schema and a current state.
- Describe relations and choose keys that reflect the required rules.
Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.
This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.
The previous chapter summarised whole collections with averages and spreads. This chapter asks an earlier question: how should the records themselves be organised so many programs can share them safely?
A summary describes data. A database design protects it.
The chapter builds in five stages. First it separates things from events about those things.
Then it shows why separate files drift apart. Then it introduces the shared software that enforces rules.
Then it presents tables with strict meanings. Last it chooses keys that identify records for years, not days.
One running example threads through every section. A shared device store keeps one record per device: an id, a tag and a category.
Loan records describe borrowing events and refer to devices by id. Watch how each stage treats the same store.
Study by predicting. Cover each expected output and say it aloud first. When a prediction fails, find the first line where your trace diverged. That line holds the lesson. Short sentences carry one idea each.
No database server is needed here. Small Python lists model each idea: a table, a lookup, a duplicate and a dangling reference.
The next chapter uses these ideas to ask questions; this chapter builds the foundation they rest on.
Expect the same vocabulary to return in every section. Thing and event come first, then schema and state, then attribute and domain, then key and reference.
Each term keeps one meaning throughout. When a sentence confuses you, check which term it uses.
Questions in this chapter stay conceptual on purpose. Table names appear, but no query language does.
Learning what a key promises comes before learning how to ask for it. The how belongs to the next chapter.
This one builds the what and the why.
Organisation matters more than storage. Related facts with stated relationships outlast scattered copies.
Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.
8.1 INTRODUCTION
A device is one thing. A loan of that device is an event. If you overwrite the device row every time it is borrowed, you may lose the history of earlier loans.
A database design can keep a device record and separate loan records that refer to it. That lets several events share one stable device description. The relationships become part of the design rather than a repeated note in many files.
- List the main kinds of thing and event in the task.
- Identify each record with a stable key.
- Connect related records through explicit references.
A shared device store needs to know which devices exist and which loans are still open.
A database is an organised collection of related data. A database management system, or DBMS, is software that manages access, storage and operations on that data.
The application uses the DBMS; the three terms are not interchangeable.
Think of a school library. One catalogue card describes each book: its title, author and shelf number.
A separate loan slip records each borrowing: who took which book and when. The card describes a thing.
The slip describes an event about that thing.
A phone shows the same split. One contact entry holds each person: a name and a number.
The call log holds events: who was called and for how long. Deleting the log never deletes the contact.
The two lists serve different purposes.
A record is one stored row about one thing or event. A field is one named kind of fact within it.
A useful design records each fact in an appropriate place. A device record can describe a device, while loan records describe borrowing events.
Repeating a device’s category in every loan can make later corrections difficult.
Read the device table as things and the loan list as events. Each device appears once, however often it is borrowed.
Each borrowing appears as its own loan record that points at the device. History accumulates without rewriting the thing itself.
| Thing or event | Example record | Why separate |
|---|---|---|
| Device (thing) | 21, unit A, tablet. | One stable description shared by all its loans. |
| Loan (event) | Loan 101 borrows device 21. | Each borrowing is its own dated fact. |
| Device (thing) | 24, unit B, laptop. | Its category is stored once, not per loan. |
Read the table. The first column names the kind. The second shows one record. The third states the benefit. Separation lets many events share one description instead of copying it.
Read the diagram. The first box lists what the task involves. The second gives each thing exactly one record. The third connects events to things with references. Only then do questions across both become reliable.
A small Python model shows the lookup idea without any server. Each device is a dictionary. A loop finds the dictionary whose id matches. The id does the identifying; the position in the list does not.
Write down what this program should print before you read the expected output.
devices = [{"device_id": 21, "tag": "unit A", "category": "tablet"}, {"device_id": 24, "tag": "unit B", "category": "laptop"}, {"device_id": 29, "tag": "unit C", "category": "tablet"}]
found = None
for row in devices:
if row["device_id"] == 24:
found = row
print(found["tag"])
print(len(devices))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 builds a list of three dictionaries, one per device. Each dictionary carries the same three fields.
- Line 2 prepares an empty holder for the answer. Lines 3 to 5 check each row in turn and keep the row whose id equals 24.
- Line 6 prints the tag of the kept row: unit B. Line 7 prints the list length: 3. The loop examined every row, but position never decided identity.
unit B
3Search for 29 instead of 24. Predict the printed tag before running.
Read the expected output. Two lines answer two questions: which tag belongs to id 24, and how many devices exist. The first line uses the key. The second counts the list. Neither answer depends on row order.
| Question | Relevant data |
|---|---|
| Which devices are available? | Device records combined with active loan records. |
| Which loans are overdue? | Loan dates, return status and the stated loan policy. |
| How many devices are in each category? | A grouped count of device records. |
Read the table. Each question needs combined facts, not one pile of everything. Availability joins things with events. Overdue joins dates with policy. Counts group one table. Related means combinable by rule.
Why is a spreadsheet with every device and every loan mixed into one repeated row not automatically a good database design?
It may duplicate device facts, lose history during edits, or allow contradictory records.
Result: The logical organisation matters as much as the storage tool.
A store keeps borrower names inside the device record and overwrites them per loan. What breaks first?
Goal. Name what the overwrite destroys.
Approach. Ask whether a thing fact or an event fact is being overwritten.
Trace. The device row holds the thing; each borrower is an event. Overwriting keeps only the latest borrower, so earlier loans vanish from the record.
Result. History is lost, and two loans cannot coexist.
Result: History is lost, because thing facts and event facts share one row.
Sort three facts into thing facts and event facts: tag of unit A, category of unit B, loan 101 borrows device 21.
Goal. Label each fact as thing or event.
Approach. Ask whether the fact describes the device itself or one borrowing.
Trace. The tag and the category describe devices, so they are thing facts. The borrowing describes one event, so it is an event fact.
Result. Two thing facts and one event fact.
Result: Tag and category are thing facts; the borrowing is an event fact.
The same links also answer counting questions. Each loan points at one device, so group the loans by their device.
Device 21 collects two loans, device 24 collects one, and device 29 collects none. The links do the grouping; no extra list is needed.
Try to predict the printed result first. The trace below explains every line.
loans = [(101, 21), (102, 21), (103, 24)]
counts = {}
for loan_id, device_id in loans:
counts[device_id] = counts.get(device_id, 0) + 1
print(len(loans))
print(counts[21])
print(counts.get(29, 0))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three loans as pairs of loan id and device id. Two pairs name device 21.
- Line 2 prepares an empty count per device. Lines 3 and 4 walk the loans and raise the matching device count by one each time.
- Line 5 prints the loan total: 3. Line 6 prints the count for device 21: two loans.
- Line 7 asks for device 29 with a default of zero. No loan names it, so the answer is 0, not an error. Absence is reported, not hidden.
3
2
0Move loan 103 to device 29. Predict all three printed numbers.
Read the expected output. Three loans exist.
Two belong to device 21. Zero belong to device 29.
The zero matters: it distinguishes an idle device from a missing device. Links plus grouping answer which-device questions directly.
Separate things from events, then link them. That separation is the whole design idea.
8.2 FILE SYSTEM
Imagine the same device category appearing in several independently edited files. A correction must reach every live copy. If it reaches only some copies, different reports can give different answers.
This is the connection between redundancy and inconsistency. Repetition creates extra opportunities for disagreement. Deliberate recovery copies are different because they have a controlled purpose rather than competing claims to be the current truth.
- Find facts that are repeated across active files.
- Ask how every copy is kept consistent after a change.
- Decide whether one managed source with controlled sharing would simplify the task.
Separate files can work well until several programs need consistent versions of the same facts.
In a basic file-system approach, each application may control its own files and parsing rules. That can be simple for one task, but shared data introduces coordination problems.
Picture a small shop. Billing keeps one notebook of sales.
Stock keeps another notebook of counts. Both write the device name by hand.
One writes tablet, the other writes tabet. Neither program can tell which spelling is right.
Phone contacts show the milder version. Two family members each store the same shop number differently.
Calling still works, but nobody knows which entry to update when the number changes. One shared entry would end the doubt.
Redundancy is repeated storage of live facts. Inconsistency is disagreement between copies.
| Limitation | Example |
|---|---|
| Difficult access | A new question requires another custom file-processing program. |
| Redundancy | The same device description is copied into several files. |
| Inconsistency | One copy is corrected while another keeps an old category. |
| Isolation | Related facts use different formats or field meanings. |
| Data dependence | A storage-layout change forces changes in several programs. |
| Uncontrolled sharing | Concurrent edits overwrite each other or expose unnecessary data. |
Read the table. Each row names one coordination failure.
Difficult access slows new questions. Redundancy multiplies storage.
Inconsistency multiplies answers. Isolation blocks combining.
Dependence spreads edits. Uncontrolled sharing risks overwrites.
Redundancy is repetition; inconsistency is disagreement. They are related but not identical. A deliberate backup repeats data for recovery, while uncontrolled copies of live facts can produce competing versions.
Three device facts kept in two files need 6 stored copies. Correcting one fact then needs 2 writes, one per file. One shared table would need a single write. The extra write is where drift begins.
The program below counts the damage from one repeated row. Three stored rows hold only two distinct tags. The set of whole rows also holds two members. Counting distinct values exposes the repetition.
Before running the program, say the output in your own words.
rows = [["unit A", "tablet"], ["unit B", "laptop"], ["unit A", "tablet"]]
print(len(rows))
print(len({row[0] for row in rows}))
print(len(set(map(tuple, rows))))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three rows, with the first row repeated exactly. This models one device copied into two files.
- Line 2 prints the stored row count: 3. Storage counts copies, not devices.
- Line 3 collects the first field of each row into a set. Sets drop repeats, so unit A and unit B remain: 2.
- Line 4 converts each row to a tuple so whole rows can enter a set. Two distinct rows remain: 2. Repetition is now measured, not guessed.
3
2
2Append ["unit B", "laptop"] once more. Predict all three printed numbers.
Read the expected output. Stored rows say three. Distinct tags say two. Distinct whole rows say two. The gap between three and two is the redundancy, measured openly.
| Aspect | Separate files | One managed table |
|---|---|---|
| Finding a record | Open each file and reconcile formats. | Ask one source with one meaning per field. |
| Correcting a fact | Repeat the edit in every copy. | Edit once; every reader sees the fix. |
| Two editors at once | Last writer wins silently. | Access rules coordinate the change. |
| Adding a field | Change every program that reads the file. | Extend the plan once with stated rules. |
Read the table. Each row compares the same job in both worlds. Files repeat effort and risk. One table centralises meaning, edits, coordination and change. Small one-task jobs may still suit files.
Read the diagram. The first box is the starting point: each event keeps its own notebook.
The second box names the failure: copies drift. The third box is the repair: one table per thing.
The fourth replaces copying with links.
Two loan files contain different contact details for the same account. What has happened?
Repeated storage created opportunities for separate updates. The records now disagree.
Result: There is inconsistency, probably enabled by uncontrolled redundancy.
A category correction must reach two files, but only one is edited. Which reports disagree afterwards?
Goal. Trace which readers see the old value.
Approach. Count the writes the correction needed versus the writes it received.
Trace. Two files needed 2 writes, but only one happened. Readers of the edited file see the fix; readers of the other file still see the stale value.
Result. Any report built from the unedited file disagrees.
Result: Reports from the unedited file stay stale until it receives its write.
A shop fixes tabet to tablet in billing but forgets stock. A customer asks for all tablets. What goes wrong?
Goal. Predict the customer-facing failure.
Approach. Ask which file each report reads.
Trace. Billing now spells tablet correctly, but stock still holds tabet. A stock report misses the item, so staff say it is missing while billing says it exists.
Result. One correction in one file creates two competing truths.
Result: The stock report misses the item because its copy still holds the old spelling.
These are design risks, not a claim that every file-based system is always wrong. A small documented interchange file can be exactly the right solution for a limited job.
Isolation adds a quieter failure. Billing writes dates as day-first numbers while stock writes month names.
Merging the two files for one monthly report needs manual translation of every date. Different meanings for the same field block combining as surely as different formats do.
A shop restores yesterday backup over the live file after a correct morning of sales. What is lost, and why is this not ordinary redundancy?
Goal. Name what disappears and why the backup behaves differently.
Approach. Ask which copy the shop treats as truth after the restore.
Trace. The restore replaces the live file, so the whole morning of sales vanishes. A backup is a recovery copy with a date, not a competing live truth, but restoring it blindly still discards real work.
Result. One morning of sales is lost; restores need a merge plan, not a blind overwrite.
Result: The morning sales vanish. A backup restores recovery, but only a careful merge preserves new work.
A documented interchange file remains a fair choice for a limited job. One program writes it, the other reads it, and a short note states the delimiter, the date format and the encoding.
Small and documented beats shared and vague when only two programs meet briefly.
Two programs must exchange fee records once a month. Files are acceptable. What makes this file safe?
Goal. List the safeguards a shared file needs.
Approach. Ask what a future reader must know to parse it correctly.
Trace. The note must state the delimiter, the quoting rule, the date format and the encoding. One writer and one monthly reader keep coordination trivial.
Result. A small documented file with one writer and one reader.
Result: Name the delimiter, dates and encoding; keep one writer and one reader.
Copies multiply update work. Every missed copy becomes a competing truth.
8.3 DATABASE MANAGEMENT SYSTEM
A DBMS stands between an application and managed data. Applications make requests through it. The DBMS can check declared constraints, coordinate access and execute the requested operations.
The schema is the plan: tables, fields and rules. The current state is the data presently following that plan. Adding a record normally changes the state without changing the plan.
- Describe the schema separately from sample records.
- Declare rules that the database can check.
- Use application validation and permissions for the remaining task-specific decisions.
A DBMS centralises operations so that shared rules can be enforced consistently.
Two family members share one contacts entry on a synced account. Either can edit, both see the fix, and the history shows who changed what.
One shared entry with rules replaces two drifting copies. That shared entry is the DBMS idea in miniature.
The schema describes the structure and constraints. The database state, sometimes called an instance, is the actual stored content at a particular time.
A schema can stay the same while records are inserted, updated or removed.
The schema is the plan: tables, fields and rules. The state is the content following that plan right now.
The program below proves the split. A tuple names three fields; a list holds the rows. Appending a row grows the state count from 2 to 3 while the schema count stays 3.
Write down what this program should print before you read the expected output.
schema = ("device_id", "tag", "category")
state = [[21, "unit A", "tablet"], [24, "unit B", "laptop"]]
print(len(schema))
print(len(state))
state.append([29, "unit C", "tablet"])
print(len(schema))
print(len(state))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 names the three fields once, as a schema would. The tuple is never appended to.
- Line 2 stores two rows as the current state. Lines 3 and 4 print both counts: 3 fields and 2 rows.
- Line 5 appends one row, modelling an insert. Lines 6 and 7 print both counts again: the schema still holds 3 fields while the state now holds 3 rows.
3
2
3
3Append one more row for device 31. Predict all four printed numbers.
Read the expected output. Four numbers tell a two-part story: the plan is unchanged, the content grew. Inserts change the state. Only a plan edit, such as adding a field, changes the schema.
| Term | Meaning |
|---|---|
| Data model | The concepts used to describe organisation and relationships. |
| Query | A request for data or a derived result. |
| Data definition | Operations that establish or alter structure. |
| Data manipulation | Operations that add, modify or remove stored records. |
| Database engine | The component that executes operations and manages storage. |
Read the table. The first row names the vocabulary of organisation.
The next two rows split defining structure from changing content. The last row names the machinery that executes both.
Use these terms exactly; examiners expect them.
A DBMS can provide integrity checking, controlled access, concurrency management and recovery facilities. These capabilities need configuration and correct application use.
A query written through the DBMS can still contain the wrong business condition.
Read the diagram. The application speaks first with a request.
The DBMS checks the declared rules and executes. Managed records change only through that checkpoint.
The result returns to the application, right or wrong as the question was.
| Aspect | Separate files | Managed database |
|---|---|---|
| Sharing | Each program opens files directly. | All access passes one checkpoint. |
| Rules | Every program reimplements checks. | Constraints are declared once and enforced. |
| Concurrent edits | Last writer wins silently. | Coordination controls overlapping changes. |
| Recovery | Each program arranges its own copies. | Managed backups and restore procedures. |
| Cost | Little setup for small jobs. | Administration, resources and migration effort. |
Read the table. The first four rows favour management for shared work: one checkpoint, declared rules, coordinated edits, planned recovery. The last row is honest about price: management itself needs care and resources.
Classify four facts as schema or state: tag is unique; device 21 is a tablet; loans refer to devices; loan 102 is open.
Goal. Label each fact as plan or content.
Approach. Ask whether the fact constrains all future rows or states one current row.
Trace. Uniqueness of tag constrains every future row, so it is schema. Device 21 being a tablet states one row, so it is state. The reference rule constrains all loans, so it is schema. Loan 102 being open states one loan, so it is state.
Result. Schema, state, schema, state.
Result: Two plan facts and two content facts.
An overdue rule means 14 days, but the application asks for loans older than 7 days. The DBMS returns an answer. Is the answer right?
Goal. Decide whether enforcement guarantees correctness.
Approach. Ask who supplied the business condition.
Trace. The DBMS enforced its declared rules and executed the requested question faithfully. But the question itself used 7 instead of 14, so the result lists loans the policy still calls current.
Result. Enforcement passed; the question failed.
Result: No. The DBMS cannot guess a business rule nobody gave it.
DBMS use also has costs: administration, resource use, migration effort and the impact of a shared service failure. Centralisation can concentrate sensitive information, so permissions and backups remain essential design decisions.
Concurrent edits show why the checkpoint matters. Stock holds 8 units.
Clerk A sells 2 and writes back 6. Clerk B receives 5 and writes back 13.
Both read 8 first, so the second write buries the first. The shelf ends at 13 while the true count is 11.
Coordination, not speed, prevents this lost update.
Two clerks start from stock 8. One sells 2, the other receives 5, and neither sees the other edit. What does the file hold, and what should it hold?
Goal. Compute the stored value and the correct value.
Approach. Apply each edit to the same stale starting point, then to the true sequence.
Trace. The sale gives 6; the receipt gives 13. Whichever writes last wins, so the file holds 6 or 13. Applied in order, 8 minus 2 plus 5 is 11.
Result. The file keeps one edit and loses the other; the correct count is 11.
Result: The file holds 6 or 13 depending on order. Correct coordination gives 11.
Access levels make controlled sharing concrete. A cashier needs stock counts but not supplier costs.
A manager needs both. One shared login cannot enforce that split; named accounts with stated permissions can.
Review the permission list whenever roles change, because stale rights outlive their reason.
The DBMS enforces the design it was given. Correct rules in, reliable sharing out.
8.4 RELATIONAL DATA MODEL
A row combines facts about one represented item or event. A column names one kind of fact shared across rows. The column’s domain says what values are allowed and what they mean.
Display position does not make a row’s identity permanent. A sort can move it. Use a key when you need to refer to that record later. Also distinguish a mathematical relation from an SQL table, where duplicates may be possible.
- Read the column names before interpreting a row.
- Check that each stored value belongs to its intended domain.
- Use identity rules instead of the current screen position to distinguish records.
The relational model represents data through relations with defined attributes.
A library keeps one card per book: title, author and shelf number in fixed positions. Any assistant can read any card because every card shares the same layout.
A relation is that shared layout made strict, with rules attached.
A relation is commonly presented as a table. An attribute is a named column; a tuple is a row.
An attribute’s domain specifies allowed values and meaning. The degree is the number of attributes; the cardinality is the number of tuples.
A relation is a table with named attributes. A tuple is one complete row. The domain fixes what each attribute may hold.
Read the table below row by row. The header names three attributes: device_id, tag and category.
Each later row is one tuple: 21 with unit A and tablet, 24 with unit B and laptop, 29 with unit C and tablet. Every row fills every attribute.
| device_id | tag | category |
|---|---|---|
| 21 | unit A | tablet |
| 24 | unit B | laptop |
| 29 | unit C | tablet |
Read the table again as a relation. Three attributes give degree 3. Three tuples give cardinality 3. Those counts describe this current table, not an unlimited property of all device tables.
In the mathematical relational model, a relation is a set of tuples: duplicate tuples do not occur, and tuple order has no inherent meaning. SQL tables and query results can contain duplicates unless keys or query operations prevent them, so distinguish the model from SQL’s practical behaviour.
Sort the same three devices by tag from Z to A. The first row now holds 29 instead of 21, yet no device changed. Position is presentation; identity lives in the key. The program below shows the reorder explicitly.
Try to predict the printed result first. The trace below explains every line.
rows = [(21, "unit A"), (24, "unit B"), (29, "unit C")]
print(rows[0][0])
by_tag = sorted(rows, key=lambda r: r[1], reverse=True)
print(by_tag[0][0])
print(len(by_tag))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three pairs of id and tag. Line 2 prints the first id in arrival order: 21.
- Line 3 sorts by tag from Z to A without touching the stored list. Unit C now comes first.
- Line 4 prints the new first id: 29. The device did not change; only the display order did. Line 5 confirms all three rows survive: 3.
21
29
3Sort from A to Z instead. Predict the new middle id.
Read the expected output. Arrival order says 21. Tag order says 29. Both orders describe the same three devices. Any program that assumes the first row is special will break on the next sort.
Read the diagram. Cards become columns first: name each attribute.
Then fix allowed values: that is the domain. Then demand identity: a key per row.
Skipping the domain step lets nonsense spellings in; skipping identity lets duplicates in.
Attribute names identify fields; their logical meaning does not depend on display order. A well-designed first-normal-form table holds a single domain value at each row-and-column position rather than a hidden list of unrelated values.
“Atomic” is relative to the chosen domain and operations.
A borrower with two phone numbers needs two contact rows, or two stated fields, but never one comma-joined string. A comma inside a field hides two values where the design promises one.
Queries can no longer count numbers reliably.
| Situation | Degree | Cardinality |
|---|---|---|
| Device table now | 3 | 3 |
| After adding one device | 3 | 4 |
| After adding one field | 4 | 3 |
Read the table. Adding a row raises cardinality to 4. Adding a field raises degree to 4. Rows change cardinality; columns change degree. Never swap the two terms.
A display puts the last device first. Has the logical identity of that device changed?
A row’s position is a presentation choice. A stable key identifies the device.
Result: No. Do not use the current display row number as a permanent identity.
A new row lists category phone, but the domain allows only tablet and laptop. Should the table accept it?
Goal. Decide whether the row enters the relation.
Approach. Compare the stored value with the declared domain.
Trace. The domain for category holds two members: tablet and laptop. The value phone belongs to neither, so it violates the attribute meaning. A device that is genuinely a phone needs a domain change first, with the reason recorded.
Result. Reject the row until the domain officially includes it.
Result: Reject the row. Domains protect meaning, not just spelling.
A loan row stores two borrower ids in one field separated by a comma. Which rule does it break?
Goal. Name the violated rule and give the repair.
Approach. Ask how many domain values one position may hold.
Trace. Each position must hold a single domain value. The comma hides two values in one position, so counts and joins miscount. Two loan rows, or a separate stated link, restore one value per position.
Result. The repair keeps atomic positions everywhere.
Result: It breaks atomicity. One value per position, always.
The device_id domain also carries a meaning rule: only positive assigned integers are allowed. Zero, negatives and text never enter this column.
A wall of red error text is avoided because the rule rejects the row at the door with a plain message.
A fourth device joins the store, then a warranty-months field is added for all devices. Predict the new degree and cardinality.
Goal. State both counts after the two changes.
Approach. Ask which change adds a row and which adds a field.
Trace. The new device raises cardinality from 3 to 4. The new field raises degree from 3 to 4.
Result. Cardinality and degree move independently.
Result: Degree 4, cardinality 4. Rows and fields count different things.
First normal form turns this advice into a test: at every row-and-column position, is there exactly one value from the domain? A fee field holding 120 passes the shape test but fails the domain test.
A phone field holding two numbers fails the shape test. Both rejections protect later queries.
Order displays; keys identify; domains restrict. Each job belongs to a different mechanism.
8.5 KEYS IN A RELATIONAL DATABASE
A label can happen to be unique in today’s tiny sample. That does not prove it is safe as a key. A key needs a rule that continues to identify records when more permitted data arrive.
Sometimes a combination is needed. A device can appear in several slots, and a slot can contain several devices. Their pair can still uniquely identify a reservation if the task allows only one reservation for each pair.
- State the uniqueness rule in ordinary words.
- Choose an attribute set that satisfies it without unnecessary attributes.
- Use a foreign key where a reference must point to a permitted existing record.
A key states which values are sufficient to identify a record under the intended rules.
A shop issues loyalty cards. Two members may share a name, but their card numbers never repeat. Staff ask for the card, not the name, because only the card is guaranteed unique. That card number is a key in daily use.
An order slip names its customer by member number, not by typed name. If the member changes address, old slips still point at the right person. The reference survives edits because it uses the stable key.
A superkey is an attribute set that uniquely identifies tuples. A candidate key is a minimal superkey: removing any of its attributes would lose that identifying property.
Minimal does not mean it has fewer attributes than every other candidate key.
A candidate key is minimal: drop any attribute and identification fails. The primary key is the chosen candidate.
The primary key is the chosen candidate key. Other candidate keys are alternate keys.
A composite key uses more than one attribute. For example, a reservation identified by device_id together with slot_id needs both when neither field alone identifies a reservation.
Three devices and two slots allow 6 possible reservation pairs. With 2 pairs booked, 4 remain free. Neither device_id nor slot_id alone identifies a reservation, but their pair does under the one-booking-per-pair rule.
| Entity or event | Possible key | Reason |
|---|---|---|
| Device | device_id | A stable assigned identity for each device. |
| Time slot | slot_id | One identity for each scheduled slot. |
| Reservation | device_id + slot_id | The policy permits at most one reservation per device and slot. |
Read the table. The first two rows give single-attribute keys for things. The third row combines them for the event. The reason column states the rule each key enforces. Keys always encode a policy, never just a shape.
A foreign key links referencing attributes to a permitted unique key in another or the same table. It supports referential integrity: an ordinary non-null reference must correspond to an allowed referenced value.
Optional references, deletion actions and update actions require explicit rules.
The program below tests uniqueness the way a primary key demands. Three ids start unique. Appending 24 breaks that property, and the check turns False. Four entries remain, but they no longer identify four devices.
Before running the program, say the output in your own words.
ids = [21, 24, 29]
print(len(ids) == len(set(ids)))
ids.append(24)
print(len(ids) == len(set(ids)))
print(len(ids))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three distinct ids. Line 2 compares the list length with its set length: equal means unique, so True.
- Line 3 appends 24 again, modelling a duplicate entry. Line 4 repeats the test: 4 entries but only three distinct, so False.
- Line 5 prints the entry count: 4. Counting entries cannot reveal the duplication; comparing with the set can.
True
False
4Append 30 instead of 24. Predict all three printed lines.
Read the expected output. True means the key property holds. False means it broke. Four counts entries, not devices. A primary key must keep answering True for every permitted future insert, not just today.
The loan check below models referential integrity. Three loans name devices; the device set holds 21, 24 and 29. One reference points at 30, which does not exist. The filter catches exactly that loan.
Write down what this program should print before you read the expected output.
devices = {21, 24, 29}
loans = [(101, 21), (102, 24), (103, 30)]
bad = [loan for loan in loans if loan[1] not in devices]
print(len(loans))
print(len(bad))
print(bad[0][1])Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores the permitted device ids as a set. Line 2 stores three loans as pairs of loan id and device id.
- Line 3 keeps every loan whose device is absent from the set. Only loan 103 qualifies.
- The prints show 3 loans, 1 dangling reference, pointing at 30. That reference must be rejected or the loan would describe a device that does not exist.
3
1
30Point loan 103 at device 29 instead. Predict all three printed numbers.
Read the expected output. Three loans entered. One failed the reference test. The failing value is 30. In a managed database the foreign key would reject this loan before it is stored.
Read the diagram. State the wanted key first. Scan for a match. Return the whole record on success. Reject explicitly on failure instead of inventing a row. Every key lookup in any system follows these four steps.
Read the diagram. The loan arrives naming a device. The device table is consulted before anything is stored. The loan is accepted or rejected on evidence. History then stays linked to real devices only.
| Key kind | Meaning | Device-store example |
|---|---|---|
| Superkey | Identifies every tuple, perhaps with spare attributes. | device_id plus tag together. |
| Candidate key | Minimal superkey; no attribute can be dropped. | device_id alone, or tag alone. |
| Primary key | The candidate chosen for everyday reference. | device_id. |
| Alternate key | A candidate not chosen as primary. | tag, still kept unique. |
| Foreign key | A reference to a permitted key elsewhere. | Loan device_id pointing at device_id. |
Read the table. Each row tightens the idea: from any identifying set, to minimal sets, to the chosen one, to the spares, to references between tables. The example column keeps one store running through all five rows.
Predict the output before running this complete example.
rows = [("unit A", "slot P"), ("unit A", "slot Q"), ("unit B", "slot P")]
print(len({row[0] for row in rows}) == len(rows))
print(len({row[1] for row in rows}) == len(rows))
print(len(set(rows)) == len(rows))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The first set collects distinct values from the first field.
- The second set does the same for the second field.
- The set of whole tuples keeps combinations. Comparing sizes checks uniqueness in this sample.
False
False
TrueAdd a repeated complete pair and see which uniqueness check changes.
Read the output with the reservation rule in mind. Unit A appears twice, so tags alone do not identify rows.
Slot P appears twice, so slots alone fail too. Whole pairs are all distinct, so the composite holds.
Observed counts support the rule; the rule itself comes from the task.
Observed uniqueness in a small sample does not prove a field will be a valid future key. The key must follow the business rule.
A name that happens to be unique today can be repeated tomorrow; an assigned stable identifier can avoid that assumption.
A booking rule allows at most one reservation per device and slot. Which attribute set identifies a reservation?
Goal. Choose a key that the rule guarantees.
Approach. Test each candidate against permitted future rows.
Trace. Device 21 can appear in slots P and Q, so device_id alone repeats. Slot P can hold devices 21 and 24, so slot_id alone repeats. The pair never repeats under the stated rule, and dropping either half breaks identification.
Result. The composite device_id plus slot_id is the candidate key.
Result: The pair device_id plus slot_id, minimal and sufficient.
A loan names device 30, but the device table holds only 21, 24 and 29. What should happen on insert?
Goal. Decide the fate of the new loan.
Approach. Ask whether the reference matches a permitted existing key.
Trace. The device set contains three ids; 30 is not among them. Storing the loan would create history about nothing. The foreign key rule exists exactly for this moment.
Result. Reject the insert and report the missing device.
Result: Reject it. A reference must point at a permitted existing record.
A designer proposes the tag as primary key because all three current tags differ. What is the risk?
Goal. Test the proposal against future rows.
Approach. Ask what the business guarantees about tags.
Trace. Today tags are unique by accident of a tiny sample. Nothing stops a fourth device reusing a tag after a rename, while device_id is assigned never to repeat. Accident is not a rule.
Result. Keep device_id primary; keep tag unique as an alternate key.
Result: Sample uniqueness is not a guarantee. Choose the assigned stable identifier.
A key is a promise about future rows, not a summary of past rows.
Summary
Use these points to test what you can explain without looking back.
- A DBMS manages a database for applications.
- Uncontrolled duplication can create inconsistency and update problems.
- The schema defines structure; the state holds current records.
- Relations contain attributes and tuples; degree counts attributes and cardinality counts tuples.
- Candidate keys are minimal identifying attribute sets; a primary key is the selected candidate.
- Composite keys use several attributes; foreign keys express referential rules.
- A key must reflect permitted future data, not just one sample.
- Separate files repeat live facts; missed copies become competing truths.
- A domain allows only meaningful values; display order never identifies a record.
- Foreign keys reject references to missing keys, subject to the declared nullability rules.
- Links let one question span things and events, such as counting loans per device.
- Lost updates happen when two editors write from the same stale read; coordination prevents them.
Exercise
Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.
8.1 Give one schema fact and one state fact for a device database.
8.2 Explain a redundancy problem without claiming all copies are bad.
8.3 Can a relation have several candidate keys?
8.4 Does minimal key mean the candidate with the fewest columns among all candidates?
8.5 Design a key for a rule allowing at most one booking per account and time slot.
8.6 A booking references an account that does not exist. Which rule should reject it?
8.7 Does a table’s display order identify records permanently?
8.8 Explain one cost of adopting a DBMS.
8.9 Why can SELECT results contain duplicates even though a mathematical relation is a set?
8.10 Why is an account label that is unique in one sample not automatically a safe primary key?
8.11 A table holds device ids [21, 24, 29]. Trace a lookup for id 24 step by step.
| Step | Action | Result |
|---|---|---|
| 1 | Compare 24 with 21. | No match; continue. |
| 2 | Compare 24 with 24. | Match; stop scanning. |
| 3 | Return the full record. | unit B, laptop. |
8.12 Predict the output of the duplicate-count program.
rows = [["unit A", "tablet"], ["unit B", "laptop"], ["unit A", "tablet"]]
print(len(rows))
print(len({row[0] for row in rows}))
print(len(set(map(tuple, rows))))8.13 A loan for device 30 arrives when devices are {21, 24, 29}. Name the fault and the repair.
devices = {21, 24, 29}
loan = (104, 30)8.14 A show allows one seat per member per show. Design the key without reusing the chapter example.
| Candidate | Verdict |
|---|---|
| member_id alone | Repeats across shows; fails. |
| show_id alone | Repeats across members; fails. |
| member_id + show_id | Minimal and sufficient under the rule. |
8.15 State whether each change alters schema or state: add a member, add a phone field, borrow a book, drop the loan table.
8.16 Two clerks edit fee records in separate files while a DBMS alternative exists. Which design fits and why?
8.17 Three loans reference devices 24, 24 and 29. How many reference device 24, and how many reference device 21?
8.18 A category field with domain {tablet, laptop} receives phone. Should it store? Explain.
Answers
8.1 Schema: device_id is a primary key. State: a particular device record is currently stored.
8.2 Repeated live descriptions can disagree after partial updates; a managed recovery backup serves a different purpose.
8.3 Yes. Several different minimal attribute sets can each uniquely identify a tuple.
8.4 No. It means no proper subset of that candidate is still a superkey.
8.5 The pair account_id and slot_id can be a composite candidate key under that rule.
8.6 A suitable non-null foreign key referencing the account key.
8.7 No. Use an appropriate stable key.
8.8 It needs administration, resources and planned changes; poor configuration can concentrate risk.
8.9 SQL commonly uses bag-like result semantics unless keys or operations such as DISTINCT remove duplicates.
8.10 Future permitted records may reuse the label; the business rule must guarantee its uniqueness and stability.
8.11 Two comparisons. The scan stops at the match and returns unit B with laptop; id order, not position, guided it.
8.12 3, then 2, then 2. Three stored rows hold two distinct tags and two distinct whole rows.
8.13 Dangling reference: 30 matches no permitted device key. Reject the loan until device 30 exists or correct the id.
8.14 The composite member_id plus show_id. Neither half alone identifies a booking; the pair does.
8.15 State, schema, state, schema. Row changes touch content; table and field changes touch the plan.
8.16 The DBMS fits: one checkpoint enforces rules, coordinates concurrent edits and keeps one current truth.
8.17 Two reference device 24. Zero reference device 21. Group by the reference and report absence as zero.
8.18 No. The value lies outside the declared domain, so the insert is rejected until the domain officially changes.