SQL Practice Logo

SQLPractice Online

GROUP BY Fundamentals: Functions

Module: Aggregate Functions & Grouping

-- Single column GROUP BY

SELECT

department,

COUNT(*) AS employee_count,

AVG(salary) AS avg_salary

FROM employees

GROUP BY department;

-- Multiple columns GROUP BY

SELECT

department,

job_title,

COUNT(*) AS count,

AVG(salary) AS avg_salary

FROM employees

GROUP BY department, job_title;

-- With WHERE filtering

SELECT

department,

COUNT(*) AS count

FROM employees

WHERE salary > 50000

GROUP BY department;

All non-aggregate columns must be in GROUP BY

GROUP BY comes after WHERE, before HAVING

One result row per unique group

NULL values form one group

Can group by multiple columns

Strict about GROUP BY columns

More lenient (can select non-grouped columns)

Strict about GROUP BY columns

Core references in this topic include GROUP BY, COUNT, SUM. Learn what each one does, when to use it, and the execution or engine rules that matter.

GROUP BY

Collects rows into groups so aggregate functions can compute one result per group.

GROUP BY department_id

COUNT

Counts rows or non-NULL values depending on the argument.

COUNT(*)

SUM

Adds numeric values together across the current group or window frame.

SUM(revenue)