121

I have a simple query:

select * from countries

with the following results:

country_name
------------
Albania
Andorra
Antigua
.....

I would like to return the results in one row, so like this:

Albania, Andorra, Antigua, ...

Of course, I can write a PL/SQL function to do the job (I already did in Oracle 10g), but is there a nicer, preferably non-Oracle-specific solution (or may be a built-in function) for this task?

I would generally use it to avoid multiple rows in a sub-query, so if a person has more then one citizenship, I do not want her/him to be a duplicate in the list.

My question is based on the similar question on SQL server 2005.

UPDATE: My function looks like this:

CREATE OR REPLACE FUNCTION APPEND_FIELD (sqlstr in varchar2, sep in varchar2 ) return varchar2 is
ret varchar2(4000) := '';
TYPE cur_typ IS REF CURSOR;
rec cur_typ;
field varchar2(4000);
begin
     OPEN rec FOR sqlstr;
     LOOP
         FETCH rec INTO field;
         EXIT WHEN rec%NOTFOUND;
         ret := ret || field || sep;
     END LOOP;
     if length(ret) = 0 then
          RETURN '';
     else
          RETURN substr(ret,1,length(ret)-length(sep));
     end if;
end;
Community
  • 1
  • 1
rics
  • 5,494
  • 5
  • 33
  • 42

11 Answers11

134

The WM_CONCAT function (if included in your database, pre Oracle 11.2) or LISTAGG (starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:

select listagg(table_name, ', ') within group (order by table_name) 
  from user_tables;

or

select wm_concat(table_name) 
  from user_tables;

More details/options

Link to documentation

schnatterer
  • 7,525
  • 7
  • 61
  • 80
JoshL
  • 10,737
  • 11
  • 55
  • 61
  • This command is faster than @Decci.7 has provided +1 and I like simple one-liners :D – Kitet Feb 17 '14 at 11:07
  • 8
    Note that Oracle don't recommend using `WM_CONCAT` as it is undocumented and unsupported: [WMSYS.WM_CONCAT Should Not Be Used For Customer Applications, It Is An Internal Function (Doc ID 1336219.1)](https://support.oracle.com/CSP/main/article?cmd=show&type=NOT&doctype=HOWTO&id=1336219.1) – Burhan Ali Mar 24 '14 at 10:22
  • 11
    WM_CONCAT was dropped in 12c. Anyone using this undocumented function is in for a surprise when they upgrade. – Jon Heller May 09 '14 at 06:24
  • 1
    listagg is perfect,but the wm_concat not works with Oracle12 – gszecsenyi Oct 17 '17 at 08:53
101

Here is a simple way without stragg or creating a function.

create table countries ( country_name varchar2 (100));

insert into countries values ('Albania');

insert into countries values ('Andorra');

insert into countries values ('Antigua');


SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv
      FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn,
                   COUNT (*) OVER () cnt
              FROM countries)
     WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;

CSV                                                                             
--------------------------
Albania,Andorra,Antigua                                                         

1 row selected.

As others have mentioned, if you are on 11g R2 or greater, you can now use listagg which is much simpler.

select listagg(country_name,', ') within group(order by country_name) csv
  from countries;

CSV                                                                             
--------------------------
Albania, Andorra, Antigua

1 row selected.
Daniel Emge
  • 1,567
  • 1
  • 9
  • 7
  • Nice short solution but a couple typos marred it. This line should read: FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn, – Stew S Jan 26 '09 at 21:26
  • 3
    JoshL's suggestion of using the LISTAGG function is highly preferable for anyone using 11.2 or newer. – JakeRobb Jun 08 '15 at 21:10
  • 3
    Just make sure your concatenated results don't exceed the VARCHAR2 max length limit of your oracle database (most likely 4000 bytes) otherwise you will run into `ORA-01489 result of string concatenation is too long`. – JanM Jun 21 '17 at 09:37
  • @JanM **[Comment 1 of 2]** So, this is where I run into some challenges. I use [REGEXP_REPLACE](https://stackoverflow.com/questions/26672269/how-to-remove-duplicates-from-comma-separated-list-by-regex-in-oracle-regexp-rep) to remove the duplicates, but this does not work if I reach the VARCHAR2 max limit first. – datalifenyc Jan 28 '19 at 23:37
  • @JanM **[Comment 2 of 2]** Next, I try to convert it to a [clob using RTRIM,XMLAGG,XMLELEMENT, and GETCLOBVAL()](https://stackoverflow.com/questions/13395678/result-of-string-concatenation-is-too-long-after-using-to-clob), which I then cast back to [VARCHAR2](https://stackoverflow.com/questions/28282195/ora-00932-inconsistent-datatypes-expected-got-clob-00932-00000). However, the run time for the query turns into hours rather than 15 minutes. Do you have any recommendations of other approaches? Also, I saw a suggestion for creating a custom function instead. – datalifenyc Jan 28 '19 at 23:37
  • how this query work if I join two table and want to get a column by comma separated value from 2nd table? – Basher Sarkar Jul 30 '21 at 16:22
21

For Oracle you can use LISTAGG

Makatun
  • 947
  • 10
  • 11
20

you can try this query.

select listagg(country_name,',') within group (order by country_name) cnt 
from countries; 
CassOnMars
  • 6,153
  • 2
  • 32
  • 47
Gaya3
  • 209
  • 2
  • 3
20

You can use this as well:

SELECT RTRIM (
          XMLAGG (XMLELEMENT (e, country_name || ',')).EXTRACT ('//text()'),
          ',')
          country_name
  FROM countries;
Noel
  • 10,152
  • 30
  • 45
  • 67
Decci.7
  • 201
  • 2
  • 2
4

The fastest way it is to use the Oracle collect function.

You can also do this:

select *
  2    from (
  3  select deptno,
  4         case when row_number() over (partition by deptno order by ename)=1
  5             then stragg(ename) over
  6                  (partition by deptno
  7                       order by ename
  8                         rows between unbounded preceding
  9                                  and unbounded following)
 10         end enames
 11    from emp
 12         )
 13   where enames is not null

Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.

tuinstoel
  • 7,248
  • 27
  • 27
2

In this example we are creating a function to bring a comma delineated list of distinct line level AP invoice hold reasons into one field for header level query:

 FUNCTION getHoldReasonsByInvoiceId (p_InvoiceId IN NUMBER) RETURN VARCHAR2

  IS

  v_HoldReasons   VARCHAR2 (1000);

  v_Count         NUMBER := 0;

  CURSOR v_HoldsCusror (p2_InvoiceId IN NUMBER)
   IS
     SELECT DISTINCT hold_reason
       FROM ap.AP_HOLDS_ALL APH
      WHERE status_flag NOT IN ('R') AND invoice_id = p2_InvoiceId;
BEGIN

  v_HoldReasons := ' ';

  FOR rHR IN v_HoldsCusror (p_InvoiceId)
  LOOP
     v_Count := v_COunt + 1;

     IF (v_Count = 1)
     THEN
        v_HoldReasons := rHR.hold_reason;
     ELSE
        v_HoldReasons := v_HoldReasons || ', ' || rHR.hold_reason;
     END IF;
  END LOOP;

  RETURN v_HoldReasons;
END; 
Emil
  • 7,220
  • 17
  • 76
  • 135
2

I needed a similar thing and found the following solution.

select RTRIM(XMLAGG(XMLELEMENT(e,country_name || ',')).EXTRACT('//text()'),',') country_name from  
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tips
  • 29
  • 1
  • 1
    While it works, I dont recommend this solution to anybody. I saw an update command on table with only 80 000 rows using this solution and it was run for 6-8 hours. – csadam Oct 24 '11 at 16:06
  • @csadam What do you recommend for larger rows, where the end goal is to remove duplicates to avoid the varchar2 4000 bytes limitation? – datalifenyc Jan 29 '19 at 03:11
  • @myidealab You can find some workarounds [here](https://blogs.oracle.com/datawarehousing/managing-overflows-in-listagg) and [here](https://oracle-base.com/articles/misc/string-aggregation-techniques). To remove duplicates you can try an inner select with DISTINCT. Maybe the best solution is to create a custom function for these cases... However you could also redesign your solution, does it really have to use a 4000 char long string? – csadam Jan 30 '19 at 18:58
0
SELECT REPLACE(REPLACE
((SELECT     TOP (100) PERCENT country_name + ', ' AS CountryName
FROM         country_name
ORDER BY country_name FOR XML PATH('')), 
'&<CountryName>', ''), '&<CountryName>', '') AS CountryNames
The iOSDev
  • 5,237
  • 7
  • 41
  • 78
0

I have always had to write some PL/SQL for this or I just concatenate a ',' to the field and copy into an editor and remove the CR from the list giving me the single line.

That is,

select country_name||', ' country from countries

A little bit long winded both ways.

If you look at Ask Tom you will see loads of possible solutions but they all revert to type declarations and/or PL/SQL

Ask Tom

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrew Wood
  • 179
  • 3
  • 9
-4

you can use this query to do the above task

DECLARE @test NVARCHAR(max)
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test SELECT field2= @test

for detail and step by step explanation visit the following link
http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html

chown
  • 51,908
  • 16
  • 134
  • 170
Rashmi Kant
  • 159
  • 1
  • 2