⚡0 XP🔥0

Aggregation with GROUP BY and HAVING

Lesson 3 of 8 ⏱ 4 min read ✎ 4 exercises ❓ 5-question quiz ▶ Runs SQL

Summarise data with COUNT, SUM, AVG, MIN, MAX and COUNT(DISTINCT), group results with GROUP BY, filter groups with HAVING, and understand the WHERE vs HAVING difference.

Aggregate functions#

Aggregate functions turn many rows into one value:

Function Returns
COUNT(*) number of rows
COUNT(column) number of non-NULL values
COUNT(DISTINCT column) number of unique values
SUM(column) total
AVG(column) average
MIN(column) / MAX(column) smallest / largest
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Aggregates ignore NULLs (except COUNT(*)):

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

GROUP BY - one result per group#

GROUP BY splits rows into groups and calculates aggregates for each - exactly like a pivot table.

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Grouping by several columns#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Grouping by a calculated value - orders per year#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

(strftime('%Y', date) extracts the year in SQLite. MySQL: YEAR(order_date); PostgreSQL: EXTRACT(YEAR FROM order_date).)

हिंदी में समझें

GROUP BY बिल्कुल pivot table जैसा है: data को किसी column के आधार पर समूहों (groups) में बाँटो, फिर हर समूह का COUNT / SUM / AVG निकालो।

जैसे GROUP BY status - हर status (Delivered, Cancelled...) का एक group बनेगा और COUNT(*) हर group में कितने orders हैं, वह बताएगा।

नियम: SELECT में जो column aggregate (COUNT, SUM...) के अंदर नहीं है, उसे GROUP BY में ज़रूर लिखें।

The GROUP BY rule#

Every column in SELECT must be either inside an aggregate function or listed in GROUP BY.

-- Wrong: which customer name should appear for each city?
SELECT city, name, COUNT(*) FROM customers GROUP BY city;

-- Right
SELECT city, COUNT(*) FROM customers GROUP BY city;
Common Mistake

SQLite (used here) and older MySQL versions allow the wrong query and return a random name - no error, just a silently wrong result. PostgreSQL, SQL Server and modern MySQL raise an error. Always follow the rule.

HAVING - filtering groups#

WHERE filters rows before grouping. HAVING filters groups after aggregation.

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Combining both:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run
WHERE HAVING
Filters individual rows groups
Runs before GROUP BY after GROUP BY
Can use aggregates? No Yes
Example WHERE status = 'Delivered' HAVING COUNT(*) > 20

Calculations inside aggregates#

You can aggregate expressions. Total units and average discount per order:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Revenue needs the price from products - you'll calculate it after learning JOINs in the next lesson.

Summary#

  • Aggregates: COUNT, SUM, AVG, MIN, MAX, COUNT(DISTINCT).
  • GROUP BY gives one row per group; every non-aggregated SELECT column must be grouped.
  • WHERE filters rows before grouping; HAVING filters groups after.
  • You can group by calculated values like the year of a date.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Orders by payment mode

Show each payment_mode and the number of orders as orders, most used first.

Database: shop (see the tables in this lesson)
2

Average price by category

Show each product category, the number of products, and the average price rounded to 2 decimals (avg_price).

Database: shop (see the tables in this lesson)
3

Cities with 3 or more customers

Show cities that have at least 3 customers, with the count as customers, sorted by count (highest first) and then city name.

Database: shop (see the tables in this lesson)
4

Units sold per product

Using order_items, show each product_id and the total quantity sold as units, only for products that sold more than 30 units, highest first.

Database: shop (see the tables in this lesson)

Quick Quiz

Q1.

What does COUNT(*) return?

Q2.

Which query counts orders for each status?

Q3.

What is the difference between WHERE and HAVING?

Q4.

Which is invalid in standard SQL?

Q5.

How do you count how many different cities customers come from?