Skip to main content
Albero Academy

Views, Transactions & Best Practices

Save queries as views, guarantee all-or-nothing changes with transactions, and finish with the habits of professional SQL.

Chapter 16SQL15 min readBeginner friendly
  • #SQL
  • #Views
  • #Transactions

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:

a reusable view
CREATE VIEW placed_students AS
SELECT s.name, s.package, p.name AS programme
FROM students s
JOIN programmes p ON s.programme_id = p.id
WHERE 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:

all-or-nothing
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:

PropertyMeans
AtomicityAll statements succeed or none do
ConsistencyConstraints are never left violated
IsolationConcurrent transactions don't corrupt each other
DurabilityCommitted data survives a crash

Best practices

  • Select only the columns you need — avoid SELECT * in production code.
  • Always scope UPDATE/DELETE with a WHERE; preview with SELECT.
  • 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

  1. 01A view is a saved query you can query like a table — hides complexity, centralises logic.
  2. 02Transactions (BEGIN … COMMIT/ROLLBACK) make grouped changes all-or-nothing.
  3. 03ACID = Atomicity, Consistency, Isolation, Durability — the reliability guarantees.
  4. 04Best practice: scoped writes, no SELECT *, DB-enforced integrity, sensible indexes.
  5. 05Always use parameterised queries from app code to prevent SQL injection.