GROUP BY in SQL

Level 372 keystrokes

GROUP BY groups rows with the same values and allows aggregate functions per group.

SQL code

1SELECT
-- One result row per department
2 department,
-- COUNT(*) counts the rows (employees) in each group
3 COUNT(*) AS count
4FROM
5 employees
-- GROUP BY puts rows with the same department into one group
-- Without ORDER BY, the order of the groups may differ
6GROUP BY
7 department;

Output

+------------+-------+
| department | count |
+------------+-------+
| Sales      |     5 |
| IT         |     8 |
| HR         |     3 |
+------------+-------+
3 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • ,× 1
  • ;× 1
  • (× 1
  • )× 1
  • *× 1

More SQL examples at level 3

← SQL typing practice