Quick Answers on GROUP BY and COUNT
"How many of each?" is one of the first real questions people ask a database. GROUP BY and COUNT answer it. These quick answers cover the questions learners send us most, using one small example table.
The example
CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT, kind TEXT, owner TEXT);
INSERT INTO pets (name, kind, owner) VALUES
('Bo', 'dog', 'Ana'), ('Mia', 'cat', 'Ana'), ('Rex', 'dog', 'Ben'),
('Tia', 'cat', NULL), ('Zed', 'fish', 'Ben');
The basics
How do I count all rows?
SELECT COUNT(*) FROM pets; returns 5.
How do I count per kind of pet?
SELECT kind, COUNT(*) AS how_many FROM pets GROUP BY kind;
Result: cat 2, dog 2, fish 1. GROUP BY makes one result row per distinct kind.
What is the difference between COUNT(*) and COUNT(owner)?
COUNT(*) counts rows. COUNT(owner) counts rows where owner is not NULL. Here they give 5 and 4, because Tia has no owner recorded.
How do I count different values only?
SELECT COUNT(DISTINCT owner) FROM pets; returns 2 (Ana and Ben).
Filtering groups
How do I show only kinds with more than one pet?
Use HAVING, which filters after grouping:
SELECT kind, COUNT(*) FROM pets GROUP BY kind HAVING COUNT(*) > 1;
Why can't I use WHERE for that?
WHERE runs before the groups exist, so it cannot see the count. Use WHERE to filter rows first and HAVING to filter groups afterwards. You can use both in one query.
Common errors
"column must appear in the GROUP BY clause or be used in an aggregate function"
You selected a column that has several different values in a group, such as name while grouping by kind. The database cannot pick one. Either add it to GROUP BY or wrap it in a function such as MIN(name). (SQLite and some MySQL settings allow this and silently pick a value, which is why it can seem to work and then confuse you on another database.)
Why are my counts too high after a JOIN?
Joining multiplies rows. If an owner has three pets and two addresses, a join can produce six rows. Count a unique id with COUNT(DISTINCT pets.id), or count before joining.
Ordering and naming
How do I show the biggest groups first?
Add ORDER BY how_many DESC after GROUP BY.
Can I group by more than one column?
Yes: GROUP BY owner, kind gives one row per owner-and-kind pair.
Quick reference
| You want | Write |
|---|---|
| Total rows | COUNT(*) |
| Rows with a value | COUNT(column) |
| Different values | COUNT(DISTINCT column) |
| One row per group | GROUP BY column |
| Filter groups | HAVING condition |
See the order in which these steps run in watching a SELECT query run, step by step.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.
This is a static page of sample discussion topics. There is no live forum, membership or user community on this site.