Given the table orders with columns customer_id and product, what is the result of this query?
SELECT customer_id, ARRAY_AGG(product ORDER BY product) AS products FROM orders GROUP BY customer_id ORDER BY customer_id;
CREATE TABLE orders (customer_id INT, product TEXT); INSERT INTO orders VALUES (1, 'apple'), (1, 'banana'), (2, 'carrot'), (2, 'apple'), (3, 'banana');
Remember that ARRAY_AGG collects values into an array, and ORDER BY inside it sorts the array elements.
The query groups rows by customer_id and collects their product values into arrays sorted alphabetically. For customer 1, products are 'apple' and 'banana' sorted as ['apple', 'banana']. For customer 2, 'apple' and 'carrot' sorted as ['apple', 'carrot']. Customer 3 has only 'banana'.
Choose the option with correct syntax for using ARRAY_AGG with ordering.
Look for the correct placement of ORDER BY inside the ARRAY_AGG function.
Option A correctly places ORDER BY inside the parentheses of ARRAY_AGG. Option A misses the column to aggregate. Option A uses a comma incorrectly. Option A orders the whole query result, not the array elements.
You want to aggregate unique product names per customer into an array. Which query is the most efficient?
PostgreSQL supports DISTINCT inside ARRAY_AGG to remove duplicates efficiently.
Option C uses ARRAY_AGG(DISTINCT ...) which is optimized internally. Option C uses a correlated subquery which is less efficient. Option C deduplicates before aggregation but requires a subquery. Option C does not remove duplicates.
Consider this query with a filter that matches no rows:
SELECT ARRAY_AGG(product) FROM orders WHERE customer_id = 999;
What is the result?
Think about aggregate functions behavior when no rows are aggregated.
Aggregate functions like ARRAY_AGG return NULL when no rows match the filter. They do not return empty arrays or raise errors.
Given the query:
SELECT customer_id, ARRAY_AGG(product ORDER BY quantity) FROM orders GROUP BY customer_id;
Assuming quantity is not in the orders table, what error will PostgreSQL raise?
Check if all columns used inside ARRAY_AGG exist in the table.
The error occurs because quantity is referenced in the ORDER BY inside ARRAY_AGG but does not exist in the orders table.