Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

How to concatenate the string values of a column/field in a PostgreSQL query?

$
0
0

This is a very popular interview question of the database, many times I faced this the question in SQL Server interview.

Problem:Suppose we have the following table (employee)

id
deprt_id
emp_name
1
1
Dilip
2
1
Anil
3
1
Mamta
4
2
Ashish
5
2
Naina

And I want to result set as below

deprt_id
emp_name
1
Dilip,Anil,Mamta
2
Ashish,Naina,Kartikey

To achieve this above result-set we will work on the PostgreSQL query. As new versions of the database come along, some new features and enhancements are also added. According to the different versions, whatever features are available here, I will give detailed information about it.

Create table employee


CREATETABLEemployee
(
       id     intGENERATEDBYDEFAULTASIDENTITY,
       deprt_idtext,
       emp_nametext
);

INSERTINTOemployee(deprt_id,emp_name)VALUES (1,'Dilip');
INSERTINTOemployee(deprt_id,emp_name)VALUES (1,'Anil');
INSERTINTOemployee(deprt_id,emp_name)VALUES (1,'Mamta');
INSERTINTOemployee(deprt_id,emp_name)VALUES (2,'Ashish');
INSERTINTOemployee(deprt_id,emp_name)VALUES (2,'Naina');
INSERTINTOemployee(deprt_id,emp_name)VALUES (2,'Kartikey');


PostgreSQL 9.0 or later


The function string_agg(expression, delimiter) is used to concatenate string value of a column, run the following query.


SELECTdeprt_id,string_agg(emp_name,',')
FROMemployee
  GROUPBYdeprt_id;




ORDER BY clause in any aggregate expression string_agg(column_name, ',', order by column_name).


SELECTdeprt_id,string_agg(emp_name,','ORDERBYemployee)
FROMemployee
GROUPBYdeprt_id;



PostgreSQL 8.4 or later


The function array_to_string() can be used to give the desired result.


SELECTdeprt_id,array_to_string(array_agg(emp_name),',')
FROMemployee
GROUPBYdeprt_id;







Viewing all articles
Browse latest Browse all 265

Trending Articles