MySQL
GROUP BY
concatenate strings
SQL tutorial
database management

How to use GROUP BY to concatenate strings in MySQL?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

In MySQL, the GROUP BY clause is typically used to group rows that have the same values in specified columns into aggregated data such as sums and counts. However, a lesser-known functionality is its capability to concatenate strings. This article will guide you through using GROUP BY to concatenate strings, enhancing your data manipulation skills in MySQL.

Understanding String Concatenation in SQL

Concatenation is the process of joining two or more strings end-to-end. In MySQL, the CONCAT() function is often used for this purpose. While CONCAT() works well for merging strings within a single row, combining strings across multiple rows requires a different approach. This is where aggregation functions and GROUP BY come into play.

Using GROUP BY with String Aggregation

The GROUP BY clause groups rows sharing a specified column value, while aggregate functions compute a set of values from the grouped rows. Typically, aggregate functions like SUM, AVG, or COUNT are numeric. For strings, MySQL provides the GROUP_CONCAT() function, which allows concatenation of multiple string values into a single string.

Example Scenario

Consider a table employees:

employee_iddepartmentfirst_name
1SalesJohn
2SalesJane
3HRJake
4HRKate

Suppose we want to concatenate employee names grouped by their department. Here, GROUP BY combined with GROUP_CONCAT() can help.

Building the Query

Step 1: Basic Query Structure

Start by identifying the columns required for the result: department and a concatenated string of first_name.

sql
SELECT department, GROUP_CONCAT(first_name) AS employees
FROM employees
GROUP BY department;

Step 2: Running the Query

Executing this query will give us the following results:

departmentemployees
SalesJohn,Jane
HRJake,Kate

This output shows the concatenated names of employees in each department, effectively utilizing GROUP BY with GROUP_CONCAT().

Enhancing the Query

Specifying a Separator

By default, GROUP_CONCAT() uses a comma to separate concatenated strings. You can customize this separator using the SEPARATOR keyword.

sql
SELECT department, GROUP_CONCAT(first_name SEPARATOR '; ') AS employees
FROM employees
GROUP BY department;

This would result in an output like:

departmentemployees
SalesJohn; Jane
HRJake; Kate

Ordering Concatenated Results

To order the names within each group, you can use the ORDER BY clause within GROUP_CONCAT().

sql
SELECT department, GROUP_CONCAT(first_name ORDER BY first_name ASC) AS employees
FROM employees
GROUP BY department;

In the above query, employee names within each department will be sorted alphabetically in the concatenated result.

Handling Larger Data with Limits

GROUP_CONCAT() has a limit on the length of the concatenated result, controlled by the group_concat_max_len session variable. If you expect very large concatenation results, you might need to adjust this limit.

sql
SET SESSION group_concat_max_len = 10000;

Summary Table

Here is a summary table of key points for using GROUP BY to concatenate strings:

FeatureSyntax ExampleDescription
Basic ConcatenationGROUP_CONCAT(first_name)Concatenates strings within each group
Custom SeparatorGROUP_CONCAT(first_name SEPARATOR '; ')Uses '; ' as a separator between strings
Ordering ResultsGROUP_CONCAT(first_name ORDER BY first_name ASC)Orders the names alphabetically in the result
Adjusting Max LengthSET SESSION group_concat_max_len = 10000;Increases the maximum allowed length of the result

Conclusion

Utilizing GROUP BY in conjunction with GROUP_CONCAT() in MySQL offers a powerful method for concatenating strings across grouped rows. Whether you're handling hierarchically structured data or simply need formatted string outputs, this approach is both versatile and efficient. By customizing separators, ordering, and length limits, you can tailor the output to suit a wide range of data presentation needs.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.