Chapter 12 · Lesson 1 of 4

Transforming Lists with list_transform

Apply a lambda to every element of a DuckDB list with list_transform, such as doubling each price in an order's price list.

list_transform applies a function to every element of a list and returns a new list with the results. Think of it like a map operation.

The syntax uses a lambda expression:

SELECT list_transform([1, 2, 3], lambda x : x * 10)
-- [10, 20, 30]

Lambda expressions start with the keyword lambda, followed by a parameter name, a colon, and the expression to evaluate.

You can use this on table columns too. For example, adding 10% tax to every price in a list:

SELECT customer, list_transform(prices, lambda p : round(p * 1.1, 2)) AS taxed
FROM orders

NULL elements stay NULL after transformation. The return type of the new list is determined by the lambda expression.

The sample table stores items and prices as parallel lists. That means the first item belongs with the first price, the second item belongs with the second price, and so on. This is compact, but position-dependent data can be fragile if the lists get out of sync.

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_transform to double every price in the prices column. Return customer and the transformed list as doubled_prices, ordered by customer.

Hint: list_transform(prices, lambda p : p * 2)

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