Chapter 12 · Lesson 3 of 4
Reducing a List with list_reduce
Fold a DuckDB list into a single value with list_reduce, sum each order's prices, and learn why empty lists need a starting value.
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)
-- 10The 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 ordersIf the list has exactly one element, that element is the result without calling the lambda. A NULL list returns NULL.
An empty list is different: DuckDB raises an error ("Cannot perform list_reduce on an empty input list") unless you pass a starting value as an optional third argument:
SELECT list_reduce([], lambda acc, x : acc + x, 0)
-- 0The next lesson uses that starting value when a filter can leave a list empty.
Sample data
This lesson loads the orders table (4 rows with item and price lists) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for orders
CREATE OR REPLACE TABLE orders (
customer VARCHAR,
items VARCHAR[],
prices DECIMAL(8,2)[]
);
INSERT INTO orders VALUES
('Alice', ['Widget', 'Gadget'], [9.99, 24.99]),
('Bob', ['Gizmo', 'Widget', 'Doohickey'], [14.99, 9.99, 4.99]),
('Carol', ['Gadget'], [24.99]),
('Dave', ['Sticker'], [4.99]);Practice challenge
Use list_reduce to compute the total price per order. Return customer and the sum as order_total, ordered by customer.
Hint: list_reduce(prices, lambda a, b : a + b)
Run your query in the editor and the lesson checks the result automatically.
Lessons in Array Lambdas
Transform, filter, and reduce DuckDB list columns with lambda functions such as list_transform, list_filter, and list_reduce.