Rana Maninder Singh
Lesson 11 of 11SQL & DBMS (MySQL)

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


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.

Types of databases
Types of databases

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:

Use this when: You're defining schema so data quality isn't only enforced in the app layer.

ConstraintPurpose
PRIMARY KEYUnique row identifier
NOT NULLRequired field
UNIQUENo duplicates
CHECKBusiness rule on values
DEFAULTValue if insert omits column
FOREIGN KEYLink 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:

Use this when: Child table (orders) must reference parent table (customers) — referential integrity.


Tutorial 2 — Normalization (3NF intuition)

Normal formIdeaExample
1NFNo repeating columnsOne row per order line
2NFNo partial dependency on part of keySplit order header vs lines
3NFNo transitive dependencySegment 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:

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:

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:

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


Essential commands

Command / actionWhat it does
PRIMARY KEY / FOREIGN KEYEnforce relationships
NOT NULL / UNIQUE / CHECKData quality at insert
COALESCE(a,b)Replace NULL with default
START TRANSACTION / COMMIT / ROLLBACKAll-or-nothing changes
CREATE INDEXFaster 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:

  1. Add a CHECK that revenue cannot go negative (worked model below — adapt to your practice table).
  2. Create an index on sales.customer_id.
  3. Run a transaction that updates two rows, then COMMIT (try ROLLBACK once in a throwaway run).
  4. 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 done

Framing prompts for the rest (fill these blanks in your .sql comments before each statement):

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

Checklist

  • [ ] I can name 4 constraint types
  • [ ] I explained 3NF in one sentence
  • [ ] Transaction COMMIT and ROLLBACK tested
  • [ ] Next: PostgreSQL