Chapter 12 · Lesson 2 of 4
Filtering Lists with list_filter
Keep only the list elements that match a condition with list_filter and a lambda, such as the prices above 10 in each order.
list_filter keeps only the elements that satisfy a condition and returns a shorter list.
SELECT list_filter([10, 3, 25, 8], lambda x : x > 9)
-- [10, 25]The lambda must return a boolean. Elements where it returns true are kept; the rest are dropped.
On a table column:
SELECT customer, list_filter(prices, lambda p : p > 10) AS expensive
FROM ordersIf no elements match, the result is an empty list []. This is useful for narrowing down list data before further processing.
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_filter to keep only prices greater than 10. Return customer and the filtered list as high_prices, ordered by customer.
Hint: list_filter(prices, lambda p : p > 10)
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.