BCA
Relational databases, keys, SQL joins, and transactions
Study map: BCA Semester 2 DBMS; proposed foundational breakdown
A database organises persistent information so it can be queried and updated reliably. A relational model represents data in tables with defined attributes and constraints. Begin by identifying entities and relationships: artists, releases, tracks, and contributions, for example. A many-to-many relationship often needs an association table.
1. Model entities and relationships
A database organises persistent information so it can be queried and updated reliably. A relational model represents data in tables with defined attributes and constraints. Begin by identifying entities and relationships: artists, releases, tracks, and contributions, for example. A many-to-many relationship often needs an association table.
A primary key identifies a row through unique, non-null key values. For a single-column foreign key, a non-NULL value must match an eligible referenced key when enforcement is active. NULL can be allowed unless the column is also declared NOT NULL. For composite foreign keys, the treatment of partly NULL keys depends on the matching mode; require NOT NULL on the columns when every row must have the relationship. Names are often poor identifiers because they can change or repeat. The model should describe business rules rather than merely mimic the layout of an existing spreadsheet.
Further reading: PostgreSQL SQL tutorial
2. Dependencies and normalisation
Repeated information can create update, insertion, and deletion anomalies. If an artist’s contact details appear in every release row, changing one copy but not another creates inconsistency. Normalisation examines dependencies and decomposes tables to reduce such problems while preserving the needed relationships.
First normal form concerns the chosen relational structure and atomic values under its design. Higher normal forms examine key dependencies and other conditions. Do not simply split a table whenever a column repeats. Identify the functional dependencies, candidate keys, and lossless relationships. Performance-oriented denormalisation should be deliberate and justified after understanding the data model.
3. Query, filter, aggregate, and join
SQL queries select columns, filter rows, combine tables, and aggregate values. A join condition specifies which rows are related. An inner join returns matching combinations; a left join can retain unmatched rows from its left input. Duplicates may be legitimate when a relationship has several matches.
For Artists(id,name) and Releases(id,artist_id,title), joining on Artists.id=Releases.artist_id connects each release to its artist. Counting after a many-to-many join can overcount if the unit of analysis is unclear. NULL represents missing or unknown information in SQL’s logic and requires appropriate predicates such as IS NULL rather than ordinary equality.
Further reading: PostgreSQL: joins between tables
4. Transactions and lab practice
A transaction groups work into a unit with defined reliability guarantees. Atomicity means the grouped changes succeed together or are rolled back; consistency concerns preservation of defined rules; isolation governs interaction with concurrent work; durability concerns committed changes surviving relevant failures. Actual isolation behaviour depends on the database and chosen level.
A lab should create related tables, insert representative rows, test constraints, query joins, aggregate results, and demonstrate rollback in a local practice database. Use parameterised statements when applications pass user values. A functioning query is not sufficient if it produces the wrong unit of analysis or leaves integrity unenforced.
Further reading: Transactions
Applied business–computing case: reason, implement and review
Create customer, order and order-line tables with appropriate keys. Separate repeated customer attributes from each line item, then use relationships to reconstruct a view. Normalisation reduces certain update anomalies, but a database still needs constraints and carefully designed transactions.
Simulate reserving the last item for two orders. A read followed by a later update can be unsafe under concurrent activity. Study how a transaction and appropriate database operations preserve the required invariant. Test duplicate identifiers, missing references and a failed multi-step change. Reconcile results after recovery. SQL retrieves and changes records, while the data model supplies meaning and the business owner defines valid states. A successful query is not evidence that the chosen schema answers the correct question.
Transfer practice: prove the reporting grain
Create Customers(customer_id), Orders(order_id, customer_id, amount) and Payments(payment_id, order_id, amount). Use two orders with amounts 100 and 200; give the first order two payments and the second one payment. Before writing SQL, predict the row count and the sum of order amounts after joining Orders to Payments. The direct join contains three rows and repeats the first order amount, producing 400 rather than the order-table total of 300. Payment totals require the actual payment amounts and cannot be inferred from these order amounts.
Compare two reports: aggregate payments to one row per order before joining, or report payment rows while keeping order totals in a separate measure. Explain how a left join retains an unpaid order and how COUNT(*) differs from counting a non-null payment identifier. Test an unmatched order, a duplicate key and a missing customer reference. Record which failures the constraints reject and which require a business rule.
For a final review, distinguish database integrity from reporting meaning. An undergraduate should state keys and query grain; a postgraduate learner should compare aggregation designs and concurrency assumptions; a research learner should investigate how constraints and correction workflows affect error rates. A valid join is only one part of a defensible report.
Study questions and answers
Why can a join increase the number of result rows?
One row may match several rows in the other table. That multiplicity can be correct and must be considered when aggregating.
Why is a transaction useful for transferring an amount between accounts?
The related debit and credit should be treated as a unit so a partial update does not leave an inconsistent result.
Extended practice questions
Explain primary and foreign keys through customers and orders.
A primary key identifies each row uniquely within a table, such as a customer identifier in Customers. An Orders row can contain that identifier as a foreign key referencing its customer. This separates the customer facts from repeated order records while preserving the relationship. A foreign-key constraint can reject an order referencing a nonexistent customer when the database is configured to enforce it. Keys do not establish that names, addresses or business statuses are correct. Define the identifier policy and handling of changes as part of the data model.
Marking guide: Unique identity; referencing relationship; enforcement; correctness limits; identifier policy. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.
Marks: 10
Customers has one row each for C1 and C2. Orders has three C1 orders and one C2 order. How many rows result from an inner join on customer ID, and why?
The join returns four rows: the C1 customer row matches three order rows, and the C2 row matches one. Customer details appear repeatedly because the output grain is one matched order, not one unique customer. Counting all joined rows therefore gives four matched orders, whereas counting distinct customer identifiers gives two customers. The result assumes unique customer keys and exactly the stated valid orders. Duplicate customer records could multiply matches and corrupt totals. Choose the query grain before reporting a business count, and test key assumptions rather than relying on a plausible-looking result.
Marking guide: Four join rows; one-order grain; distincttwo; uniqueness assumptions; multiplication risk. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.
Marks: 10
Critique the statement: normalisation removes every business data problem.
Normalisation helps organise dependencies and reduce certain duplication and update anomalies. It does not guarantee valid customer identifiers, truthful inputs, appropriate access, timely updates or correct business definitions. A well-normalised database can still contain outdated addresses or represent a flawed process. Conversely, a deliberately denormalised analytical view may be useful when its derivation and refresh are controlled. Evaluate schema design with integrity constraints, provenance and actual query needs. The claim fails because structural organisation addresses only part of the broader information-quality and governance problem.
Marking guide: Dependencies/anomalies; missing quality/governance; controlled views; broader assessment. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.
Marks: 10
Frame a research investigation into relational constraints and order-record quality.
Ask whether introducing defined key constraints and an exception workflow reduces invalid customer references in order records. Measure rejected submissions, corrected orders and downstream rework rather than only database error messages. Compare periods or workflows while recording changes in entry forms, training and customer volumes. Investigate whether users bypass the system or substitute misleading identifiers to avoid rejection. The contribution should explain how technical constraints and human correction processes interact. A constraint can prevent one invalid pattern without guaranteeing that the resulting order represents a truthful business event.
Marking guide: Constraint/exception question; quality outcomes; comparison; bypass mechanisms; validity boundary. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.
Marks: 10
An order table is joined to multiple payments per order, and revenue totals rise. Why can the query be wrong even with valid keys?
A one-to-many join repeats the order row once for each matching payment. Summing the repeated order amount inflates revenue even when every key is valid. Define the intended reporting grain and aggregate payments by order before combining them with one order row, or use a query designed for the required measure. Reconcile counts and totals on a small fixture. Finance owns the revenue definition and IT owns query correctness. Valid referential relationships do not guarantee that an aggregate answers the business question.
Marking guide: Join multiplicity; grain; aggregate-before-join; reconciliation; semantic ownership. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.
Marks: 10
Compare a primary key, a foreign key and a business identifier.
A primary key uniquely identifies a row under the table's constraints. For a single-column foreign key, a non-NULL value must match an eligible referenced key when enforcement is active; add NOT NULL if the relationship is mandatory. Composite keys need their matching mode and NULL rules specified separately. A business identifier is a value used in organisational work, such as an order number, which needs its own uniqueness and stability policy. These roles may coincide but should not be assumed equivalent. Constraints can protect structural relationships, while business validity also depends on status, timing and meaning. In SQLite, explicitly check foreign-key enforcement for the connection rather than assuming a declared relationship is always being checked.
Marking guide: Unique row key; referenced relation; business policy; enforcement; validity boundary. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.
Marks: 10
Orders O1=100 and O 2=200; O1 has two payment rows and O 2 one. What is SUM(order_amount) after a direct inner join on these matches?
The joined rows contain O1 twice and O2 once, so summing order amounts gives 100+100+200=400. The order-table total is100+200=300. The extra 100 is duplication caused by join multiplicity, not new revenue. Payment amounts are not supplied, so neither paid total nor outstanding balance can be calculated from this information. A correct report must specify the required grain and appropriate aggregation. This fixture is useful because a hand result exposes the error without relying on the query's apparent syntactic validity or the size of a production dataset.
Marking guide: Joined 400 versus order 300; multiplicity; no payment-total inference; grain. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.
Marks: 10
Design a transaction for moving an amount between two internal balances.
Validate the identifiers, amount and business authority, then perform the debit and credit within one transaction so a failure does not leave only one side applied. Define insufficient-funds behaviour and test rollback after an induced second-step failure using synthetic accounts. Consider concurrent updates and repeated requests under the database's actual isolation and constraint behaviour. A transaction coordinates database changes; it does not automatically cover a separate external payment service. Finance approves the meaning and IT verifies the implementation and recovery evidence. Passing a small fixture is not certification of a production transfer system.
Marking guide: Atomic debit/credit; rollback test; validation/authority; concurrency/repeats; external boundary. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.
Marks: 10
Revision cards
Explain primary and foreign keys through customers and orders.
Customers.customer_id is a unique, non-null primary key. Orders.customer_id references the customer key; enforced foreign keys reject nonexistent references. These relationships do not establish accurate names, addresses or business statuses.
Customers has one row each for C1 and C2. Orders has three C1 orders and one C2 order. How many rows result from an inner join on customer ID, and why?
Four join rows represent matched orders; there are two distinct customers. Declare grain and check unique keys before counting.
An order table is joined to multiple payments per order, and revenue totals rise. Why can the query be wrong even with valid keys?
A one-to-many join repeats order amounts. Match the aggregation grain to the measure; valid keys do not prevent double counting.
Compare a primary key, a foreign key and a business identifier.
Primary key identifies rows; foreign key enforces a declared reference when enabled; business ID serves an organisational identity policy. They may differ.
Orders O1=100 and O 2=200; O1 has two payment rows and O 2 one. What is SUM(order_amount) after a direct inner join on these matches?
Direct joined sum 400; true order total 300. O1 is repeated twice. Payment balances cannot be inferred without payment amounts.
Design a transaction for moving an amount between two internal balances.
Debit and credit must commit together or roll back together. Validate authority and test failure, concurrency and replay; external services need separate coordination.
Why use a primary key instead of a customer name for identity?
Names may repeat or change. A stable key identifies a record and supports relationships. The key does not itself prove that the record describes the correct real person; matching and correction still need review.
What does a local database transaction guarantee within its scope?
It groups the specified local changes into a controlled commit or rollback boundary under the database’s guarantees. It does not automatically make an external payment or email atomic with those changes.
Practice task
Design Artists, Releases, and Tracks tables with keys and constraints. Insert test data, write an inner and left join, count releases per artist, and practise rollback locally.
Sources and further reading
- PostgreSQL SQL tutorial
Type: Free learning material; no paid certificate required
Use: Free primary documentation and query examples. - Joins
Type: Free learning material; no paid certificate required
Use: Study matching and retained rows. - Transactions
Type: Free learning material; no paid certificate required
Use: Work through atomic updates and rollback. - PostgreSQL: primary and foreign-key constraints
Type: Public primary documentation
Use: Check key uniqueness, nullability and referenced relationships.