PostgreSQL – ARRAY_AGG Function

array_agg is a PostgreSQL aggregate function that is used to aggregate values from multiple rows into a single array.

The syntax for using array_agg is as shown below:

SELECT array_agg(column_name)
FROM table_name
WHERE condition;

where column_name is the name of the column whose values you want to aggregate into an array.

table_name is the name of the table containing that column.

The WHERE clause is optional and can be used to filter the rows.

For example, consider a table named students with columns name and age. Below is the syntax to get the aggregate of ages of all students whose names start with the letter ‘J’.

SELECT array_agg(age)
FROM students
WHERE name LIKE 'J%';

This would return a single row containing an array of all ages of students whose names start with the letter ‘J’.

array_agg can also be used with GROUP BY or HAVING to further aggregate and filter the data.

Similar Posts