BCA
Database management systems for dependable records
Study map: Original foundation and applied lesson; editorially linked to the named subject
A database management system stores and controls shared records. This chapter uses orders, delivery attempts and payment records to show why row grain and keys matter, how joins can inflate totals, and what a database transaction can roll back. The runnable exercise uses an in-memory SQLite database; linked PostgreSQL pages provide concept-specific further reading.
Foundation: structure dependable records
A database management system provides mechanisms for storing, querying and controlling shared records. A relational design represents entities and relationships through tables and keys. An order table might contain one row per order, while an order-line table contains several rows per order. The distinction is its grain. Before writing SQL, describe what one row means and which facts belong to that row. This makes the schema a model of the organisation rather than a collection of convenient spreadsheet columns.
A primary key identifies a row; a foreign key can express a reference to another table; a constraint limits permitted values. The design should reflect the business rule it intends to protect. A stable order identifier is usually more suitable than a customer's display name because names can change and need not be unique. A valid reference confirms a structural relationship, not that the underlying customer or transaction is genuine.
Finance depends on reliable amounts, operations on correct status transitions, sales on usable customer records and IT on maintainable schema and access. Managers must approve the meaning of these records. The database cannot infer whether a promised delivery date was agreed fairly or whether an employee should be allowed to override it. Human responsibility remains part of the system.
In standard relational SQL, a primary key uniquely identifies each row and its columns cannot be NULL. A key can combine several columns when their combination identifies the row. A foreign key references an eligible unique or primary key; whether NULL is permitted depends on the referencing column constraints. Check the particular database engine’s documented behaviour, since implementations have exceptions.
Undergraduate: keys, joins and a worked multiplicity example
Take orders O1 worth 10,000 paise and O2 worth 20,000 paise. O1 has delivery attempts one and two; O2 has attempt one. A join produces three rows: O1/1, O1/2 and O2/1. SUM(order amount) after that join is 40,000 paise because O1 is repeated. The order-level total is 30,000. This is a predictable consequence of a one-to-many relationship, not a random database bug.
Choose a query that answers the intended question. Aggregate orders independently for order value. Aggregate attempts independently for delivery activity. If combining results, preserve their grain deliberately. SUM(DISTINCT amount) is not a general repair: two different orders can legitimately have the same amount, and the distinct-value calculation would then remove a valid contribution. Deduplicate using the identity and semantics of the record rather than whichever expression produces the expected number.
In the companion exercise, orders have a primary key, required customer and amount fields, and a positive-amount check. A repeated identifier with identical values is treated as a replay by application logic. A repeated identifier with different values is quarantined for review. The positive constraint fits this synthetic order model; it would not fit every representation of returns. Validation rules require an explicit domain definition.
Postgraduate: transactions protect a bounded change
A transaction groups changes into a unit that can commit or roll back. In the exercise, the program attempts to insert a valid new order followed by a negative-amount order. The second insert violates the constraint, and the valid insert is also rolled back because both belong to the same transaction. The accepted total therefore remains 30,000 paise. If the two inserts were committed separately, the valid first change would remain even after the second failed.
This boundary matters for a business operation whose steps must succeed together. Yet a transaction in one database does not automatically control an external email, a payment provider or a separate database. Define the system boundary and design recovery for external effects. Do not claim an all-or-nothing organisational workflow merely because one SQL block uses a transaction.
Concurrency creates additional questions about which changes a reader can observe and whether competing updates preserve an intended rule. Study the chosen database's isolation behaviour rather than assuming every system handles it identically. Indexes can improve some queries while increasing storage and update work; evaluate workloads rather than declaring that more indexes always improve performance. Database administration includes backup recovery, access and monitoring, beyond writing a correct SELECT statement.
Research: evaluate a schema as a socio-technical choice
A study could examine whether stable identifiers and constraints reduce reconciliation errors across departments. The research design must account for changes in recording and detection. A new constraint might reduce accepted invalid rows while increasing exception workload. Report both outcomes and investigate whether users bypass the system through spreadsheets or undocumented messages.
Compare the process before and after the change or use an appropriate concurrent comparison. Record case mix, correction procedures and time to resolve exceptions. Explain why the reference used to judge correctness is reliable for the particular claim. A database accepting all rows is not evidence of accurate data, and a database rejecting many rows is not automatically poorly designed.
The contribution can concern a mismatch between a business workflow and its schema, a correction mechanism or the limits of a technical constraint. For a portfolio, submit the entity description, row grain, key choices, three queries, rollback evidence and limitation note. Separate an implementation that behaves correctly on test cases from a design that fits the full organisation.
Practice and free reference sequence
Run the standard-library records_pipeline.py exercise without installing a database server. Inspect its CREATE TABLE statement, parameterised INSERT commands and transaction boundary. Predict what remains after the failed batch, then compare the naive join with the original order total. Change one order amount so that two orders have equal values and explain why SUM(DISTINCT amount) would be inappropriate.
The executable uses SQLite in memory. The linked PostgreSQL constraints and transactions pages are further readings, not evidence that this script is a PostgreSQL implementation. Learn the concepts, then check syntax and behaviour in the actual system you choose. The practice database disappears at program exit; persistence, recovery, multiple users and distributed coordination remain outside this lab.
Further reading: PostgreSQL: constraints
Study questions and answers
Distinguish a primary key from a foreign key.
A primary key uniquely identifies a row using one or more non-null columns. A composite primary key uses a combination of columns. A foreign key constrains a reference to an eligible key in another or the same table. These protect structural rules, not the factual truth of every field. Indicative marking: Primary key 3; foreign key 3; example 2; truth boundary 2.
Why is SUM(DISTINCT amount) not a general repair for duplicated order values after a join?
Distinct operates on values, not order identities. Two different orders can have the same amount and both must count. Preserve the order grain or aggregate before joining instead. Indicative marking: Value/identity distinction 3; counterexample 3; repair 2; interpretation 2.
A batch inserts one valid order then an invalid order in one transaction. What should remain after rollback?
Neither new order remains. In the lab the positive-amount constraint rejects the second insert, and the transaction rolls back the valid first insert too. The original total remains 30,000 paise; effects outside that database are outside this guarantee. Indicative marking: Rollback result 3; reason 3; total 2; boundary 2.
How would you evaluate new database constraints across departments?
Measure invalid accepted records and exception workload with consistent definitions and a justified comparison. Investigate bypasses, detection changes and correction delay. Technical rejection counts alone do not establish better organisational outcomes. Indicative marking: Outcomes 3; comparison 3; behavioural mechanisms 2; limitation 2.
Extended practice questions
Distinguish a primary key from a foreign key.
A primary key uniquely identifies a row using one or more non-null columns. A composite primary key uses a combination of columns. A foreign key constrains a reference to an eligible key in another or the same table. These protect structural rules, not the factual truth of every field.
Marking guide: Primary key 3; foreign key 3; example 2; truth boundary 2.
Marks: 10
Why is SUM(DISTINCT amount) not a general repair for duplicated order values after a join?
Distinct operates on values, not order identities. Two different orders can have the same amount and both must count. Preserve the order grain or aggregate before joining instead.
Marking guide: Value/identity distinction 3; counterexample 3; repair 2; interpretation 2.
Marks: 10
A batch inserts one valid order then an invalid order in one transaction. What should remain after rollback?
Neither new order remains. In the lab the positive-amount constraint rejects the second insert, and the transaction rolls back the valid first insert too. The original total remains 30,000 paise; effects outside that database are outside this guarantee.
Marking guide: Rollback result 3; reason 3; total 2; boundary 2.
Marks: 10
How would you evaluate new database constraints across departments?
Measure invalid accepted records and exception workload with consistent definitions and a justified comparison. Investigate bypasses, detection changes and correction delay. Technical rejection counts alone do not establish better organisational outcomes.
Marking guide: Outcomes 3; comparison 3; behavioural mechanisms 2; limitation 2.
Marks: 10
Finance reports zero net payment difference, but two customers dispute their balances. Explain a possible cause.
A net sum can hide offsetting exceptions. In the fixture O2 has an outstanding 5,000 paise while O3 has an excess 5,000; their combined difference is zero although neither is matched. Reconcile by order before combining totals and retain direction, references and source evidence. Finance owns allocation decisions, customer service investigates the dispute and the data team validates grain. The result is not a bank reconciliation and omits timing and recognition policy. Do not contact or refund customers solely from the synthetic difference.
Marking guide: Offsetting exceptions;order grain;responsibility and scope.
Compare a foreign key with a complete business-validity check.
A foreign key checks a specified relationship between stored records when enforcement is enabled. It can reject an order referencing an absent customer. It cannot establish that the present customer is the correct one, that the transaction actually occurred or that approval was authorised. Required references also need a null policy; this schema explicitly requires them. The database supports the agreed contract while business owners and stewards investigate meaning and evidence. A technically accepted row may remain unsuitable for a released report.
Marking guide: Relationship versus truth;enforcement/null policy;human evidence.
Three order amounts are 10,000, 20,000 and 30,000 paise. The first order has two payment rows and each of the other two has one. What does summing order amounts after joining orders to payments produce?
The first order appears twice, producing 10,000 + 10,000 + 20,000 + 30,000 = 70,000 paise instead of the order-table total 60,000. The join changes result grain to order-payment pairs. Aggregate payments to one row per order before joining, or calculate order value directly at order grain. SUM(DISTINCT amount) is not a general repair because separate orders can have equal amounts. Define whether the business report means orders, invoicing or recognised revenue before presenting the corrected amount.
Marking guide: 70,000 versus60,000;grain;distinct shortcut;business definition.
An operation inserts an order and then a payment with an invalid reference. Explain the required recovery.
Treat the two writes as one intended business operation with an explicit transaction boundary. If the payment insert violates its foreign key, the transaction should roll back the first write so the system does not retain a half-completed operation. The SQLite lesson demonstrates this with OX and confirms that OX is absent afterwards. A rejected statement alone does not establish that earlier writes were undone. Production recovery also needs durable evidence and retry policy; a local database transaction cannot guarantee atomicity with an external payment service.
Marking guide: Multi-write rollback;absence proof;external-system boundary.
Revision cards
Why specify the grain before designing a database table?
The grain identifies what one row represents, such as an order or order line. It guides keys and relationships. Mixed grains can duplicate totals or hide details even when the database accepts every row.
What can a foreign-key constraint prevent?
It can reject a reference that violates the specified relationship to existing keys. It does not establish that the selected real-world entity is correct or that every business relationship has been modelled appropriately.
Why test transaction rollback with a deliberately failed operation?
A bounded failure can reveal whether grouped local updates leave partial state. Inspect the resulting records, not only an error message. External effects still need separate coordination beyond the tested database boundary.
How does a primary key differ from a business identifier?
A primary key identifies database rows under enforced rules; a business identifier carries domain meaning and may change or need separate validation. They can coincide, but do not assume they must. Stable technical identity does not certify real-world uniqueness.
Why does referential integrity not prove a transaction is legitimate?
A foreign-key constraint can ensure a referenced row exists, but cannot establish authorisation, eligibility or factual truth. A structurally valid relationship may still be inappropriate. Apply relevant business and access rules alongside database constraints.
What problem does normalisation address?
It organises dependencies to reduce certain redundancy and update anomalies. It does not guarantee fast queries or perfect real-world modelling. Explain the functional dependencies and intended operations before applying a normal form as a mechanical design badge.
Why choose an isolation level with the actual workload in mind?
Isolation affects which concurrent behaviours an application can observe and the tradeoffs of coordination. Requirements differ between reporting and critical updates. Test the relevant anomalies and database semantics rather than treating a level name as a universal guarantee.
How should a database migration protect existing meaning?
Verify how old records map to the new structure, including defaults, exceptions and dependent applications. Preserve a recovery plan and test representative cases. Successfully changing the schema does not establish that existing facts retained their intended interpretation.
Why can an index slow some database operations?
Maintaining it adds work when indexed records change and consumes storage. Its benefit depends on the query and workload. Evaluate representative reads and writes rather than assuming more indexes always improve the system.
What does a successful database restore test establish?
It demonstrates the inspected recovery outcome under specified conditions, including usable data and relevant application behaviour. A completed restore command alone is weaker evidence. Record timing, exclusions and whether the intended recovery objective was met.
Practice task
Follow information-workshop.html: predict and run the pipeline, reconcile classifications, explain the inflated join, and submit a metric contract, exception policy and managerial memo.
Sources and further reading
- Shared records workshop
Type: Original practical teaching
Use: Chapter-specific runnable exercise and evidence requirements - Python CSV documentation
Type: Free official documentation
Use: Parsing, quoting and deliberate type conversion - PostgreSQL constraints
Type: Free official documentation
Use: Structural record rules; the local runnable exercise uses SQLite - PostgreSQL transactions
Type: Free official documentation
Use: Further reading on bounded commit and rollback