w3resource

Using GROUP_CONCAT and STRING_AGG for String Aggregation in SQL


Using GROUP_CONCAT in MySQL & STRING_AGG in PostgreSQL

Write a SQL query to concatenate employee names by department, using GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.

Solution:

-- MySQL
SELECT DepartmentID, GROUP_CONCAT(Name SEPARATOR ', ') AS EmployeeNames
FROM Employees
GROUP BY DepartmentID;

-- PostgreSQL
SELECT DepartmentID, STRING_AGG(Name, ', ') AS EmployeeNames
FROM Employees
GROUP BY DepartmentID;

Explanation:

  • Purpose of the Query :
    • The goal is to demonstrate how string aggregation differs between MySQL and PostgreSQL.
  • Key Components :
    • GROUP_CONCAT (MySQL): Concatenates values with a separator.
    • STRING_AGG (PostgreSQL): Achieves the same result with different syntax.
  • Why Compare String Aggregation?:
    • String aggregation functions vary across platforms, impacting query portability.
    • Understanding these differences ensures accurate results.
  • Real-World Application :
    • In reporting systems, concatenating names supports concise summaries.

Additional Notes:

  • Use GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.
  • Test queries on all target platforms to ensure consistent results.
  • Important Considerations:
    • Handle null values to avoid unexpected results.

For more Practice: Solve these Related Problems:

  • Write a SQL query to concatenate product names by category, using GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.
  • Write a SQL query to concatenate customer names by city, using GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.
  • Write a SQL query to concatenate order IDs by customer, using GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.
  • Write a SQL query to concatenate employee names by project, using GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise:Using Recursive Queries Across Databases.
Next SQL Exercise: Using MERGE in SQL Server and INSERT ... ON DUPLICATE KEY UPDATE in MySQL.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.