# 3.2.3 The Sous Chefs (Aggregations) ![The Sous Chefs](assets/arch_sous_chefs.png) With data retrieved by the Runners and combined by the Assemblers, the final step in the Query Algebra is usually shaping the output for the Maitre D'. This falls to **The Sous Chefs**, a group of extremely stressed staff members tasked with squashing, sorting, and throwing away data. ### The Maitre D's Summary Let's see how the Sous Chefs squash our Cafe's data for the Maitre D'. #### 1. The Duck's Desk (Before Index: HashAggregate) If the orders aren't sorted, the staff member has to throw them into buckets (a Hash Table) on his Counter. This requires a lot of memory! ```sql EXPLAIN SELECT animal_id, count(*) FROM orders GROUP BY animal_id; -- Result: -- HashAggregate (cost=725000.00..750000.00 rows=1000 width=12) -- Group Key: animal_id -- -> Seq Scan on orders (cost=0.00..625000.00 rows=10000000) ``` #### 2. The Conveyor Belt (After Index: GroupAggregate) Once we hire an Index Clerk for `animal_id`, the data arrives at the staff member's station already perfectly sorted. He just stands there with a clicker and watches the plates pass by! ```sql -- The Clerk ensures the data is sorted as it's pulled CREATE INDEX idx_orders_animal ON orders(animal_id); EXPLAIN SELECT animal_id, count(*) FROM orders GROUP BY animal_id; -- Result: -- GroupAggregate (cost=0.43..12500.00 rows=1000 width=12) -- Group Key: animal_id -- -> Index Scan using idx_orders_animal on orders (cost=0.43..2500.00 rows=50000) ``` #### 3. The Portion Controller (Limit) This is the Head Chef's favorite way to save energy. ```sql EXPLAIN SELECT * FROM supply_deliveries LIMIT 1; -- Result: -- Limit (cost=0.00..0.02 rows=1 width=44) -- -> Seq Scan on supply_deliveries (cost=0.00..1845.00 rows=10000000) ``` Notice the **`cost`** at the top! Even though the Seq Scan below it costs 1,845 points, the **Limit** node knows it only needs one plate. It estimates the final cost at virtually zero (0.02) because it will pull the plug on the Runner the moment it gets what it wants! --- [[Chapter 3/3.2.2 - The Plate Assemblers (Joins)|← 3.2.2 - The Plate Assemblers (Joins)]] | [[Chapter 3/3.2 - Query Algebra|↑ 3.2 - Query Algebra]] | [[Chapter 3/3.3 - Sargability|3.3 - Sargability →]]