How to sort the result from string_agg()

SqlPostgresqlString Aggregation

Sql Problem Overview


I have a table:

CREATE TABLE tblproducts
(
productid integer,
product character varying(20)
)

With the rows:

INSERT INTO tblproducts(productid, product) VALUES (1, 'CANDID POWDER 50 GM');
INSERT INTO tblproducts(productid, product) VALUES (2, 'SINAREST P SYP 100 ML');
INSERT INTO tblproducts(productid, product) VALUES (3, 'ESOZ D 20 MG CAP');
INSERT INTO tblproducts(productid, product) VALUES (4, 'HHDERM CREAM 10 GM');
INSERT INTO tblproducts(productid, product) VALUES (5, 'CREAM 15 GM');
INSERT INTO tblproducts(productid, product) VALUES (6, 'KZ LOTION 50 ML');
INSERT INTO tblproducts(productid, product) VALUES (7, 'BUDECORT 200 Rotocap');

If I execute string_agg() on tblproducts:

SELECT string_agg(product, ' | ') FROM "tblproducts"

It will return the following result:

CANDID POWDER 50 GM | ESOZ D 20 MG CAP | HHDERM CREAM 10 GM | CREAM 15 GM | KZ LOTION 50 ML | BUDECORT 200 Rotocap

How can I sort the aggregated string, in the order I would get using ORDER BY product?

I'm using PostgreSQL 9.2.4.

Sql Solutions


Solution 1 - Sql

With postgres 9.0+ you can write:

select string_agg(product,' | ' order by product) from "tblproducts"

Details here.

Solution 2 - Sql

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

SELECT
  STRING_AGG(prod, '|') WITHIN GROUP (ORDER BY product)
FROM ... 

Solution 3 - Sql

select string_agg(prod,' | ') FROM 
  (SELECT product as prod FROM tblproducts ORDER BY product )MAIN;

SQL FIDDLE

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVivek S.View Question on Stackoverflow
Solution 1 - SqlIhor RomanchenkoView Answer on Stackoverflow
Solution 2 - SqlLuukView Answer on Stackoverflow
Solution 3 - SqlIlesh PatelView Answer on Stackoverflow