Constraints, Normalization & Transactions
Lesson opener
In one line: Database design and safety topics from the SQL roadmap that prevent bad data and broken reports.
Why it matters: Without constraints, bad rows slip in - duplicate emails, negative revenue, null segments - and your reports lie quietly until someone notices.
Before this lesson: Window functions
Before you start
| Resource | Link |
|---|---|
| Previous | Window functions |
| Next | Postgres orientation & psql |
| External | SQL roadmap |
Learning roadmap
Interactive roadmap on the website — Learning roadmaps in the sidebar.
What you will learn
Database design and safety topics from the SQL roadmap that prevent bad data and broken reports.

Tutorial 1 — Constraints
[Create customers table with rules]
WHY: Without constraints, bad rows slip in — duplicate emails, negative revenue, null segments — and your reports lie quietly until someone notices.
WHEN: You're designing a new customers table and want the database to reject junk at insert time.
CREATE TABLE customers (
customer_id VARCHAR(10) PRIMARY KEY,
segment VARCHAR(20) NOT NULL,
total_revenue DECIMAL(12,2) CHECK (total_revenue >= 0),
churned SMALLINT DEFAULT 0,
email VARCHAR(100) UNIQUE
);Breaking it down:
PRIMARY KEY (customer_id)→ one unique id per row — no duplicatesNOT NULLon segment → every row must have a segmentCHECK (total_revenue >= 0)→ business rule: revenue can't go negativeDEFAULT 0on churned → new rows assumed active unless specifiedUNIQUEon email → no two customers share the same email
Use this when: You're defining schema so data quality isn't only enforced in the app layer.
| Constraint | Purpose |
|---|---|
| PRIMARY KEY | Unique row identifier |
| NOT NULL | Required field |
| UNIQUE | No duplicates |
| CHECK | Business rule on values |
| DEFAULT | Value if insert omits column |
| FOREIGN KEY | Link to parent table |
[Link sales to customers]
WHY: Orphan order rows with invalid customer_id break joins and inflate "unknown customer" buckets in BI.
WHEN: You add a sales table and need every order to point at a real customer row.
ALTER TABLE sales
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(customer_id);Breaking it down:
ALTER TABLE sales→ modify existing sales tableFOREIGN KEY (customer_id) REFERENCES customers(customer_id)→ sales.customer_id must exist in customers.customer_idfk_customer→ name for the rule — easier to drop or document later
Use this when: Child table (orders) must reference parent table (customers) — referential integrity.
Tutorial 2 — Normalization (3NF intuition)
| Normal form | Idea | Example |
|---|---|---|
| 1NF | No repeating columns | One row per order line |
| 2NF | No partial dependency on part of key | Split order header vs lines |
| 3NF | No transitive dependency | Segment name in segments table, not duplicated on every row |
Lab model: customers + sales is already near star-schema friendly for analytics.
Tutorial 3 — NULL handling in SQL
[COALESCE and NULLIF for clean output]
WHY: NULL segments break charts; zero revenue sometimes means "missing" not "literally zero" — you need display rules in the query.
WHEN: You're exporting customer data for a dashboard that can't handle blank segment labels.
SELECT customer_id,
COALESCE(segment, 'Unknown') AS segment,
NULLIF(total_revenue, 0) AS revenue_or_null
FROM customers;Breaking it down:
COALESCE(segment, 'Unknown')→ replace missing segment with a labelNULLIF(total_revenue, 0)→ turn 0 into NULL — useful when 0 means "no value" for averages
Use this when: Reporting layer needs friendlier NULLs without altering stored data.
Tutorial 4 — Transactions
[Commit or rollback paired updates]
WHY: Half-finished updates — segment changed but paired table not — leave data inconsistent and reports wrong mid-batch.
WHEN: You're promoting customer C0001 to Gold and might need to undo everything if a validation step fails.
START TRANSACTION;
UPDATE customers SET segment = 'Gold' WHERE customer_id = 'C0001';
-- if something wrong:
-- ROLLBACK;
COMMIT;Breaking it down:
START TRANSACTION→ begin an all-or-nothing batchUPDATE ...→ change applies but isn't final until COMMITROLLBACK(commented) → undo all changes in this transactionCOMMIT→ make changes permanent
Use this when: Money, inventory, or multi-table updates must succeed together or not at all.
Use transactions when moving money, inventory, or paired updates across tables.
Tutorial 5 — Indexes (performance basics)
[Speed up joins and filters on big tables]
WHY: Full table scans on millions of sales rows make dashboards timeout — indexes [lookup shortcuts] on filter/join columns help the engine find rows fast.
WHEN: sales grows large and queries filtering by customer_id or month get slow in Workbench.
CREATE INDEX idx_sales_customer ON sales(customer_id);
CREATE INDEX idx_sales_month ON sales(month);Breaking it down:
CREATE INDEX idx_sales_customer ON sales(customer_id)→ faster lookups/joins on customer_idCREATE INDEX idx_sales_month ON sales(month)→ faster filters and sorts on month- Trade-off: slightly slower INSERTs — worth it on large read-heavy tables
Use this when: EXPLAIN shows full scans on columns you filter or join constantly.
Indexes speed up JOIN and WHERE on large tables — trade-off: slower INSERT.
Also cover
- SQL injection: always use parameters in apps; in lab use literals carefully
- EXPLAIN SELECT — preview query plan in Workbench
- RIGHT JOIN / FULL OUTER JOIN — know they exist; LEFT + INNER cover most BI work
Essential commands
| Command / action | What it does |
|---|---|
PRIMARY KEY / FOREIGN KEY | Enforce relationships |
NOT NULL / UNIQUE / CHECK | Data quality at insert |
COALESCE(a,b) | Replace NULL with default |
START TRANSACTION / COMMIT / ROLLBACK | All-or-nothing changes |
CREATE INDEX | Faster lookups on big tables |
Practice
Before each statement, name the three SQL beats — Source → Pattern → Result (SQL translation of Input → Logic → Output — see sql2). For DDL/DML practice, Source is the table you change; Pattern is the constraint / index / transaction form; Result is the rule or durable change you expect.
Do this now:
- Add a
CHECKthat revenue cannot go negative (worked model below — adapt to your practice table). - Create an index on
sales.customer_id. - Run a transaction that updates two rows, then
COMMIT(tryROLLBACKonce in a throwaway run). - Save as
exercises/answers/sql/11_constraints.sql.
Example framing for task 1 (CHECK pattern from Tutorial 1 — on a practice copy of the table, or write the rule into a new sandbox table; do not break the shared lab customers schema):
-- Source: practice customers-like table (total_revenue / revenue column)
-- Pattern: CHECK constraint on create (business rule at insert/update)
-- Result: DB rejects rows where revenue is negative
CREATE TABLE practice_customers_chk (
customer_id VARCHAR(10) PRIMARY KEY,
segment VARCHAR(20) NOT NULL,
total_revenue DECIMAL(12,2) CHECK (total_revenue >= 0),
churned SMALLINT DEFAULT 0
);
-- DROP TABLE practice_customers_chk; -- clean up when doneFraming prompts for the rest (fill these blanks in your .sql comments before each statement):
- Source: ___
Pattern: ___
Result: ___
- Source: ___
Pattern: ___
Result: ___
Checklist
- [ ] I can name 4 constraint types
- [ ] I explained 3NF in one sentence
- [ ] Transaction COMMIT and ROLLBACK tested
- [ ] Next: PostgreSQL