"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Concatenate Values Across Multiple Rows in PostgreSQL?

How Can I Concatenate Values Across Multiple Rows in PostgreSQL?

Posted on 2025-02-21
Browse:956

How Can I Concatenate Values Across Multiple Rows in PostgreSQL?

PostgreSQL Data row value connection

]

In relational database operations, it is often necessary to process the data before obtaining the final result. A common task is to concatenate values ​​of multiple rows based on common identifiers. In PostgreSQL, the GROUP_CONCAT function provides a simple solution for this.

GROUP_CONCAT Function

PostgreSQL version 9.0 and above introduces the GROUP_CONCAT aggregate function, which takes a set of values ​​in a column and concatenates them into a single string. GROUP_CONCAT syntax is as follows:

GROUP_CONCAT(DISTINCT expression [ORDER BY expression] [separator])

parameter:

  • DISTINCT: (optional) Prevent duplicate values ​​from being included in the result.
  • expression: The column or expression to be joined.
  • ORDER BY: (optional) Specifies the order of joining values.
  • separator: (optional) A character or string used to separate the concatenated values. Default is comma (,).

Example

Consider the following table called "sample_data":

TM677223
idvalue
TM674
TM679
TM99
TM99

To concatenate the values ​​in the "value" column of each unique "id", we can use
SELECT id, GROUP_CONCAT(value) AS concatenated_values
FROM sample_data
GROUP BY id;

SELECT id, GROUP_CONCAT(value) AS concatenated_values FROM sample_data GROUP BY id;

This query will produce the following output: concatenated_values4,9,72 2,3
id
TM67
TM99

]

]

] As you can see, the values ​​of each "id" are concatenated and separated by commas.

Alternative syntax for PostgreSQL 9.0
SELECT id, string_agg(value, ',') AS concatenated_values
FROM sample_data
GROUP BY id;
:

SELECT id, string_agg(value, ',') AS concatenated_values FROM sample_data GROUP BY id;

This syntax is equivalent to the

GROUP_CONCAT syntax described above. in conclusion

By using the

GROUP_CONCATHow Can I Concatenate Values Across Multiple Rows in PostgreSQL?
or the

string_agg

functions, you can easily concatenate multi-row data in PostgreSQL. Which syntax to choose depends on your PostgreSQL version and personal preferences.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3