4 Hours

6. Analytics: Aggregations & Grouping

Data Science

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

COUNT()

Returns the number of rows. COUNT(*) is fast, but COUNT(column) only counts non-null values.

SUM()

Adds up numeric values. Mandatory for financial reporting.

AVG()

Calculates the mathematical mean. Use for Average Order Value.

MIN/MAX

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.

SQL
-- 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.

Performance Tip: Always use 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

  1. Raw Filter: Use WHERE to target a timeframe (e.g., created_at > <strong><code>2024-01-01).
  2. Identify Buckets: What are you grouping by? (e.g., region or month).
  3. Calculate Metrics: Add your SUM, COUNT, or AVG functions.
  4. Filter Results: Use HAVING if you only care about regions with > 100 sales.
  5. Presentation: Add ORDER BY to put the top performers at the top.

Knowledge Check

Ready to test your understanding of 6. Analytics: Aggregations & Grouping?

Back