GROUP_CONCAT Function in SQL

Level 4115 keystrokes

GROUP_CONCAT joins the values of a group into one string, here one list of member names per department.

SQL code

-- Return each department and a list of its members
1SELECT
2 department,
-- GROUP_CONCAT joins the names of all rows in the group into one string
3 GROUP_CONCAT(
4 name
-- Order the names alphabetically inside the list
5 ORDER BY name
-- Separate names with ', ' (the default is a comma without a space)
6 SEPARATOR ', '
-- The result is cut at group_concat_max_len (1024 bytes by default)
7 ) AS members
8FROM
9 employees
-- One group, and one result row, per department; the row order is not guaranteed without ORDER BY
10GROUP BY
11 department;

Output

+------------+---------------------+
| department | members             |
+------------+---------------------+
| HR         | Alice, Bob          |
| IT         | Carol, Dave, Eve    |
| Sales      | Frank               |
+------------+---------------------+
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.

  • ,× 2
  • '× 2
  • _× 1
  • ;× 1
  • (× 1
  • )× 1

More SQL examples at level 4

← SQL typing practice