GROUP_CONCAT in SQL

Level 4135 keystrokes

GROUP_CONCAT concatenates values from multiple rows into a single string.

SQL code

-- Choose the columns to return
1SELECT
-- Department of each group
2 department,
-- GROUP_CONCAT joins values from many rows into one string
3 GROUP_CONCAT(
-- The value to join: each employee's name
4 name
-- Sort names alphabetically inside each group
5 ORDER BY name
-- Put a comma and a space between names
6 SEPARATOR ', '
-- Call the joined column members
7 ) AS members
-- Read rows from the employees table
8FROM
9 employees
-- One group, and one result row, per department
10GROUP BY
11 department
-- Sort result rows by department name
12ORDER BY
13 department;

Output

+------------+---------------------+
| department | members             |
+------------+---------------------+
| HR         | Alice, Bob          |
| IT         | Carol, Dan, 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