Temporary Tables and Disk Spills: Why Sorts Get Slow

Sorts, GROUP BY, DISTINCT and window functions build temporary data in memory, then spill to disk past a limit. How to spot and avoid it.

In this chapter

Temporary tables and sort files: when a query spills to disk

More on Running a database in production

Keep learning

Overview

ORDER BY (no index in that order) Sort buffer, then sorted runs on disk GROUP BY / aggregates Hash table keyed by group (or a sort) Hash table or sort to drop duplicates Fewer, narrower columns UNION (not UNION ALL) Append, then hash or sort to drop duplicates UNION ALL when duplicates cannot occur Window functions Sort by PARTITION BY + ORDER BY, frame buffer Index in partition + order sequence Hash join, materialized subquery Hash table of one input / stored result Sort step, method says disk / external / merge Sort step, in memory, small top-N heap Fine: LIMIT kept it small Hash aggregate or hash join with several batches Temp / materialize node A result was stored before the next step Rows into the sort ≫ rows returned Filter earlier, or use an index that delivers the order Per-operation memory (sort / hash) Fewer spills RAM × operations per query × sessions Shared temp memory pool Many mid-sized temps stay in RAM Less RAM for the page cache Temp file location Must have room for the largest spill Temp size cap per query One runaway query cannot fill the disk That query fails instead Log spills above N bytes You find the offenders Log volume chapters · running a database in production Temporary tables and sort files: when a query spills to disk

1. Which operators need scratch space

Sort, hash aggregate, distinct, union and window operators each get a per-operation memory budget. Rows that fit stay in memory. Overflow spills to temp files on disk. Hash aggregate Memory budget per operation, per query fits → fast Temp files on disk 5x to 50x slower A query with 3 sorts and 2 hashes can use 5 budgets at once Operators that build scratch data Scratch structure Avoid or shrink it with

2. Sort spill: external merge sort

Too much data for the sort budget: sort a budget-full, write it as a run, repeat, then merge the runs. Too many runs to merge at once means another merge pass, and every pass rewrites all the data. Two shortcuts beat a bigger budget. LIMIT n keeps only n rows in a small heap (top-N), and a narrower select list shrinks every row. A big global budget is a trap: it is reserved per sort, per session.

3. Hash and temp tables: same budget, same cliff

GROUP BY, DISTINCT and UNION keep one row per group or distinct value. Row width matters more than any setting: three small columns fit at 20 million input rows, SELECT * fits almost nowhere.

4. How a plan reveals a spill

Signs in an actual (executed) plan, in any engine You see It means

5. Avoid it: index order, fewer rows, smaller rows

Select only the columns you need. Filter and LIMIT before the sort or group step. Add an index that delivers the order or the groups. Use UNION ALL where duplicates cannot occur. Only then raise the memory budget, for that one session or job. Knobs (generic) and what they trade ⚙ In real engines

Recap

Sort, hash aggregate, DISTINCT, UNION, window and hash join all build scratch data in a per-operation budget. Past the budget they spill: runs on disk plus merge passes, or hash batches on disk. Index order, earlier filters, LIMIT and narrower rows beat bigger budgets. Budgets multiply by operators and sessions, so raise them per job, not globally.

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.