In one sentence

Every column in SELECT must be either:

  1. In the GROUP BY clause, OR
  2. Inside an aggregate function

If you know Python

Like Python’s collections.Counter or pandas groupby(), SQL’s GROUP BY lets you summarize data by category. It allows you to count, sum, and average across groups.

from collections import Counter
city_counts = Counter(c['city'] for c in customers)

# or with pandas
df.groupby('city').size()

The issue with these is that if you simply want to know how many customers are in each city, you are sending all the records to Python and letting it manage them. SQL can do this in the database and simply return the city and the number of customers in that city.

SELECT city, COUNT(*) AS customer_count
FROM customers
GROUP BY city

Same result, but the work happens on the database server.

The usual mistake

-- ✅ Correct: city is in GROUP BY, COUNT is aggregate
SELECT city, COUNT(*)
FROM customers
GROUP BY city

-- ❌ Wrong: name is not grouped or aggregated
SELECT city, name, COUNT(*)
FROM customers
GROUP BY city
-- Error! Which "name" should it show for each city?

This trips up everyone. The database doesn’t know which name to pick when there are 50 customers in San Antonio, so it either throws an error or gives bad results. If you are receiving errors or unexpected results when using aggregate functions and GROUP BY, this is the first thing that you should check, twice.

Example

You can use multiple aggregate functions for the same GROUP BY

SELECT city,
       COUNT(*) AS total,
       MIN(signup_date) AS first_signup,
       MAX(signup_date) AS last_signup
FROM customers
GROUP BY city

..or GROUP BY multiple columns

SELECT city, is_premium, COUNT(*) AS count
FROM customers
GROUP BY city, is_premium

Notice that in both these examples any column in the SELECT clause that is not an aggregate function is in the GROUP BY clause.

Go deeper

GROUP BY: Aggregating Your Data, post 10 of SQL for Python Developers: the aggregate functions, how WHERE and ORDER BY combine with GROUP BY, and the order the database runs them in.