6. Analytics: Aggregations & Grouping
Answering Business Questions
In production, you don't just get data — you process data. Questions like What is the average revenue per user? or How many signups did we have last Tuesday?' are handled by the Aggregation Engine. Doing this in your app code is 100x slower than doing it directly in SQL.
The Aggregate Functions
Returns the number of rows. COUNT(*) is fast, but COUNT(column) only counts non-null values.
Adds up numeric values. Mandatory for financial reporting.
Calculates the mathematical mean. Use for Average Order Value.
Finds the boundaries of your data set (e.g., Earliest Login).
The GROUP BY Rule
Grouping is the most powerful tool in SQL, but it has one strict rule that confuses beginners: Every column in your SELECT must either be in the GROUP BY clause or wrapped in an aggregate function.
-- Correct Grouping Pattern SELECT category, COUNT(*) as product_count, AVG(price) as avg_price FROM products GROUP BY category HAVING COUNT(*) > 5; -- Filter the GROUPS, not the rows!
HAVING vs WHERE
This is a common interview question. WHERE filters the individual rows BEFORE they are grouped. HAVING filters the results AFTER they are grouped and calculated.
WHERE as much as possible to reduce the number of rows the database has to group. Grouping is memory-intensive.Step-by-Step: Building a Dashboard Query
- Raw Filter: Use
WHEREto target a timeframe (e.g.,created_at > <strong><code>2024-01-01). - Identify Buckets: What are you grouping by? (e.g.,
regionormonth). - Calculate Metrics: Add your
SUM,COUNT, orAVGfunctions. - Filter Results: Use
HAVINGif you only care about regions with > 100 sales. - Presentation: Add
ORDER BYto put the top performers at the top.
Knowledge Check
Ready to test your understanding of 6. Analytics: Aggregations & Grouping?