DELAPARRA
Index
Color
NL
Category: SQL

GROUP BY

Explained by Updated

What is GROUP BY?

GROUP BY: Collapses rows that share the same key into one row per group, so aggregate functions run per group. GROUP BY collapses rows that share the same value into one row per group, so aggregate functions like COUNT and SUM run per group. SELECT country, COUNT(*) FROM customers GROUP BY country counts customers per country.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about GROUP BY

How is GROUP BY used in practice?

It is the foundation of almost every report: revenue per month, orders per customer, tickets per status.

What should you keep in mind with GROUP BY?

Every column in the SELECT must either be in the GROUP BY or wrapped in an aggregate function. MySQL used to allow other columns and return an arbitrary value from the group, which caused subtle bugs; modern versions refuse by default with ONLY_FULL_GROUP_BY. Grouping by date parts, such as DATE(created_at), works but cannot use a normal index, so for large tables a stored date column or summary table may be faster.

What does an example of GROUP BY look like?

SELECT user_id, COUNT(*) AS orders FROM orders GROUP BY user_id;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with G

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.