30 Database Index Interview Questions to Test Yourself
Thirty index questions to try before reading: B-trees, clustered keys, composite order, covering, cardinality and when an index makes writes slower.
In this chapter
Thirty index questions to try before the chapters
Keep learning
Overview
Column order and choosing the index Which columns, in which order, and when one index beats two. Filter first, or read in the right order? An orders table holds 200 million rows. A query asks for one tenant’s orders above ₹10,000, newest first, LIMIT 50. Would you build (tenant_id, amount, created_at) or (tenant_id, created_at, amount)? What changes if expensive orders are common overall but almost absent among recent orders? (tenant_id, amount, created_at) narrows to the amount range, but the dates inside that range are out of order, so every match is read and sorted before the LIMIT applies. (tenant_id, created_at, amount) walks one tenant newest first and stops after 50 matches. amount is tested on each entry it passes, so the rows it rejects are the cost. The choice depends on how the matching rows are spread, not on which column has more distinct values. Follow-up: if recent orders are rarely expensive, the time-ordered walk passes thousands of rejects before it finds 50, and the amount-first index wins. Does a range make the later columns useless? INDEX (customer_id, order_date, status). A query filters one customer, a date range and one status. Explain what each column contributes. Can status cut table reads without cutting the number of index entries read? customer_id (equality) and order_date (range) decide where the scan starts and stops. status cannot narrow the scan after the range, but it is inside every entry, so it can be tested there. Keep three costs apart: entries the scan visits, entries rejected inside the index, and rows fetched from the table. Two single-column indexes, or one composite? Queries filter by customer alone, by status alone, or by both. You can afford two indexes. What do you build, and what do you ask for first? How does adding ORDER BY created_at LIMIT 20 change the answer? Ask first: how often each query shape runs, how selective each value is, the write rate, and the index sizes. Engines can combine two single indexes (PostgreSQL bitmap AND/OR, MySQL index merge), but that is usually slower than one composite index. Follow-up: a combined bitmap returns rows in page order, so a sort is needed. An index that ends in created_at, such as (customer_id, status, created_at), can stop after 20. Index merge is mentioned, but not that a PostgreSQL bitmap scan loses index order and always needs a sort. PostgreSQL: combining multiple indexes Is the leftmost-prefix rule absolute? PostgreSQL 18 · MySQL 8 INDEX (region, customer_id). A query filters only by customer_id. A developer says the index cannot help because region is missing. Always true? Compare a table with 5 distinct regions to one with 5 million distinct leading values. Not always. A skip scan runs one seek per distinct leading value (PostgreSQL 18, MySQL 8.0.13+ for some plans, Oracle). With 5 regions that is 5 small seeks: cheap. With 5 million leading values it is 5 million seeks, worse than a scan. “Usable” and “efficient” are different judgments. Do not design an index around skip scan. Why does a mixed-direction ORDER BY still sort? INDEX (priority, created_at). ORDER BY priority DESC, created_at ASC LIMIT 20 sorts the whole result. In PostgreSQL the query adds NULLS LAST to a DESC column. Why might a matching index still be skipped? An index can be read forwards or backwards, which flips every column together. Mixed directions need an index declared that way. MySQL stores DESC in an index only from 8.0. PostgreSQL always has. Follow-up: in PostgreSQL, DESC defaults to NULLS FIRST. The index must declare the same null placement, for example (priority DESC NULLS LAST, created_at). NULLS FIRST and NULLS LAST in index order are not covered yet. PostgreSQL: indexes and ORDER BY OR across two indexed columns When is a UNION rewrite better, and when is UNION ALL wrong? A UNION rewrite gives each branch its own index seek. UNION ALL returns a row twice when it matches both branches. Use UNION, or exclude the first branch from the second: AND (email <> $1 OR email IS NULL). Only a short note and one reference row cover it. MySQL: index merge Design the index set for one table You get the 20 most frequent and the 5 slowest queries for a write-heavy table, and a budget of four secondary indexes. A new query arrives that none of the four serves well. Does it get a fifth index? Weight queries by frequency × cost, not one vote each. Merge candidates: an index whose leading columns match another’s can serve both. Drop left-prefix duplicates. Count the indexes that constraints already need: primary key, unique keys, foreign keys. Budget write cost, disk and buffer-pool memory, and test at production volume. Follow-up: try a rewrite, a small extra column on an existing index, or a summary table before adding a permanent fifth index. What a lookup really costs The tree walk is cheap. The rows, loops and table visits after it are not. The plan uses the index, and it still takes 8 seconds A query returns 20 rows. The plan shows an index scan, yet it takes eight seconds. A developer says “indexing is handled”. How do you investigate? An inner index lookup takes 0.05 ms but runs one million times. Is it cheap? Compare rows examined with rows returned. A big gap means a wide range or a late filter. Look for a table fetch per match, sorts, buffer reads, and estimated against actual rows. Follow-up: no. 0.05 ms × 1,000,000 is 50 seconds. In PostgreSQL EXPLAIN, time and rows are per loop, so multiply by loops. Why deep pages get slow Page 1 loads fast. OFFSET 1000000 LIMIT 50 takes seconds, though an index matches the sort. How do you paginate when many rows share a timestamp and new rows arrive between requests? OFFSET still reads and throws away every skipped row. Use a keyset cursor, WHERE (created_at, id) < (?, ?), with an index in the same order. The id tie-breaker makes the order unique, so no row is skipped or shown twice. New rows do not shift a cursor’s pages, which OFFSET cannot promise. Say what consistency the product needs. A covering index that still reads the table Every column the query needs is in the index. The plan says Index Only Scan, yet reports thousands of Heap Fetches. Why can a big batch of updates make this query slower with the same index? Index entries carry no visibility information, so the scan checks the visibility map for each heap page. Only pages marked all-visible can be skipped. The others are read to check the row version. Follow-up: updates clear the all-visible bits until VACUUM sets them again, so heap fetches rise. When the planner skips or misjudges the index Expressions, types, collations, estimates and prepared statements. An index on email misses a case-insensitive lookup You add an index on lower(email). Does it help a code path that uses ILIKE? An index matches only the expression it was built on. Index lower(email), and the query must use that same expression. Every expression index adds work to each write. Follow-up: no. ILIKE is not equality on lower(). Use citext, a case-insensitive collation, or a trigram index. Quoting a number makes the index work Two tables join on VARCHAR columns with different character sets. Why might the join skip the index? Comparing a string column with a number converts the column on every row, so the index order is no use. Many strings become the same number (‘1’, ‘ 1’, ‘01’), so there is not even a single key to seek. Follow-up: a charset or collation mismatch also converts one side. Fix the column definitions, not the query. LIKE ‘abc%’ ignores a plain B-tree A prefix search on name scans the table, though name is indexed. The database uses the en_US.UTF-8 collation. Product now wants LIKE ‘%abc%’. What changes? Under a non-C collation the B-tree order does not support prefix ranges. Build the index with text_pattern_ops. That index serves LIKE prefixes but not an ordinary ORDER BY in the collation’s order. Follow-up: a leading wildcard has no starting point in any B-tree. Use a trigram GIN or GiST index (pg_trgm), and pay its size and write cost. A sequential scan beats a selective-looking index A query that matches 8% of rows uses a sequential scan. Forcing the index is faster on your laptop and slower on staging. Physical order (correlation), random_page_cost and cache size move that line. A warm laptop cache hides random I/O. Follow-up: it changes every plan in the session, and only tells you whether the cost settings are wrong. Fresh statistics, terrible estimate A query filters country and city. Statistics were just refreshed, yet the optimizer expects 50 rows and gets 500,000. Why might creating another index fail to fix it? The planner multiplies the selectivity of each filter, assuming the columns are independent. A city implies its country, so the estimate is far too low. PostgreSQL extended statistics (CREATE STATISTICS with dependencies or mcv) can capture the link for some queries, not all. Follow-up: the index is not the problem. A wrong row estimate picks a wrong plan whatever indexes exist. A longer IN list switches plans WHERE id IN (...) with 150 values is fast. With 250 values the optimizer picks another index and runs 10× slower. When would a histogram help more than adding an index? Up to eq_range_index_dive_limit values (200 by default) MySQL probes the index for each value to count rows exactly. Above it, it uses averaged index statistics. The rougher estimate can choose a worse index. Raising the limit or splitting the list are options. Follow-up: a histogram improves estimates on a column without an index and costs nothing on writes, but it does not speed up the lookup itself. Index dives and eq_range_index_dive_limit are not covered yet. MySQL: range optimization MySQL: optimizer statistics One prepared query, different plans per customer Why is it fast with a literal tenant id in psql but slow from the app? After five runs, PostgreSQL may switch a prepared statement to a generic plan that does not look at the parameter value. A generic plan fits the typical tenant and can be terrible for the 80-million one. That is data skew. Follow-up: psql with a literal gets a custom plan for that value. Compare the plan the app really gets (auto_explain or EXPLAIN EXECUTE) and look at plan_cache_mode. Generic and custom plans are not covered yet. PostgreSQL: PREPARE, generic and custom plans PostgreSQL: plan_cache_mode A perfect partial index, ignored Why is passing ‘pending’ at execution time not enough? The planner uses a partial index only when it can prove the query’s WHERE implies the index’s WHERE. A generic plan must work for any value of $1, so it cannot assume ‘pending’. Fix: write the literal in the query text, or make sure a custom plan is used. PostgreSQL: partial indexes PostgreSQL: PREPARE Keys, storage and write cost What the primary key and every extra column cost on each write. A longer primary key slows every secondary index MySQL vs PostgreSQL A table replaces a numeric primary key with a long text id. Queries through secondary indexes get slower, though those indexes did not change. Would PostgreSQL pay the same way? An InnoDB secondary index entry stores the primary key to find the row. A wider key makes every secondary index bigger and less cache-friendly. It also lowers fan-out in the upper levels of each tree. Follow-up: no. A PostgreSQL index points to a heap location (ctid), so the primary key width affects only its own index. Random UUIDs slow down inserts A team moves from bigint ids to UUIDv4 primary keys. Insert rate falls and the cache hit rate drops as the table grows. Does UUIDv7 fix it, and what does it give up? Random keys land on random leaf pages: page splits, pages about 69% full, and a working set bigger than memory. In InnoDB the table itself is that key-ordered tree, and the 16 bytes are copied into each secondary index. Follow-up: UUIDv7 is time-ordered, so inserts append at the right edge. It reveals the creation time and is still twice the size of a bigint. One INCLUDE column slows down writes Why does it matter that the column is payload, not a search key? A HOT update skips every index, but only when no indexed column changes and the page has room. An INCLUDE column counts as indexed. Each last_seen_at update now writes a new entry into every index on the table. Follow-up: the column is not even searchable. You pay full index maintenance for a column that only saves a heap visit. Check n_tup_hot_upd, index size and fillfactor. HOT and INCLUDE are each covered, but not that an INCLUDE column blocks HOT updates. PostgreSQL: heap-only tuples (HOT) A small queue table with a huge index A jobs table holds about 10,000 rows with constant inserts and deletes. Its index is many gigabytes, and fetching the oldest job slows down during the day. REINDEX fixes it for a few hours. What is blocking cleanup? Deleted rows leave dead entries at the old end of the index, and every poll steps over them. Only VACUUM, or B-tree deletion of entries dead to every transaction, removes them. Follow-up: something holds the xmin horizon back: a long or idle-in-transaction session, a stale replication slot, or hot_standby_feedback. Find it before scheduling reindexes. A partial index on pending jobs keeps the index small. Dead index entries in queue tables and B-tree bottom-up deletion are not covered yet. PostgreSQL: B-tree implementation PostgreSQL: routine vacuuming Constraints and special index types NULL in unique keys, foreign keys, JSON, BRIN and partitions. A unique index that allows duplicates UNIQUE (tenant_id, external_id), and external_id can be NULL. Production has many (42, NULL) rows. Rows are soft-deleted with deleted_at. Enforce uniqueness among live rows in PostgreSQL and in MySQL. NULL is not equal to NULL, so most databases allow repeated NULLs in a unique index. SQL Server is the exception. PostgreSQL 15+ has NULLS NOT DISTINCT. Follow-up: PostgreSQL, a partial unique index WHERE deleted_at IS NULL. MySQL has no partial index: index an expression or generated column that is NULL for deleted rows. Deleting one parent row takes 40 seconds Deleting one customer takes 40 seconds and blocks other writes. orders.customer_id references customers.id. Why does MySQL not behave this way with the same schema? PostgreSQL indexes the referenced key, not the referencing column. Each parent delete scans orders to check or cascade. Fix: an index on orders(customer_id). Follow-up: InnoDB requires an index on foreign key columns and creates one if it is missing. Foreign keys without an index on the child column are not covered yet. The linked chapter covers the locks foreign keys take. PostgreSQL: foreign keys MySQL: foreign keys One JSONB column, many query styles events.payload is JSONB, filtered by containment (@>), key existence (?) and one nested field. After adding GIN, insert latency gets spiky and some…
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.