Hash-Based Aggregation: Grouping Data Without Sorting

Hash-based aggregation uses a hash table to group data for functions like COUNT or SUM, avoiding a costly sort. It's used in database query engines for GROUP BY operations, especially when distinct groups fit in memory.
Why it exists
Grouping and aggregating large datasets, like in a SQL GROUP BY query, is a fundamental but expensive operation. The classic approach, sorting the data by the grouping key first, becomes a major bottleneck with large data volumes, consuming significant CPU and I/O. Hash-based aggregation was developed as a faster alternative that avoids the sorting step entirely, trading predictable sort performance for potentially faster, memory-based lookups.
The mental model
Think of it like sorting mail into cubbyholes. Instead of sorting a giant pile of letters alphabetically by city (the sort-based approach), you give each city a specific cubbyhole (a hash bucket). As each letter arrives, you instantly place it in the correct city's cubbyhole. At the end, you just count the letters in each cubbyhole. This is much faster than sorting the whole pile, provided you have enough cubbyholes (memory) and they don't overflow.
How it works
When a database executes a GROUP BY query using this strategy, it creates an in-memory hash table. For each row of data it processes, it computes a hash value from the grouping key's columns. This hash value points to a bucket in the table. If an entry for that group already exists, the aggregate function is applied (e.g., a counter is incremented). If not, a new entry for that group is created. This process repeats for every row, building the final aggregates directly in the hash table.
When to use it
Query optimizers favor hash aggregation when the number of distinct groups (the cardinality of the grouping key) is expected to be low. It excels when the entire hash table, holding one entry per group, can comfortably fit in available RAM. This makes it ideal for smaller datasets or queries that group by columns with few unique values, like 'country_code' or 'product_category'.
When not to use it
The primary limitation is memory. If the number of unique groups is very large, the hash table can exceed available RAM, forcing the system to spill parts of it to disk. This "spilling" causes a dramatic performance drop, often making it slower than a sort-based approach. It's also less suitable for data with high skew, where many different keys hash to the same bucket, creating long collision chains that degrade lookup speed. If subsequent query steps require sorted data, a sort-based aggregation is more efficient.
One canonical example
A query like SELECT product_id, SUM(sales) FROM transactions GROUP BY product_id on a table with millions of transactions but only a few thousand unique products. The database can create a hash table with a few thousand entries. For each transaction row, it hashes the product_id, finds the corresponding entry, and adds the sale amount to that product's running total. This avoids sorting millions of rows.
Interview question
For a GROUP BY operation, when would a database query optimizer typically prefer hash-based aggregation over a sort-based approach?
- a.When the total dataset size is very large, making sorting impractical.
- b.When the query requires the final aggregated results to be returned in a sorted order.
- c.When the grouping key exhibits high data skew, causing many values to hash to the same bucket.
- d.When the number of unique groups is small enough for the aggregation state to fit in memory.Correct
Why? this is the answer
Hash-based aggregation excels when the number of distinct groups is low, allowing the in-memory hash table to comfortably hold all aggregation states. Options A, C, and D describe scenarios where hash-based aggregation is either not the primary consideration or is explicitly less suitable.
Just read this? Test yourself on what you have been reading.
Read the original → arxiv.org
- #database
- #query processing
- #aggregation
- #hash table
You just looked this up. Could you explain it out loud?
That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on database — each one lists the topics its interview covers.
See open roles