LEARN

How to Use LISTAGG in Snowflake

A guide on using the LISTAGG function in Snowflake to aggregate text values, including ordering results.

Archie Sarre Wood
Archie Sarre Wood

What is LISTAGG in Snowflake?

The LISTAGG function in Snowflake allows you to aggregate and concatenate multiple text values into a single string. This is useful for creating summaries, lists, or grouped textual data.

Syntax for LISTAGG in Snowflake

LISTAGG(expression [, delimiter]) [WITHIN GROUP (ORDER BY expression)]
  • expression: The column or expression to concatenate.
  • delimiter: Optional separator used between values (default is a comma).
  • ORDER BY: Optional clause to order aggregated values.

Examples

Basic LISTAGG Example

Here’s how to concatenate city names within each region:

SELECT 
  region, 
  LISTAGG(city, ', ') AS cities
FROM locations
GROUP BY region;

Output:

regioncities
EastNew York, Boston
WestSan Francisco, Seattle

Custom Delimiter

Use the LISTAGG(expression, delimiter) syntax to specify a custom delimiter:

SELECT 
  region, 
  LISTAGG(city, '; ') AS cities
FROM locations
GROUP BY region;

Output:

regioncities
EastNew York; Boston
WestSan Francisco; Seattle

LISTAGG with ORDER BY

Use the WITHIN GROUP (ORDER BY ...) clause to specify the order of concatenated values:

SELECT 
  region, 
  LISTAGG(city, ', ') WITHIN GROUP (ORDER BY city ASC) AS cities_sorted
FROM locations
GROUP BY region;

This ensures that cities are ordered alphabetically within each concatenation.

Distinct Aggregation

If you need only unique values:

SELECT 
  department, 
  LISTAGG(DISTINCT employee_name, ', ') AS employees
FROM employee_data
GROUP BY department;

Output:

departmentemployees
SalesJohn, Jane, Jim

Conclusion

  • LISTAGG in Snowflake is powerful for concatenating textual values.
  • ORDER BY within LISTAGG allows you to control the sequence of concatenated items.
  • DISTINCT within LISTAGG allows you to aggregate unique values.
  • The delimiter option within LISTAGG allows you to specify a custom delimiter.

For more details, refer to Snowflake’s official documentation.

Get Started with Evidence

Build performant data apps using SQL and markdown

Join industry leaders version controlling their reporting layer

Start Free Trial →