Quick revision
The short answer
The sort needed more memory than work_mem, so PostgreSQL spilled about 1.8 GB to temporary files and merged them from disk, which is most of the 40 seconds. I would first check whether an index on the ORDER BY columns or a query that sorts fewer rows and columns can avoid the sort, and otherwise raise work_mem only for this query or the reporting role, with SET LOCAL or ALTER ROLE. What I would avoid is raising work_mem globally, because it applies to every sort and hash node in every connection and can exhaust the server's memory.
What to remember
In this answer, we read Sort Method: external merge Disk: 1840000kB as a sort that needed more than work_mem and spilled 1.8 GB to temporary files. We first tried to remove the sort with an index on the ORDER BY columns or by sorting fewer and narrower rows, then raised work_mem only for this query with SET LOCAL or for the reporting role with ALTER ROLE, testing a few values. We avoided a global increase, because work_mem applies per node and per connection and can exhaust memory, and we used log_temp_files and pg_stat_statements to find other spilling queries.
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.
The sort needed more memory than work_mem, so PostgreSQL spilled about 1.8 GB to temporary files and merged them from disk, which is most of the 40 seconds. I would first check whether an index on the ORDER BY columns or a query that sorts fewer rows and columns can avoid the sort, and otherwise raise work_mem only for this query or the reporting role, with SET LOCAL or ALTER ROLE. What I would avoid is raising work_mem globally, because it applies to every sort and hash node in every connection and can exhaust the server's memory.
Why this question is asked
Slow reporting queries are a classic tuning task, and the line Sort Method: external merge is one of the clearest signals EXPLAIN gives. The tempting fix is to raise work_mem in postgresql.conf and move on, which can turn one slow query into an out-of-memory crash on a busy day. Interviewers ask this to see whether we read the plan correctly and fix it at the right scope. In this answer, we will recap what the line means, see why the query is slow, try the fixes that remove the sort, then size work_mem for this query only, and finally find other queries with the same problem.
1A Quick Recap: What the Plan Line Means
work_mem is the amount of memory one sort or hash operation may use. If the rows to sort fit, PostgreSQL sorts them in memory with quicksort, and EXPLAIN ANALYZE says Sort Method: quicksort Memory: 25000kB. If they do not fit, PostgreSQL sorts chunks that fit, writes each sorted chunk to a temporary file, and then merges the files. That is an external merge sort, and the plan says Sort Method: external merge Disk: 1840000kB, meaning about 1.8 GB of temporary files.
The BUFFERS option adds the temporary block counts, temp read and temp written, which confirm the same thing in 8 KB blocks.
Notice where the time goes. The scan finishes after about 6 seconds, and the sort takes most of the remaining time, writing and reading 230,000 temporary blocks. So the sort is the problem, not the scan.
2First Ask: Does the Query Need This Sort?
Before giving the sort more memory, we check whether it needs to happen at all. The cheapest sort is the one the planner can skip. If there is a B-tree index on exactly the ORDER BY columns, PostgreSQL can read rows in index order and no sort node appears. That works best when the query also filters to a part of the table, or uses LIMIT.
We also look at what is being sorted. A report that sorts 12 million rows of SELECT * and then shows the top 100 per region should aggregate or filter first, so the sort handles thousands of rows, not millions. And sort cost grows with row width: sorting only the id and key columns and joining the details afterwards can shrink a 1.8 GB sort to a few hundred megabytes. With LIMIT, PostgreSQL can use a top-N heapsort that keeps only the needed rows in memory.
3Raising work_mem for This Query Only
If the report really must sort millions of rows, more memory is the right fix, at the right scope. SET LOCAL changes work_mem for the current transaction only, so nothing else on the server is affected. ALTER ROLE sets it for every session of the reporting user.
- Read EXPLAIN (ANALYZE, BUFFERS)external merge, Disk: 1840000kB
- Can an index on the ORDER BY avoid the sort?YesAdd it and re-check the planNoLook at the rows and columns sorted
- Can the query sort fewer or narrower rows?YesFilter, aggregate or LIMIT firstNoGive this query more memory
- SET LOCAL or ALTER ROLE work_memnever the global default
- Re-run EXPLAIN ANALYZEcompare time and Disk size
5 steps in order. Play them, or step through them one at a time.
Notice that 512 MB did not remove the spill entirely. The in-memory representation of rows is usually larger than the temporary files, so a 1.8 GB spill may need well over 2 GB of work_mem to sort fully in memory. Even so, a larger work_mem means fewer, longer sorted runs and fewer merge passes, which often cuts the time a lot. We test a few values, such as 256 MB, 512 MB and 1 GB, and pick the smallest that brings the query to an acceptable time. In a Spring service, the reporting code can run SET LOCAL at the start of its @Transactional method, or the reports can use their own DataSource that logs in as the reporting role.
4What We Avoid Changing, and Why
We avoid raising work_mem globally. work_mem is not a limit per query; it is per sort or hash node, and hash nodes may use up to twice that with the default hash_mem_multiplier. A busy server with 100 connections, each running a query with three such nodes, would be allowed 100 x 3 x 1 GB = 300 GB with a global 1 GB setting. That will not all happen at once on a quiet day, but on the busiest day it might, and the Linux out-of-memory killer then ends a PostgreSQL process, which makes the server restart all connections.
We also avoid tricks that hide the symptom, such as turning off planner options like enable_sort or enable_hashagg globally, which change plans for every other query. The fix should be as narrow as the problem.
5Finding Other Queries That Spill
One spilling query usually means there are others. The setting log_temp_files logs every temporary file above a given size, together with the statement that created it, so we can see which queries spill and how much.
With that list, we fix each query the same way: remove the sort if we can, otherwise give that query or role more memory.
6Follow-up questions
Why is the in-memory sort bigger than the disk size shown?
Because rows in memory carry overhead such as tuple headers and pointers used by the sort, while temporary files store them compactly. So to sort fully in memory we usually need noticeably more work_mem than the Disk value in the plan, and the only reliable way to know is to test with EXPLAIN ANALYZE.
Would adding more RAM to the server fix it?
Only if we also raise work_mem, and the global risk stays the same. More RAM helps caching, but the sort is limited by work_mem, not by free memory. The targeted settings are still the right tool.
Can parallel query help this sort?
Sometimes. With parallel workers, each worker sorts part of the rows with its own work_mem, then a Gather Merge combines them. That spreads the work across CPU cores but also multiplies memory use by the number of workers, so it needs the same care.
7Conclusion
In this answer, we read Sort Method: external merge Disk: 1840000kB as a sort that needed more than work_mem and spilled 1.8 GB to temporary files. We first tried to remove the sort with an index on the ORDER BY columns or by sorting fewer and narrower rows, then raised work_mem only for this query with SET LOCAL or for the reporting role with ALTER ROLE, testing a few values. We avoided a global increase, because work_mem applies per node and per connection and can exhaust memory, and we used log_temp_files and pg_stat_statements to find other spilling queries.
Open with
The plan says the sort did not fit in work_mem, so PostgreSQL sorted chunks, wrote about 1.8 GB of temporary files and merged them from disk. The scan only took about 6 seconds, so the sort is where the time goes.
Then, if they want more
First I would check whether the sort is needed: an index on the ORDER BY columns can give rows already in order, especially with a filter or LIMIT, and often a report sorts millions of wide rows when it could aggregate, filter or sort just the keys first.
If the sort really is needed, I would raise work_mem only for that query, with SET LOCAL work_mem inside the transaction, or for the reporting role with ALTER ROLE reporting SET work_mem. I would test a few values, because the in-memory size is bigger than the disk size, so 512 MB may still spill but with fewer merge passes.
What I would not do is raise work_mem globally: it applies per sort or hash node, per connection, and hash nodes can use double, so 100 connections with a few nodes each could ask for hundreds of gigabytes and trigger the OOM killer. I would also not disable planner options globally.
Finally, I would set log_temp_files and check temp_blks_written in pg_stat_statements to find other queries that spill.
About this answer
- Last updated
- 12 November 2026
- 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
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 "EXPLAIN (ANALYZE, BUFFERS) on a reporting query shows 'Sort Method: external merge Disk...": https://scrivio-interview-library.netlify.app/databases/postgresql/9f1d28c6d4/