Description
Concatenates non-null values from a group into a single string. This function is a syntactic sugar for the group_concat function, designed to be compatible with the PostgreSQL and SQL Server functions of the same name. Its underlying implementation fully reuses the logic of the existing group_concat function.Syntax
Parameters
expr: the values to concatenate, with null values ignored. It must evaluate to VARCHAR. You can optionally specifyDISTINCTto eliminate duplicate values from the output string. If you want to concatenate multipleexprdirectly, use concat or concat_ws to specify formats.delimiter: the required separator used to concatenate non-null values from different rows. It must be of VARCHAR type. To eliminate the separator, specify an empty string''.- Items in ORDER BY can be unsigned integers (starting from 1), column names, or normal expressions. The results are sorted in ascending order by default. You can also explicitly specify the ASC keyword. If you want to sort results in descending order, add the DESC keyword to the name of the column you are sorting.
NOTE
- STRING_AGG is a PostgreSQL and SQL Server compatible function where the delimiter is specified as the second parameter and is required.
- For MySQL-style syntax (using the
SEPARATORkeyword), use group_concat.
Return value
Returns a string value for each group and returns NULL if there are no non-NULL values. You can limit the length of the string returned by string_agg by setting the session variablegroup_concat_max_len, which defaults to 1024. Minimum value: 4. Unit: characters.
Example:
Examples
-
Create a table
employeeswhich contains employee information. -
Use string_agg to concatenate values.
Example 1: Concatenate employee names in each department with comma as delimiter, ignoring NULL values.
Example 2: Concatenate employee names using
|as delimiter.Example 3: Concatenate distinct employee names using comma as delimiter.Example 4: Concatenate employee names sorted by salary in ascending order.Example 5: Concatenate employee names sorted by salary in descending order.Example 6: Concatenate employee information in “name:salary” format using nested concat().Example 7: Concatenate all employee names globally (without GROUP BY).Example 8: No matching result is found and NULL is returned.Example 9: Limit the length of the returned string to 10 characters.