Schema design, normalisation & indexes
Design tables and indexes and read an EXPLAIN plan.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
Good schema design stores each fact once and links tables with keys. Indexes then make the common queries fast, and EXPLAIN shows whether the database actually uses them.
Explained simply
Designing a schema means deciding which tables you need, which columns go in each, and how the tables link together. A good design makes the right queries easy and makes wrong data hard to store.
The main rule is: store each fact in one place. If a customer's email is copied into every order, changing it means updating hundreds of rows, and sooner or later two copies disagree. Instead, store the email once in customers and let each order point to the customer by id.
Keys and constraints make the database guard your data. A primary key identifies each row. A foreign key says an order must belong to a customer that really exists. NOT NULL, UNIQUE and CHECK reject bad values even if your Java code has a bug.
Indexes make lookups fast. Without one, the database reads every row to find a match. An index is like the index at the back of a book: it tells the database exactly where to look. EXPLAIN shows you whether the database actually uses it.
Press Play on a diagram to walk through it one step at a time.
- 1List entities
Users, orders, products: the nouns of the domain
- 2Map relationships
One-to-many, many-to-many via a join table
- 3Add keys
Primary, foreign and unique constraints
- 4Normalise to 3NF
Each fact stored once, no repeating groups
- 5Index hot queries
Index columns used in WHERE, JOIN, ORDER BY
- 6Check EXPLAIN
Confirm index scans instead of full scans
- Sequential scan of every row
- O(n) per lookup
- Fast writes
- Index scan jumps to matches
- O(log n) per lookup
- Slightly slower writes, extra storage
- Each fact stored once
- Updates touch one row
- Needs joins to read
- The default for OLTP apps
- Facts copied for fast reads
- Updates must touch every copy
- Fewer joins
- Good for reports and caches
In depth
Turning relationships into tables
Start from the nouns of the domain (customer, order, product) and how they relate. For one-to-many, such as one customer with many orders, put a foreign key on the many side: orders.customer_id. For many-to-many, such as orders and products, you need a join table, order_items, holding order_id and product_id. That table often carries its own data, like quantity and unit price at the time of sale.
One-to-one is rarer. Use it to split rarely used or sensitive columns into a separate table that shares the same primary key. Ask about each relationship: is it required or optional, and what happens when the parent is deleted? Those answers become NOT NULL and ON DELETE rules.
- One-to-one
- Same primary key in both tables
- user and user_profile
- One-to-many
- Foreign key on the many side
- orders.customer_id
- Many-to-many
- Join table with two foreign keys
- order_items(order_id, product_id)
- Can hold extra columns
Normal forms in plain words
Normalisation is a checklist for removing duplicated facts. First normal form (1NF): each column holds one value, so no comma-separated tags and no phone1, phone2, phone3 columns; put repeating items in their own table. Second normal form (2NF): when the key has several columns, every other column must depend on the whole key. In order_items(order_id, product_id), product_name depends only on product_id, so it belongs in products. Third normal form (3NF): non-key columns must not depend on other non-key columns. If orders stores customer_id and customer_city, the city depends on the customer, not the order.
Denormalising on purpose is fine for read-heavy reports, but do it knowingly and keep the normalised data as the source of truth.
- 1One wide row
Order, customer, and items as item1, item2...
- 21NF
Move items into their own rows
- 32NF
Product details move to products
- 43NF
Customer details move to customers
- 5Result
customers, orders, order_items, products
Keys and constraints that protect data
Most tables use a surrogate key: a meaningless number generated by the database. In modern PostgreSQL write id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, the SQL-standard replacement for SERIAL. UUIDs are useful when ids are created outside the database or must not be guessable; time-ordered UUID version 7 keeps index inserts efficient. Keep real-world identifiers like email as UNIQUE columns rather than as the primary key, because they can change.
Add constraints for every rule you can state: NOT NULL for required fields, UNIQUE for natural identifiers, CHECK (quantity > 0) for value rules, and foreign keys with a chosen ON DELETE action: RESTRICT (the default behaviour is similar) blocks deleting a parent with children, CASCADE deletes them too. PostgreSQL creates indexes for primary keys and unique constraints, but not for foreign key columns; add those yourself.
- Use NUMERIC(12, 2) for money, never float
- Use TIMESTAMPTZ for points in time
- Name constraints so error messages are readable
How a B-tree index finds rows
The default index type is a B-tree: a shallow, balanced tree of pages with keys in sorted order. Even with 100 million rows it is only about four levels deep, so a lookup reads a handful of pages instead of the whole table. Because keys are sorted, the same index also helps range filters and ORDER BY.
A composite index on (customer_id, created_at) is sorted by customer first, then by date within each customer. So it serves WHERE customer_id = 42, and WHERE customer_id = 42 AND created_at > ..., but not a filter on created_at alone. Put equality columns first and range columns last. Wrapping a column in a function, like WHERE lower(email) = ..., skips a plain index; create an expression index on lower(email) instead. Partial indexes such as ... WHERE status = 'open' stay small when you only query a subset.
- 1Root page
Key ranges point to the right child page
- 2Internal pages
Narrow the range at each level
- 3Leaf pages
Sorted keys with pointers to rows
- 4Table (heap)
Fetch only the matching rows
Reading an EXPLAIN plan
EXPLAIN shows the plan the database intends to use; EXPLAIN ANALYZE actually runs the query and adds real timings and row counts. Because it really runs, wrap ANALYZE of an UPDATE or DELETE in BEGIN and ROLLBACK. Read the plan from the most indented line outward.
Scan types tell you how a table is read. Seq Scan reads every row, which is fine for small tables or when most rows match. Index Scan uses an index, Index Only Scan answers from the index alone, and Bitmap Heap Scan collects many matches first. Join nodes are Nested Loop (good for few rows), Hash Join and Merge Join. The most useful check is estimated rows versus actual rows: if the planner expected 10 and got 100,000, its statistics are stale or the data is skewed, so run ANALYZE on the table.
- EXPLAIN (ANALYZE, BUFFERS) also shows pages read
- cost=0.43..8.45: startup cost, then total cost
- Large gaps between estimated and actual rows mean bad statistics
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Model entities and relationships~1h
- 2Normalise tables to 3NF~1h
- 3Add primary, foreign and unique keys~1h
- 4Create indexes for common queries~1h
- 5Read an EXPLAIN plan~1h
Key points
- Normalisation removes duplicated data so updates happen in one place.
- Foreign keys let the database reject orphaned rows.
- Indexes speed reads but cost write time and storage; add them for real queries.
- A composite index on (a, b) helps queries filtering on a, or a and b, not b alone.
Key terms
Tap a card to flip it. 0/5 known
Examples
CREATE TABLE customers (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_orders_customer ON orders (customer_id, created_at);
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at;Designing orders, products and the join table
An online shop needs orders that contain many products. Step 1: products and orders each get an identity primary key. Step 2: order_items links them, with a composite primary key so a product appears once per order. Step 3: unit_price is stored on the item because prices change later and the order must keep the price paid; this is not duplication but a different fact. Step 4: CHECK constraints reject zero quantities and negative prices. Step 5: index the foreign key product_id, which PostgreSQL does not do automatically.
CREATE TABLE products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
price NUMERIC(12, 2) NOT NULL CHECK (price >= 0)
);
CREATE TABLE order_items (
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products(id),
quantity INT NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(12, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
CREATE INDEX idx_order_items_product ON order_items (product_id);Fixing a slow query with an index
The open-tickets page takes 900 ms. Step 1: run EXPLAIN ANALYZE and see a Seq Scan over 2 million rows that keeps only 40. Step 2: the query filters on status = 'open' and sorts by created_at. Step 3: since only a few rows are open, a partial index on created_at WHERE status = 'open' is small and matches the sort. Step 4: rerun EXPLAIN ANALYZE: an Index Scan returns the rows in under a millisecond, and no separate sort step is needed.
EXPLAIN ANALYZE
SELECT id, title FROM tickets
WHERE status = 'open' ORDER BY created_at LIMIT 50;
-- Before: Seq Scan on tickets (actual rows=40) ... Execution Time: 905 ms
CREATE INDEX idx_tickets_open_created
ON tickets (created_at) WHERE status = 'open';
-- After: Index Scan using idx_tickets_open_created on tickets
-- ... Execution Time: 0.2 msQuick reference
- One-to-many: foreign key on the many side. Many-to-many: a join table
- id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY is the modern PostgreSQL default
- PostgreSQL does not index foreign key columns automatically
- Composite index (a, b) serves filters on a, or a and b, but not b alone
- Put equality columns first and range columns last in a composite index
- CREATE INDEX ... ON t (lower(email)) supports WHERE lower(email) = ...
- EXPLAIN ANALYZE runs the query; wrap writes in BEGIN ... ROLLBACK
- Run ANALYZE table_name when estimated and actual rows differ wildly
Common mistakes
- Storing comma-separated lists in one column.
- Forgetting indexes on foreign key columns used in joins.
- Indexing every column, which slows all writes.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create tables users and posts, where every post belongs to one user and is deleted when the user is deleted.
- Exercise 2medium
Model students and courses with an enrolment that stores the grade. A student may enrol in a course only once, and grades must be between 0 and 100.
- Exercise 3hard
Users log in by email, typed in any case. Make emails unique regardless of case and make login lookups fast. Show the lookup query.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use UUIDs or numeric ids?
- Numeric identity columns are smaller and fast. Use UUIDs when ids are generated outside the database or must not be guessable, and prefer UUID version 7, which is time-ordered and kinder to indexes.
- How many indexes is too many?
- Every index slows writes and uses space, so add each one for a real query you have measured. Check unused indexes in PostgreSQL with the pg_stat_user_indexes view.
- Should I use ON DELETE CASCADE?
- Use it for child rows that have no meaning without their parent, like order items. For important data such as orders of a customer, prefer blocking the delete or soft-deleting.
- Do I always need third normal form?
- Aim for 3NF in transactional tables, then denormalise only for measured performance needs such as reporting tables or caches.