Ira SQL ProIra SQL Pro

SQL GROUP BY Multiple Columns

intermediateaggregation
2 min read

What is GROUP BY Multiple Columns?

You can group by more than one column to create finer subcategories. Each unique combination of values becomes its own group.

Syntax

SELECT col1, col2, AGGREGATE(col3)
FROM table_name
GROUP BY col1, col2;

When to Use

  • Revenue by product and month
  • Student counts by grade and age
  • Sales by region and category

Key Points

  1. Unique Combinations — Each unique pair (or tuple) of grouping columns forms a distinct group.
  2. More Groups — Adding columns to GROUP BY creates more, smaller groups.
  3. SELECT Rule — All non-aggregated columns must appear in GROUP BY.
  4. ROLLUP — PostgreSQL supports GROUP BY ROLLUP(col1, col2) for subtotals.
  5. CUBEGROUP BY CUBE(col1, col2) generates all possible grouping combinations.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

SQL GROUP BY Multiple Columns Challenge

Write a query that solve this task: count students for each grade-age combination.

Expected result

One row per unique grade-age combination with the count.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is GROUP BY Multiple Columns?

Initializing database...Each run starts from fresh sample data.

More Examples

Employees by department and role

Count employees in each department-role pair.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

How many columns can I GROUP BY?
There is no practical limit, but grouping by many columns creates very granular groups.
What is GROUP BY ROLLUP?
ROLLUP generates subtotal rows. GROUP BY ROLLUP(department, role) produces groups for each department+role, each department alone, and a grand total.

Related Topics