Quick revision
The short answer
Most likely the planner's statistics are stale after the backfill, so it misjudges how many rows fall in the last day and thinks a sequential scan plus sort is cheaper. We confirm with EXPLAIN (ANALYZE, BUFFERS), comparing estimated with actual rows, then run ANALYZE orders and raise the column's statistics target if needed. We also check for a cast on created_at and that the index is valid, because an index left invalid by a failed CREATE INDEX CONCURRENTLY is never used.
What to remember
In this answer, we saw that a Seq Scan and Sort on an indexed column after a big backfill usually means stale statistics: the planner overestimates rows in the last day and avoids the index. EXPLAIN (ANALYZE, BUFFERS) shows the gap between estimated and actual rows, ANALYZE and a higher per-column statistics target fix it, a cast on the column or mismatched types can block the index, and an index left invalid by a failed concurrent build is never used. With good estimates, a backward index scan answers the query with no sort.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Most likely the planner's statistics are stale after the backfill, so it misjudges how many rows fall in the last day and thinks a sequential scan plus sort is cheaper. We confirm with EXPLAIN (ANALYZE, BUFFERS), comparing estimated with actual rows, then run ANALYZE orders and raise the column's statistics target if needed. We also check for a cast on created_at and that the index is valid, because an index left invalid by a failed CREATE INDEX CONCURRENTLY is never used.
Why this question is asked
This query is the shape of almost every 'latest items' page: filter by recent time, sort newest first, take 50. With a good index it should touch a few pages and return in a millisecond, and right after a large backfill it suddenly scans 200 million rows. Interviewers like this question because the index is fine and the problem is the planner's knowledge about the data. In this answer, we will recap how the planner chooses, read the plan, fix the statistics, check the expression and the index itself, and see what the good plan looks like.
1A Quick Recap of How the Planner Chooses
PostgreSQL's planner does not try every plan by running it. It estimates the cost of each candidate from statistics: the table's row count and, for each column, a histogram of values and the most common values, collected by ANALYZE into pg_statistic. From these it guesses how many rows a condition will match, called the selectivity.
If it believes the last day holds only a few thousand rows, walking the index backwards and stopping after 50 is clearly cheapest. If it believes the last day holds tens of millions, a sequential scan with a sort looks cheaper, because random index reads for many rows cost more than reading the table in order. So when we see a Seq Scan and a Sort, the first question is what the planner believed.
2Reading the Plan With ANALYZE and BUFFERS
Plain EXPLAIN shows only estimates. EXPLAIN (ANALYZE, BUFFERS) runs the query and adds actual row counts, timings, and how many pages were read from the cache or from disk. A large gap between estimated and actual rows is the signature of bad statistics.
Notice the two row counts on the scan: the planner estimated 48 million rows in the last day, the truth is 310 thousand. With 48 million, its choice was reasonable; with the real number, it was terrible. Notice also the buffers: almost 3 million pages read from disk, which is why the query takes minutes.
3Fix 1: Refresh the Statistics
A large backfill inserts or updates many rows quickly. Autovacuum runs ANALYZE only after a threshold of changes and may not have reached the table yet, or it ran in the middle of the backfill. Either way, the histogram for created_at and the row count describe a different table. Running ANALYZE ourselves is cheap, because it reads a sample, about 30,000 rows with the default target, not the whole table.
A higher statistics target means a finer histogram with more buckets, which helps when values are very unevenly spread, for example a few years of sparse history and a dense recent month. We also add ANALYZE as the last step of every future backfill script.
4Fix 2: Check the Expression and the Data
Next we check that the condition can use the index at all. A function or cast applied to the column, such as created_at::date or date_trunc('day', created_at), means the index on created_at no longer matches the expression. A parameter of a different type can also do it in some cases: comparing a bigint column with a numeric value casts the column. For timestamp and timestamptz, PostgreSQL has cross-type comparison operators in the same operator family, so the index usually still works, but the comparison then depends on the session time zone, so it is worth making both sides the same type.
We should also check the data itself. If the backfill wrote new rows with created_at = now() instead of their historical times, the last day really does contain millions of rows, and the Seq Scan may be honest. Then the fix is in the backfill, not the planner.
- Run EXPLAIN (ANALYZE, BUFFERS)compare estimated and actual rows
- Estimate far from actual?YesANALYZE, raise statistics targetNoCheck the condition
- Cast or function on the column?YesRewrite the condition or add an expression indexNoCheck the index
- Index valid in pg_index?YesCheck whether many rows really matchNoRebuild it concurrently
- Confirm the new planIndex Scan Backward, no Sort
5 steps in order. Play them, or step through them one at a time.
5Fix 3: Check That the Index Is Valid
If the index was created with CREATE INDEX CONCURRENTLY during or after the backfill, and that build failed or was cancelled, PostgreSQL leaves the index behind but marks it invalid. It still costs writes, but the planner never uses it. psql's \d orders shows it with INVALID, and the catalog shows it directly.
6What the Good Plan Looks Like
Once the planner knows that only about 310 thousand rows are recent, and that we want 50 of them, it chooses a backward index scan. It starts at the newest entry in the index, walks backwards, and stops after 50 rows. There is no Sort node, because the index already returns rows newest first.
From nearly 3 million page reads to 54. The backward scan is chosen precisely when the planner believes the limit will be reached after few rows, which is why accurate statistics matter so much for this query shape.
7Follow-up questions
What does BUFFERS add to EXPLAIN?
It shows, per plan node, how many pages were found in shared buffers (shared hit), read from the operating system or disk (shared read), dirtied and written, plus temporary file usage for sorts and hashes that spilled. It turns 'this is slow' into 'this read 2.9 million pages', which points straight at the expensive node. In PostgreSQL 18, EXPLAIN ANALYZE includes buffer counts by default; check your version.
When would you raise default_statistics_target?
Rarely for the whole database, because a higher target makes ANALYZE slower and planning a little more expensive for every column. We raise it per column with ALTER TABLE ... SET STATISTICS when EXPLAIN ANALYZE shows that column's estimates are far off because of skewed data, as with a timestamp column holding sparse history and a dense recent period, or a column with many common values. Raising the global default makes sense only when misestimates are widespread across a reporting database.
Can we stop this happening after future backfills?
Yes: run ANALYZE as the last step of every bulk load, and for very busy tables lower autovacuum_analyze_scale_factor for that table so autovacuum analyzes after a smaller share of rows change.
8Conclusion
In this answer, we saw that a Seq Scan and Sort on an indexed column after a big backfill usually means stale statistics: the planner overestimates rows in the last day and avoids the index. EXPLAIN (ANALYZE, BUFFERS) shows the gap between estimated and actual rows, ANALYZE and a higher per-column statistics target fix it, a cast on the column or mismatched types can block the index, and an index left invalid by a failed concurrent build is never used. With good estimates, a backward index scan answers the query with no sort.
Open with
I would start with EXPLAIN ANALYZE with BUFFERS, because I want to compare the estimated rows with the actual rows on the scan. After a large backfill, autovacuum may not have analyzed the table, so the planner might think tens of millions of rows are in the last day when it is really a few hundred thousand.
Then, if they want more
With that belief, a sequential scan plus sort looks cheaper than a backward index scan. If the gap is large, I check pg_stat_user_tables for the last analyze time and modified rows, and run ANALYZE orders, which only samples the table. If the column is very skewed, I raise its statistics target, for example to 1000, and analyze again.
I would also check the query expression: a cast or function on created_at stops the index being used, and mismatched types can in some cases, so both sides should be the same type. I would check the data too, because if the backfill set created_at to now, the last day really is huge.
Finally I check pg_index.indisvalid, since an index from a failed CREATE INDEX CONCURRENTLY stays invalid and is ignored; then I rebuild it concurrently. Once the estimates are right, the plan should be an Index Scan Backward with a limit and no sort node.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 18
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Query: SELECT * FROM orders WHERE created_at > now() - interval '1 day' ORDER BY...": https://scrivio-interview-library.netlify.app/databases/indexing/fffbbb5c6b/