Interview: the index is right there, make Postgres use it

A predicate matching 97% of the table is faster as a sequential scan. Selectivity, seq_page_cost, faux predicates, CTE fences, and trying a drop inside a…

More on Ticket interviews

Keep learning

Overview

1 row, the needle Index Scan One matching row: the index fetches one page. A full scan would read the whole table for it. At default costs the planner still likes the index here. That is this cost model, not a general rule. Seq Scan Someone lowered seq_page_cost “for SSDs”, so this plan flipped. The setting is global and flips other plans too. 99% of rows, the hay The index would fetch nearly every page in random order. One front-to-back read is cheaper. Same table, same index. Only the predicate and one cost constant change.

“The index is right there. Make Postgres use it.”

A report reads 97% of an 80-million-row table, so Postgres skips the index. A ticket says force it. Should you? faux predicate CTE fence invisible index Keep the full scan. Add a partial index for rare rows.

Shipped-orders export ignores the index and runs for 8 seconds

orders.status has an index, but EXPLAIN says Seq Scan. Please force the index. Seq Scan estimate vs actual Restated: the planner skips the index on purpose. The filter matches almost every row.

The estimate is honest. The access path is the question.

Every column, so a covering index would have to hold the whole row. That is a second copy of the table. EXPLAIN (ANALYZE) Estimated 77.6 million, actual 77.6 million. This is not a statistics bug. The sequential scan is throwing away about 3%. The index can find the rows. Fetching them is random I/O across a heap that is not ordered by status.

Ask what fraction of the heap the index would touch

Is the estimate the bug? compare rows= with actual rows= No. They agree. ANALYZE will not change this plan. What would the index scan do? selectivity and correlation Random page reads for 97% of rows. More reads than the table has pages. Is 8 seconds unreasonable here? count bytes, not indexes No. It is tens of millions of wide rows in one pass. Who is the index for, then? the other status values The 3% not shipped. A partial index serves that queue. rows match “shipped” correlation: heap not sorted by status estimate equals actual Index scan 77M random page fetches, many pages read again and again. Seq scan Read every page once, in order. Drop 3%.

Say no to the hint. Offer the index that matches the rare rows.

Does not overrule a planner whose estimate is right. Indexes only the rare rows, with a partial index. Treats export speed as a bytes problem, not an index problem.

No AI from here

There is no index on modified, and the audit scan is huge. There is an index on created. What do you add to the query? faux predicate Add AND created < T. It cannot change the result, but it unlocks the index. A row is never modified before it is created, so modified < T implies created < T. If that rule ever breaks, rows vanish silently. Comment it. For a permanent query, index modified instead. redundant predicate lets the index apply name the invariant modified < T no index + created < T always true too Index on created Filter modified A WITH clause made a 40 ms query take 2 seconds. What happened? optimization fence The CTE became an optimization fence: outer filters could not reach inside. Before PG 12, every CTE ran fully first, then got filtered. PG 12+ inlines it, unless AS MATERIALIZED or used twice. Materializing costs memory or disk. Do not use it to steer indexes. filters do not push down PG 12 inlines MATERIALIZED is explicit Fenced (pre-12 / MATERIALIZED) Inner query runs in full. Filter applied after. Inlined (PG 12+) Filter pushed inside. Index can apply. How do you see the plan without an index, on a live primary, without leaving it dropped? invisible index Drop it inside a transaction, EXPLAIN, then ROLLBACK. Postgres DDL is transactional, so the drop never commits. But DROP INDEX holds an exclusive lock. Queries queue. Keep it tiny, or use a clone. BEGIN / DROP / EXPLAIN / ROLLBACK exclusive lock hints not core DROP INDEX locks table index back Keep this window as short as possible. Lowering seq_page_cost to 0.1 “because we have SSDs” flipped a fine index scan into a sequential scan. Why? cost model It made every sequential scan look cheaper, everywhere. seq_page_cost (default 1) prices an in-order page read. random_page_cost (default 4) prices a random read. That is the SSD knob. Test changes on a replica against plans you trust. the constant is global flips borderline plans random_page_cost is the SSD knob seq_page_cost default random_page_cost default seq_page_cost set “for SSDs” When is it reasonable to override the planner at all? Only when estimates are right and the cost model is still wrong. Prefer giving facts: a statistic, an index, or a true redundant predicate. A hint freezes one plan while the data keeps changing. If you freeze a plan, set a date to review it. stats first prefer information over a frozen plan a date to revisit

Ops still wants the export under two seconds

What do you ship? Keep the sequential scan. Partial index for the unshipped queue. The export keeps the cheap plan. The new index serves the 3% looked up one by one. Export cost Queue lookups Planner damage Random fetches for 97% of rows: slower than 8 s. The whole session loses seq scans. pg_hint_plan: IndexScan(orders orders_status_ix) You get the requested plan, which is the slow one. It needs an extension and outlives the data. Lower seq_page_cost to 0.1 instance-wide Does not help this export. Other queries may lose index scans they needed.

Have one ready

Tell me about a time you refused to force an index. Runtime, and % of rows matched. Random fetches lost to one pass. What you indexed instead. EXPLAIN ANALYZE: estimate vs actual.

Did you show these?

Checked estimate vs actual first Why 97% loses as an index scan Kept the seq scan for the export Partial index for rare statuses Safe redundant predicate on created BEGIN/DROP/EXPLAIN/ROLLBACK + its lock

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.