SQL GROUP BY with SUM, COUNT and AVG: Examples
SUM(price) without GROUP BY is one total for the whole table. Add GROUP BY and you get one total per product. Worked examples with the rows that come back.
In this chapter
A name and a SUM need a bucket
GROUP BY with SUM and COUNT: common questions
Why does SELECT name, SUM(price) fail without GROUP BY?
SUM collapses the table to one row, but name still has many values. GROUP BY name builds one row per name so each name has one total.
How do I count rows per category in SQL?
SELECT category, COUNT(*) FROM products GROUP BY category; returns one row per category with its row count.
More on GROUP BY and HAVING
- SQL GROUP BY Explained Visually, with Examples
- SQL GROUP BY with WHERE: Filter Rows Before Grouping
- SQL HAVING Clause Explained with Examples
- HAVING with COUNT and SUM: Filter Groups in SQL
- WHERE vs HAVING in SQL: Difference with Examples
- Invalid Use of Group Function: SQL HAVING Errors Fixed
- Column Not in GROUP BY Clause Error (ONLY_FULL_GROUP_BY)
- SQL Order of Execution: WHERE, GROUP BY, HAVING, LIMIT
- COUNT(*) vs COUNT(column) in SQL: How NULLs Are Counted
- SQL GROUP BY and HAVING Cheat Sheet
Keep learning
Overview
chapters · group by and having A name and a SUM need a bucket An individual column is one value per row. An aggregate is one value for a bucket. They share a SELECT only when GROUP BY says which rows belong together.
1. A name and a total cannot share a row
Build a SELECT yourself. Start with the failing one, then fix it by adding GROUP BY or removing the name.
2. One color, one bucket
Test SELECT columns below to see why unaggregated columns conflict, while aggregate functions like COUNT(), AVG() and SUM() compute valid single values for each bucket.
3. GROUP BY, then HAVING, then ORDER BY
The buckets form first. HAVING throws a bucket away. ORDER BY sorts the buckets that are left. Play it, or step one clause at a time. GROUP BY ORDER BY
4. The only way out of a bucket is a function
Aggregate functions On the bucket Question it answers How many rows Customers in each city Adds a number Revenue per product Average of the known values Salary per department Highest value Most expensive item in a category Lowest value Oldest order in a branch Every one of them skips NULL, except COUNT(*), which counts rows. The NULL chapters of this module show what that means in practice.
5. More columns, smaller buckets
GROUP BY Country, City makes one bucket per pair. Grouping by City alone can merge places that only share a name: London, UK and London, Canada. Compare the three choices. Real life: a customer list with two cities called London. GROUP BY Country GROUP BY City GROUP BY Country, City Four London customers, but Cara lives in London, Canada. One bucket for two different places is a wrong answer that looks right. One bucket per country. One bucket per (country, city) pair, so the two Londons stay apart.
6. The bucket key can be a calculation
YEAR(OrderDate) builds one bucket per year: 1996 and 1997 never share a row. GROUP_CONCAT lists what is inside a bucket in one cell (PostgreSQL and SQL Server call it STRING_AGG). SELECT YEAR(OrderDate) AS Year, COUNT(*)FROM OrdersGROUP BY YEAR(OrderDate) Beverages comes back as one row, with its product names glued into one string.
7. Group by the id and the name
Who watched the most movies? Count per customer, sort, keep the first row. Five views customer 101 Tommovie 1 to 5 GROUP BY id, name same pair, same bucket 101 · Tomevery row says Tom5 ! Real life check
Before you run it
Bucket. What should each output row mean? That expression goes in GROUP BY. Filter. Raw rows use WHERE. A SUM, COUNT or AVG uses HAVING. Order. Need a particular order? Say ORDER BY. Buckets come out in no promised order.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.