Skip to content

Free guide

Design tables around facts and business rules

Decide what one row means before naming columns. Use keys, constraints and transactions to keep related records consistent.

Why it matters

A product manager can spot a report that counts lines as orders. A developer can stop invalid relationships and partial writes from entering the database.

Core concepts

Name the grain

The grain is the unit represented by one row. A purchase can have many lines, each with one item. After joining purchases to lines, a two-line purchase appears twice. Count distinct purchase IDs when the question asks for purchases.

Keys carry identity

A primary key identifies a row. A foreign key ties a child to a valid parent. A unique constraint can protect a natural business rule, such as one enrollment per learner per course. Confirm the business rule before making it permanent.

A transaction has a boundary

A transaction can commit a group of database changes together or undo them together. A database transaction cannot undo an email that already left your system. Record the intent to send inside the transaction, then deliver it as separate work.

Reads have costs

Indexes provide faster paths for selected searches and add write and storage costs. Inspect a slow query and its plan using realistic data. A broad index strategy based on guesses can slow the workload you wanted to improve.

Try it step by step

  1. Write “one row per …” above every table in a sketch.
  2. Specify keys, relationships and what happens when a parent is retired.
  3. Use a tiny dataset with two children under one parent. Predict each count before you query.

Write a metric contract with numerator, grain, date, exclusions and an example that someone else can calculate by hand.

Worked example

Fictional example: A report shows three shipments after joining two orders to three lines. Order A has two lines and order B has one. The correct order count is two. The line count is three. Both are valid measures when labeled correctly.

SQL
WITH lines(order_id, item) AS (
  VALUES ('A', 'pen'), ('A', 'pad'), ('B', 'pad')
)
SELECT COUNT(*) AS lines, COUNT(DISTINCT order_id) AS orders
FROM lines;
-- lines: 3, orders: 2

Common mistake

Taking a row count from a joined table without stating the grain.

Practice exercise

Run the query in PostgreSQL. Add another item to A. Predict which number changes. Change the business question to “distinct products” and adjust the query.

Check your understanding

One order has two lines and one has three. What is COUNT(*) after an inner join on these rows?

  1. Two
  2. Three
  3. Five
Show answer

Five. The joined result has one row for each matching line.

Takeaway

A useful count starts with the sentence “I am counting one of these.”

Further reading

Browse more lessons