This Oracle tutorial explains how to use the Oracle/PLSQL LISTAGG function with syntax and examples.
The Oracle/PLSQL LISTAGG function concatenates values of the measure_column for each GROUP based on the order_by_clause.
The syntax for the LISTAGG function in Oracle/PLSQL is:
The column or expression whose values you wish to concatenate together in the result set. Null values in the measure_column are ignored.
Optional. It is the delimiter to use when separating the measure_column values when outputting the results.
It determines the order that the concatenated values (ie: measure_column) are returned.
The LISTAGG function returns a string value.
The LISTAGG function can be used in the following versions of Oracle/PLSQL:
The LISTAGG function can be used in Oracle/PLSQL.
Since this is a more complicated function to understand, let's look at an example that includes data to demonstrate what the function outputs.
If you had a products table with the following data:
product_id | product_name |
---|---|
1001 | Bananas |
1002 | Apples |
1003 | Pears |
1004 | Oranges |
And then you executed a SELECT statement using the LISTAGG function:
You would get the following results:
Product_Listing |
---|
Apples, Bananas, Oranges, Pears |
In this example, the results of the LISTAGG function are output in a single field with the values comma delimited.
You can change the ORDER BY clause to use the DESC keyword and change the SELECT statement as follows:
This would give the following results:
Product_Listing |
---|
Pears, Oranges, Bananas, Apples |
You could change the delimiter from a comma to a semi-colon as follows:
This would change your results as follows:
Product_Listing |
---|
Pears; Oranges; Bananas; Apples |