Learn SQL Lesson
Reducing a List with list_reduce
`list_reduce` collapses a list into a single value by applying a two-argument `lambda` across all elements, one at a time.
SELECT list_reduce([1, 2, 3, 4], lambda acc, x : acc + x)
-- 10
The first parameter (acc) is the running accumulator and the second (x) is the current element. The result of each step becomes the accumulator for the next.
This is perfect for summing a list column:
SELECT customer, list_reduce(prices, lambda a, b : a + b) AS order_total
FROM orders
`list_reduce` needs at least one element. For empty lists, it returns `NULL`. If the list has exactly one element, that element is the result without calling the lambda.
Practice challenge
Use list_reduce to compute the total price per order. Return customer and the sum as order_total, ordered by customer.