Chapter 12 · Lesson 4 of 4

Combining Lambda Functions

Nest list_filter inside list_reduce to build an inline list pipeline, summing only prices above 10 with a starting value of 0.

Lambda functions can be nested. You can filter a list first, then transform or reduce the result.

For example, to sum only the prices above 10:

SELECT customer,
       list_reduce(
         list_filter(prices, lambda p : p > 10),
         lambda a, b : a + b,
         0
       ) AS expensive_total
FROM orders

The inner list_filter keeps prices above 10, then list_reduce sums the survivors. Some customers have no price above 10, so their filtered list is empty. The third argument, 0, is the starting value: it makes an empty list reduce to 0 instead of raising an error.

You can also transform first and filter second:

SELECT list_filter(
         list_transform([1, 2, 3, 4, 5], lambda x : x * x),
         lambda sq : sq > 10
       )
-- [16, 25]

Nesting gives you a mini data pipeline inside a single SELECT expression.

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

Combine list_filter and list_reduce: for each customer, sum only the prices that are above 10. Return customer and the total as expensive_total, ordered by customer. Pass 0 as the starting value so customers without qualifying prices get 0.

Hint: list_reduce(list_filter(prices, lambda p : p > 10), lambda a, b : a + b, 0)

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Array Lambdas

Transform, filter, and reduce DuckDB list columns with lambda functions such as list_transform, list_filter, and list_reduce.

  1. 01 · Transforming Lists with list_transform
  2. 02 · Filtering Lists with list_filter
  3. 03 · Reducing a List with list_reduce
  4. 04 · Combining Lambda Functions

Related guides