Ira SQL ProIra SQL Pro

SQL GROUP BY Clause

beginneraggregation
2 min read

What is GROUP BY?

GROUP BY divides rows into groups based on one or more columns. You then apply aggregate functions (COUNT, SUM, AVG, etc.) to each group independently.

Syntax

SELECT column, AGGREGATE(other_column)
FROM table_name
GROUP BY column;

When to Use

  • Summarizing data by category (sales by region, students by grade)
  • Creating pivot-style reports
  • Any time you need per-group statistics

Key Points

  1. SELECT Rule — Every non-aggregated column in SELECT must appear in GROUP BY.
  2. Execution Order — GROUP BY runs after WHERE but before HAVING and SELECT.
  3. Multiple Columns — You can group by multiple columns for finer granularity.
  4. NULLs — NULL values are grouped together as a single group.
  5. HAVING — Use HAVING to filter groups after aggregation.

Guided Practice

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

Practice challengeGuided learning mode

SQL GROUP BY Clause Challenge

Write a query that solve this task: count the number of students in each grade.

Expected result

One row per grade showing the grade and its student 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?

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

More Examples

Total orders per student

Sum order totals grouped by student.

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

Frequently Asked Questions

Why do I get an error when using GROUP BY?
The most common error is including a column in SELECT that is not in GROUP BY and is not inside an aggregate function.
Can I GROUP BY a column alias?
In PostgreSQL, yes. You can reference column aliases or column positions (GROUP BY 1). This is a PostgreSQL extension.

Related Topics