How to Choose a Database Index: A Real Feed Example
Index a real feed query step by step: the status filter, the sort, cardinality and covering columns, checked with EXPLAIN at each step.
In this chapter
Indexing a real feed: status filter, sort, cardinality, covering
More on Indexes: special kinds and practice
Keep learning
Overview
Run EXPLAIN on the real query Look at the index chosen, the rows estimate and the Extra column. "Using filesort" or "Using temporary" on a LIMIT query is the first thing to fix. Count rows examined, not milliseconds Time depends on the machine and the cache. Rows examined is the same on every machine. Test at production volume A table of 1,000 rows fits in one page and everything is fast. Fill a copy with a realistic number of rows and a realistic spread of values. Test cold and warm The first run after a restart reads pages from disk. Run the query twice and note both numbers. Turn on the slow query log Log anything over a threshold, and anything that examines far more rows than it returns. The queries that hurt are rarely the ones you guessed. Change one thing at a time Add one index, measure again. Two changes at once and you do not know which one helped. Few distinct values, evenly spread Weak alone. Useful as the first column of a composite index. Few distinct values, one rare value you look up Good for the rare value, ignored for the common one. Index (col, other). Equality first, sort second. Mixed ASC/DESC in ORDER BY Declare the same directions in the index (MySQL 8, PostgreSQL). Feed with next-page links Keyset cursor on (sort column, id) with an index in the same order. Wide columns in the select list Name the columns you need. Add to the index only if the query is hot and the columns are small. Index (a) next to index (a, b) The first is usually redundant. Drop it after checking. Index nobody uses Costs a write on every insert and memory in the buffer pool. Drop it. chapters · indexes Indexing a real feed: status filter, sort, cardinality, covering A blog platform has a posts table (id, user_id, status, published_at, title, body) and three screens: a list of posts by status, a public feed, and a profile page. This chapter picks the indexes for them one decision at a time, and shows how to check that the choice worked.
1. Cardinality: how many different values, and how they are spread
An index on status alone is weak for the common value but fine for the rare one: finding the 10,000 archived posts touches 1% of the table. The planner knows the spread from statistics, so the same index can be used for one value and skipped for another. Low cardinality is still useful as the first column of a composite index, which is the next section.
2. List posts by status, newest first
The rule: put the equality column first, the sort column second. All rows of one status then sit next to each other in the index, already in date order, so the database starts at the newest entry and stops after 20. The filesort disappears, and so does the dependence on how common the status is. The reversed order (published_at, status) cannot do this: the dates of all statuses are mixed together. The order of columns is covered in index lookup and the sort in index order.
3. The feed: many authors, recent first, page after page
The cursor the client sends back is the last row's (published_at, id). That pair is exactly a position in the index, so the database seeks there and reads 20 entries. Publishing a new post while someone is on page 3 does not shift their pages, which OFFSET cannot promise. The user's own page needs its own index, (user_id, published_at DESC), because the feed index starts with status.
4. Covering, SELECT * and the price of every index
Covering is a trade, not a goal. A wider index is bigger, is rewritten on every insert, and competes for memory. Now the other side of the ledger: each index you keep costs a write on every insert and update of its columns, and it has to be read into memory to be fast. When the indexes no longer fit in the buffer pool, lookups that used to take one memory read start taking disk reads. To find indexes worth dropping, look for ones that are a left prefix of another ((status) next to (status, published_at, id)) and for ones the usage statistics say are never read. MySQL exposes the second through sys.schema_unused_indexes, PostgreSQL through pg_stat_user_indexes.idx_scan. Make the index invisible first where the engine allows it, wait a full business cycle, then drop it.
5. Measuring, and why “fast on my laptop” lies
A developer database has a thousand posts, all in memory, no other users. Nearly any query is fast there, including the unindexed one. Compare the same query before and after the index, at two data volumes. A measuring checklist The query plan is explained in reading EXPLAIN, and the same ideas for a top-N query are in top-N. A range condition on the sort column is covered in range scan.
6. Joins, subqueries, UPDATE and DELETE need the same thinking
A join runs as nested loops: read the outer table with its filters, then run a small lookup on the inner table for every row found. So each table gets the index for its own lookup. The outer table needs an index for its WHERE conditions. The inner table needs an index that starts with the join column, followed by its other filters. The optimizer may flip the order, so a join needs the indexes for both directions. The driving order is worked through in join execution. An independent subquery runs once, so index it as if it were a query on its own. A correlated subquery runs once per outer row, so it is a join: index the correlated column first, then its filters. EXISTS stops at the first match. UPDATE and DELETE first find their rows exactly like a SELECT with the same WHERE, so the same index helps. Without it they scan, and in InnoDB they can lock every row they examine, not only the rows they change (see gap locks). Run EXPLAIN on the SELECT version. How the write itself works is in update internals. ! No index can fix a filter split across two tables
Recap
Selectivity, the share of rows one lookup returns, decides whether an index helps. A column with 95% of rows in one value is weak alone but fine for its rare values. For a feed, use a keyset cursor on (published_at, id) with an index in the same order, and never OFFSET on deep pages. Name the columns you need instead of SELECT *. Cover only hot queries with small columns. Every index costs a write per insert and memory. Drop redundant prefixes and unused indexes. Measure rows examined with EXPLAIN at production volume, cold and warm, one change at a time.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.