The final chapter covers two professional tools — views for reusing complex queries and transactions for guaranteeing data consistency — then the habits that make SQL maintainable. You'll finish with the full toolkit of a confident SQL practitioner.
Views
A view is a saved query that you can query like a table. It hides complexity behind a simple name and keeps logic in one place:
CREATE VIEW placed_students ASSELECT s.name, s.package, p.name AS programmeFROM students sJOIN programmes p ON s.programme_id = p.idWHERE s.placed;-- Now query it like a table:SELECT * FROM placed_students WHERE package > 8;-- A materialized view stores the result for speed (refresh it periodically).
Transactions
A transaction groups statements so they all succeed or all fail together. COMMIT makes them permanent; ROLLBACK undoes them — essential when one change depends on another:
BEGIN;UPDATE accounts SET balance = balance - 5000 WHERE id = 1;UPDATE accounts SET balance = balance + 5000 WHERE id = 2;COMMIT; -- both applied together; if either fails, ROLLBACK undoes both
ACID
Transactions give databases their reliability guarantees, summarised as ACID:
| Property | Means |
|---|---|
| Atomicity | All statements succeed or none do |
| Consistency | Constraints are never left violated |
| Isolation | Concurrent transactions don't corrupt each other |
| Durability | Committed data survives a crash |
Best practices
- Select only the columns you need — avoid
SELECT *in production code. - Always scope
UPDATE/DELETEwith aWHERE; preview withSELECT. - Let the database enforce integrity (keys, constraints); index for your real query patterns.
- Use parameterised queries from application code — never concatenate input (SQL injection; see the Cybersecurity course).
- Format and comment complex queries; use CTEs to make them readable.
Practice
Create a placed_students view and query it. Wrap a two-step balance transfer in a transaction and test a ROLLBACK. Then review an earlier query against the best-practices list — scoped writes, no SELECT *, readable CTEs. You've now completed SQL end to end.
Key takeaways
- 01A view is a saved query you can query like a table — hides complexity, centralises logic.
- 02Transactions (BEGIN … COMMIT/ROLLBACK) make grouped changes all-or-nothing.
- 03ACID = Atomicity, Consistency, Isolation, Durability — the reliability guarantees.
- 04Best practice: scoped writes, no SELECT *, DB-enforced integrity, sensible indexes.
- 05Always use parameterised queries from app code to prevent SQL injection.
