Skip to content

Stockertim Dictionary · Technology

GROUP BY clause

Also called GROUP BY, SQL GROUP BY, grouping in SQL

In short

The part of an SQL query that gathers rows sharing the same value in one or more columns, so aggregate functions return one summary row per group.

  • Beginner
  • Concept
  • Checked

In detail

GROUP BY turns a list of rows into a summary. The query names one or more columns, and the database collects every row with the same combination of values into a group. Aggregate functions in the SELECT list are then calculated within each group, so SELECT region, SUM(amount) FROM sales GROUP BY region returns one row per region with its total.

Grouping by two columns gives one row per combination that actually occurs: GROUP BY region, month gives a row for each region in each month with sales. Combinations with no rows do not appear at all, so a month with no sales in a region is missing rather than shown as zero, which matters when the result feeds a chart or a comparison.

There is one firm rule. Every column in the SELECT list must either appear in GROUP BY or sit inside an aggregate function. Asking for customer_name while grouping only by region makes no sense, because each region holds many names; strict databases reject such a query, and a few lenient ones return an arbitrary name, which is worse.

NULL values form a group of their own, so a region left blank appears as one extra row. Grouping happens after WHERE has filtered the rows and before HAVING filters the groups. The same operation exists in spreadsheets as a pivot table and in pandas as the groupby method, so the idea carries across tools.

Worked example

A solar installer in Abuja has 300 job rows with columns state and fee, and wants revenue by state.

  1. Write: SELECT state, COUNT(*) AS jobs, SUM(fee) AS revenue FROM jobs GROUP BY state ORDER BY revenue DESC;
  2. The result has four rows. The top row reads FCT, 120 jobs, ₦36,000,000.
  3. Average fee for FCT: ₦36,000,000 / 120 = ₦300,000

Three hundred rows become a four-row summary, sorted with the largest state first.

In practice

GROUP BY produces most management tables: sales by branch, tickets by status, hours by employee and week. Analysts usually add COUNT(*) to every grouped query so that each total comes with the number of rows behind it.

Watch out

  • Groups with no rows do not appear; join to a list of all regions or months if zeros must be shown.
  • Text that differs only in spacing or case, such as Lagos and lagos, forms separate groups.

Learn it properly

Official sources

Facts last checked on 9 November 2026.

Education, not advice: the Stockertim Dictionary explains what terms mean. It never recommends buying or selling anything.

English