Some RDBMSs have a GROUP_CONCAT()
function that allows you to return a query column as a delimited list (for example, a comma separated list). MySQL and MariaDB are two that have such a function.
PostgreSQL and SQL Server have similar functions called STRING_AGG()
.
Oracle, on the other hand, has the LISTAGG()
function that does pretty much the same thing (and perhaps more).
So you could say that LISTAGG()
is Oracle’s GROUP_CONCAT()
equivalent.
Example
Here’s a basic example to demonstrate how Oracle’s LISTAGG()
function works:
SELECT LISTAGG(region_name, ',')
FROM regions;
Result:
LISTAGG(REGION_NAME,',') ______________________________________________ Europe,Americas,Asia,Middle East and Africa
In this case, I specified that the separator is a comma.
Here’s what happens when we just do the query without the LISTAGG()
function:
SELECT region_name
FROM regions;
Result:
REGION_NAME _________________________ Europe Americas Asia Middle East and Africa
We get four rows, each with a separate value, instead of one comma separated row that contains all values.
The LISTAGG()
function also enables us to order the results, return only unique values (via the DISTINCT
clause), and more.
See LISTAGG()
Function in Oracle for more examples.