GROUP BY

Updated · 8 min read
mediumPostgreSQL 18sqlgroup-byaggregatestring-agginterview

GROUP BY splits the rows into groups and summarizes each group separately. An aggregate on its own gives one answer for the whole table: the total of all payments. With GROUP BY student_id, you get one total per student. "How much has each student paid?", "How many courses per technology?" and "How much came in each month?" are all GROUP BY questions. This lesson covers how grouping works, grouping by several columns, the one rule that trips everyone up, how NULL forms its own group, and listing a group's values in one cell.

In One Minute

  • GROUP BY column puts rows with the same value together; the result has one row per group.
  • Aggregates such as count and sum then work within each group.
  • Every column in SELECT must be in the GROUP BY or inside an aggregate.
  • Rows with NULL in the grouping column form one group of their own.
  • string_agg(title, ', ') lists a group's values in one cell.

The Basics

SQL
SELECT grouping_column, aggregate_function(column)
FROM table_name
GROUP BY grouping_column
ORDER BY grouping_column;

How many payments has each student made, and for how much?

SQL▶ Try it
SELECT student_id, count(*) AS payments, sum(amount_usd) AS total
FROM payments
GROUP BY student_id
ORDER BY student_id;
Output
 student_id | payments |  total
------------+----------+---------
        101 |        5 | 1700.00
        103 |        2 |  450.00
(2 rows)

The database sorted the seven payments into piles by student_id, five for Srihitha (101) and two for Navika (103), then counted and totaled each pile. Advitha (102) doesn't appear: she has no payments, so there's no pile for her. (Showing students with no payments needs a join, covered in LEFT JOIN.)

Seven payments become two groups; each group becomes one result row

Grouping by Several Columns

List several columns and each different combination becomes a group. How much has each student paid for each course?

SQL▶ Try it
SELECT student_id, course_id, count(*) AS payments, sum(amount_usd) AS paid
FROM payments
GROUP BY student_id, course_id
ORDER BY student_id, course_id;
Output
 student_id | course_id | payments |  paid
------------+-----------+----------+--------
        101 |         1 |        1 | 450.00
        101 |         2 |        2 | 500.00
        101 |         3 |        1 | 550.00
        101 |         4 |        1 | 200.00
        103 |         5 |        2 | 450.00
(5 rows)

Five groups: one per student-and-course pair. Two of them have two payments, the installments you've seen before, and each pair's total matches its course fee.

Every Column Grouped or Aggregated

Every column in the SELECT list must either be in the GROUP BY or be inside an aggregate. The reason: each group becomes one row, and a column like paid_on has five different values in Srihitha's group. Which one should the single row show? SQL refuses to guess:

SQL▶ Try it
SELECT student_id, paid_on, sum(amount_usd)
FROM payments
GROUP BY student_id;
Output
ERROR:  column "payments.paid_on" must appear in the GROUP BY clause or be used in an aggregate function

The fix is to decide what you want from the group: max(paid_on) for the latest payment, min(paid_on) for the first, or add paid_on to the GROUP BY if you want one row per date.

A group has many paid_on values; pick one with an aggregate, or group by it

There's one exception you may notice in PostgreSQL. If you group by a table's primary key, you can select the table's other columns too, because each key value has exactly one row, so there's only one possible value:

SQL▶ Try it
SELECT student_id, first_name, state
FROM students
GROUP BY student_id
ORDER BY student_id;
Output
 student_id | first_name | state
------------+------------+-------
        101 | Srihitha   | CA
        102 | Advitha    | CA
        103 | Navika     | TX
(3 rows)

This follows the SQL standard, but not every database supports it, so listing every selected column in the GROUP BY is the portable habit.

NULL Forms Its Own Group

Rows with NULL in the grouping column are grouped together, the same way DISTINCT treats them as one. Payments per method:

SQL▶ Try it
SELECT method, count(*) AS payments, sum(amount_usd) AS total
FROM payments
GROUP BY method
ORDER BY method;
Output
 method | payments |  total
--------+----------+---------
 card   |        4 | 1475.00
 check  |        2 |  475.00
 NULL   |        1 |  200.00
(3 rows)

Payment 5, with no recorded method, forms the NULL group. It sorts last because PostgreSQL places NULL last when sorting up, as in ORDER BY.

Grouping by a Calculation

You can group by an expression, not just a column. Payments per month, using PostgreSQL's date_trunc, which rounds a date down to the first day of its month:

SQL▶ Try it
SELECT date_trunc('month', paid_on)::date AS month,
       count(*) AS payments,
       sum(amount_usd) AS total
FROM payments
GROUP BY date_trunc('month', paid_on)
ORDER BY month;
Output
   month    | payments |  total
------------+----------+---------
 2025-08-01 |        1 |  450.00
 2025-10-01 |        1 |  250.00
 2025-11-01 |        1 |  225.00
 2025-12-01 |        3 | 1025.00
 2026-01-01 |        1 |  200.00
(5 rows)

December was the busiest month: three payments, $1,025.00. date_trunc is PostgreSQL only; the standard EXTRACT(MONTH FROM paid_on) gives just the month number, and Date Functions compares them.

Listing a Group's Values

string_agg joins a group's values into one text value, with the separator you choose. The course titles for each technology:

SQL▶ Try it
SELECT technology, count(*) AS courses, string_agg(title, ', ' ORDER BY title) AS titles
FROM courses
GROUP BY technology
ORDER BY technology;
Output
 technology | courses |                 titles
------------+---------+-----------------------------------------
 Git        |       1 | Git Basics
 Java       |       3 | Java Basics, Java Collections, Java OOP
 JavaScript |       1 | JavaScript Basics
 SQL        |       1 | SQL Basics
(4 rows)

The ORDER BY title inside the parentheses sorts the titles within each list. The standard calls this function LISTAGG, which Oracle uses; SQL Server and PostgreSQL use string_agg, and MySQL uses GROUP_CONCAT (MySQL only). PostgreSQL also has array_agg, which gathers the values into an array instead of text (PostgreSQL only). Tabs showing each database's version are coming to this course.

Each technology's titles, joined into one cell

Common Mistakes

Selecting a column that isn't grouped or aggregated. It fails with must appear in the GROUP BY clause or be used in an aggregate function. Decide which value the group should show.

Expecting groups in order. GROUP BY doesn't sort. Add ORDER BY.

Expecting a group for something with no rows. Advitha has no payments, so GROUP BY student_id on payments has no group for her.

Filtering groups with WHERE. WHERE filters rows before grouping; to filter groups by their totals, use HAVING, next.

Interview Corner

What does GROUP BY do?

It puts rows with equal values in the grouping columns into groups, and returns one row per group; aggregate functions in the SELECT list are computed separately for each group.

Why does SELECT student_id, paid_on, sum(amount_usd) FROM payments GROUP BY student_id fail?

A group has several paid_on values, and one result row can't show them all. Every selected column must be grouped or aggregated: use max(paid_on), or group by paid_on too.

How does GROUP BY treat NULL?

All rows with NULL in the grouping column form a single group.

Practice

Challenge: For each enrollment status, show how many enrollments have it and the list of student_id values, sorted, in one cell separated by commas. Sort the result by status. (Hint: string_agg needs text, so write student_id::text.)

Show solution
SQL▶ Try it
SELECT status, count(*) AS enrollments, string_agg(student_id::text, ', ' ORDER BY student_id) AS students
FROM enrollments
GROUP BY status
ORDER BY status;
Output
  status   | enrollments |        students
-----------+-------------+-------------------------
 active    |           5 | 101, 101, 102, 102, 103
 completed |           2 | 101, 101
(2 rows)

Five enrollments are active and two completed. Students 101 and 102 each appear twice in the active list, because Srihitha and Advitha each have two active enrollments.

Quick check: GROUP BY

3 questions
1How many rows does SELECT student_id, sum(amount_usd) FROM payments GROUP BY student_id; return?
2Which SELECT list is valid with GROUP BY student_id?
3Payment 5 has no method. In GROUP BY method, where does it go?

Key Takeaways

You want toWrite
A total per studentSELECT student_id, sum(amount_usd) FROM payments GROUP BY student_id
Per student and courseGROUP BY student_id, course_id
Per month (PostgreSQL)GROUP BY date_trunc('month', paid_on)
A list per groupstring_agg(title, ', ' ORDER BY title)

Was this tutorial helpful?

Lesson 25 of 115