Christoph's 2 Cents

A Backup for My Brain!

Oracle Developement

Handy Regexp trick for Listaggs

I use the listagg function to generate a comma separated list of employees who work in department 10 from the EMP table.

To make the list more readable, I want to substitute the last comma with the word and.

 with q as (
 select listagg(ename,', ') within group (order by 1) ret
from emp
 where deptno = 10
 )
 select regexp_replace(ret,',',' and',instr(ret,',',-1)) ret
 from q;
SQL> 

RET
--------------------------------------------------------------------------------
CLARK, KING and MILLER