Data aggregation
MySQL

A Complete Guide to the MySQL GROUP_CONCAT Function

intro

Let's learn everything you need about the MySQL GROUP_CONCAT function to master data aggregation in groups of records.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

String concatenation is a common technique for aggregating data from multiple records. It involves taking one or more strings from a set of records and combining them into a single cohesive string. Due to the frequency of this operation, databases offer specialized functions to handle it efficiently. Enter the MySQL GROUP_CONCAT function!

In this article, you will see what the GROUP_CONCAT function is, how it works, and when and how to use it with real-world examples.

Let’s get started!

What Is the GROUP_CONCAT MySQL Function?

In MySQL, GROUP_CONCAT is an aggregate function that concatenates values from multiple rows into a single string. Specifically, this function returns a string containing the concatenated non-NULL values from a set of rows.

Like most SQL aggregate functions, GROUP_CONCAT is used alongside GROUP BY to merge data from each group. However, it can also be useful in scenarios that do not involve a GROUP BY clause but still require data aggregation — I’ll provide you with a couple of such scenarios later in the article.

MySQL GROUP_CONCAT: Syntax and Main Aspects

This is the syntax of GROUP_CONCAT in MySQL:

Copy
        
1 GROUP_CONCAT([DISTINCT] expr_1 [, expr_2, ..., expr_n] 2 [ORDER BY {unsigned_integer | col_name | expr} 3 [ASC | DESC] [, col_name ...]] 4 [SEPARATOR str_separator])

Where:

  • DISTINCT is an optional keyword that the uniqueness of values. In this case, it ensures that only unique values are considered in the concatenation. If added, duplicate values from the specified expressions will be removed before concatenating. More information on the SQL DISTINCT keyword.
  • expr_1 [, expr_2, ..., expr_n] are the SQL expressions or table columns whose values you want to concatenate. If you specify multiple expressions or columns, the MySQL GROUP_CONCAT function will concatenate their values.
  • ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [, col_name ...]: An optional ORDER BY clause that allows you to sort the concatenated values before they are combined into a single string. For more information about the parameters it accepts, read our guide on the SQL ORDER BY clause.
  • SEPARATOR str_separator specifies a custom string to aggregate the concatenated values with. If omitted, a comma (",") will be used by default as the separator between values. Last value is not separated (i.e. there’s no comma after the last value and you don’t need to remove the last comma value programmatically.)

Main Aspects

A few details that you need to know about the GROUP_CONCAT MySQL function are as follows:

  • NULL values are ignored, as the function only concatenates non-NULL values from a group.
  • The function only returns NULL only if there are no non-NULL values.
  • The result is truncated to the maximum length specified by the group_concat_max_len system variable, which has a default value of 1024. This value can be changed using SET as explained in the docs.
  • The return value is either a nonbinary or binary string, depending on whether the arguments are nonbinary or binary strings.
  • The result type is TEXT or BLOB unless group_concat_max_len is less than or equal to 512. In that case, the result type is VARCHAR or VARBINARY.

MySQL GROUP_CONCAT Examples

Now that you know what the GROUP_CONCAT function is, how to use it, and how it works, you are ready to explore some basic examples.

In the examples below, we will apply GROUP_CONCAT on the following users table:

The data inside the users table as displayed in DbVisualizer
The data inside the users table as displayed in DbVisualizer

Let’s dig into the examples!

Basic Usage

If we issue a query like the one below on a set of users:

Copy
        
1 SELECT GROUP_CONCAT(name);

The result will be as follows:

Copy
        
1 John,Jane,Michael,Emily,Chris,Sarah,David,Laura,Daniel,Emma

GROUP_CONCAT concatenates the values in the name column from each row in the table, separating them with a comma (the default separator).

Now, apply the GROUP_CONCAT MySQL function to a non-string column:

Copy
        
1 SELECT GROUP_CONCAT(age) 2 FROM users;

This time, the result string will be:

Copy
        
1 30,41,25,30,37,22,27

MySQL converts the numbers to their string representations and concatenates them with the default separator (", "). Also, note that NULL values were ignored.

Custom Separator

Here is how you can use MySQL GROUP_CONCAT with separator strings that are not commas:

Copy
        
1 SELECT GROUP_CONCAT(name SEPARATOR "; ") 2 FROM users;

The result will be:

Copy
        
1 John; Jane; Michael; Emily; Chris; Sarah; David; Laura; Daniel; Emma

Note that you can use any separator including complex strings, and that there’s no need for spacing either:

Copy
        
1 SELECT GROUP_CONCAT(name SEPARATOR "-@@@-") 2 FROM users;

This time, you will get:

Copy
        
1 John-@@@-Jane-@@@-Michael-@@@-Emily-@@@-Chris-@@@-Sarah-@@@-David-@@@-Laura-@@@-Daniel-@@@-Emma

Distinct Values

Assume you want to get only the unique age values of your users. You can achieve that with the DISTINCT as follows:

Copy
        
1 SELECT GROUP_CONCAT(DISTINCT age) 2 FROM users;

The result will be:

Copy
        
1 22,25,27,30,37,41

Note that there is only a single 30 in that string, which means the duplicate value was not considered in the final resulting set.

Note: Remember that MySQL applies an implicit sort behind the scenes as part of its DISTINCT optimizations. Here is why the numbers in the result string appear in ascending order.

Multiple Columns

GROUP_CONCAT in MySQL can also be used with multiple columns as below:

Copy
        
1 SELECT GROUP_CONCAT(name, " ", surname) 2 FROM users;

In this case, the result string will be:

Copy
        
1 John Doe,Jane Smith,Michael Johnson,Emily Davis,Chris Brown,Sarah Wilson,David Lee,Laura Martinez,Daniel Garcia,Emma Miller

As you can see, GROUP_CONCAT aggregates names and surnames before merging them.

Result Sorting

You can sort the results in a descending order after aggregating them, as in the following example:

Copy
        
1 SELECT GROUP_CONCAT(name ORDER BY name DESC) 2 FROM users;

The result will be:

Copy
        
1 Sarah,Michael,Laura,John,Jane,Emma,Emily,David,Daniel,Chris

Notice how the strings are in a descending—an inverse alphabetical—order.

Similarly, you can order them in ascending order using ASC.

Use Cases of GROUP_CONCAT in MYSQL

Time to explore the most common MySQL GROUP_CONCAT use cases!

Note: The queries in the following examples will be executed in DbVisualizer, the database client with the highest user satisfaction on the market. However, any other database client will do. 

Text Aggregation

GROUP_CONCAT is useful when it comes to data aggregation, for example for generative CSV-like data:

Copy
        
1 SELECT GROUP_CONCAT(id, ",", name, ",", surname, ",", email, ",", age SEPARATOR "\\n") AS csv_output 2 FROM users;

The result string will have CSV format:

Executing the GROUP_CONCAT query in DbVisualizer
Executing the GROUP_CONCAT query in DbVisualizer

GROUP_BY Queries

Assume you want to get the list of full names sorted alphabetically of the employees for each department. You can reach that goal with a MySQL GROUP_CONCAT query as below:

Copy
        
1 SELECT D.name, 2 GROUP_CONCAT(E.full_name ORDER BY E.full_name ASC SEPARATOR ", ") AS names 3 FROM departments D 4 LEFT JOIN employees E ON E.department_id = D.id 5 GROUP BY D.name 6 ORDER BY D.name ASC;

The result will be:

Note the list of names associated with each department
Note the list of names associated with each department

GROUP_CONCAT plays nicely with GROUP BY clauses for simplified data aggregation, doesn’t it?

Subqueries

The GROUP_CONCAT MySQL function can also be used in SQL subqueries to associate aggregated strings with records in the main table.

For example, you can use GROUP_CONCAT to get a list of employees’ full names for each department and sort the entire list in an alphabetical fashion:

Copy
        
1 SELECT D.name, 2 (SELECT GROUP_CONCAT(E.full_name ORDER BY E.full_name ASC SEPARATOR ", ") 3 FROM employees E 4 WHERE E.department_id = D.id) AS names 5 FROM departments D;

The result will be something like:

See the GROUP_CONCAT in action in DbVisualizer
See the GROUP_CONCAT in action in DbVisualizer

Note how GROUP_CONCAT comes in handy for data aggregation in subqueries. In particular, the above result is just like that of the first use case.

Et voilà! You are now the master of GROUP_CONCAT in MySQL.

Conclusion

This guide has walked you through GROUP_CONCAT in MySQL. You saw its syntax and which use cases it covers. Now, you know that GROUP_CONCAT helps you aggregate strings from multiple rows into a single result string.

Completing complex operations like data aggregation becomes easier with a tool for visual database management. This is exactly what a top-notch database client such as DbVisualizer offers!

In addition to full support for MySQL and other databases, this tool comes with in-line data editing, advanced query optimization, and drag-and-drop query construction capabilities. Download DbVisualizer for free now!

FAQ

Is the MySQL GROUP_CONCAT function part of the ISO/ANSI SQL standard?

No, the GROUP_CONCAT function is not part of the ISO/ANSI SQL standard. In detail, it is a MySQL-specific extension for concatenating values from multiple rows into a single string. While similar functionality may exist in other databases (e.g. STRING_AGG in PostgreSQL), GROUP_CONCAT itself is unique to MySQL and MariaDB.

Is it possible to use the GROUP_CONCAT MySQL function in a query without the GROUP_BY clause?

Yes, GROUP_CONCAT can also be used in queries without the GROUP BY clause. In this case, the function aggregates all rows from the result set into a single concatenated string.

What is the difference between CONCAT and GROUP_CONCAT in MySQL?

  • CONCAT combines multiple strings or column values into a single string. So, it is typically used for merging values from a single row.
  • GROUP_CONCAT concatenates values from multiple records into a single string. Thus, it is often used to merge values in groups or entire tables. Also, this function can include optional sorting and a custom separator.

How to use MySQL GROUP_CONCAT with separator strings?

To utilize MySQL GROUP_CONCAT with separator strings in MySQL, include the SEPARATOR keyword followed by the desired string. For example:

Copy
        
1 SELECT GROUP_CONCAT(column_name **SEPARATOR ", "**) AS result 2 FROM table_name;

This will concatenate the values of column_name with a comma and space as the separator.

What is the difference between GROUP_CONCAT and CONCAT_WS in MySQL?

  • GROUP_CONCAT aggregates values from multiple rows into a single result string.
  • CONCAT_WS combines multiple strings or column values into a single string using a specified separator, but it works only with values from a single row.
Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

How to Display All Duplicate Records in a MySQL Table

author Antonello Zanini tags MySQL 6 min 2025-01-08
title

The Most Interesting Functions in MySQL – A Guide

author Lukas Vileikis tags MySQL 5 min 2024-12-27
title

MySQL Primary Key: What It Is, How It Works, and When to Use It

author Lukas Vileikis tags Data Visualization Tools DbVisualizer MySQL 8 min 2024-12-23
title

SQL CHECK Constraint: Definitive Guide With Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-16
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

A Complete Guide to the MySQL COUNT Function

author Antonello Zanini tags MySQL 9 min 2024-12-09
title

MySQL Nullable Columns: Everything You Need to Know

author Antonello Zanini tags MySQL 6 min 2024-12-03
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

MySQL 9.0 and the New EXPLAIN Features

author Lukas Vileikis tags MySQL SQL 9 min 2024-11-27

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.