A lambda is an anonymous function. It does not require a name and can be passed as a parameter to other functions or methods. This topic describes the limits, syntax, and usage examples of lambda functions.
Lambda expressions are anonymous functions that do not need to be named and can be used as parameters in other functions or methods. Use them to apply element-level transformations and filters to arrays and complex data structures inline, without defining a named function.
Syntax
parameter_list -> expression
The parameter list can be empty or contain one or more parameters. Use parentheses when specifying multiple parameters. The -> delimiter separates the parameter list from the expression or code block. Parameter types are determined by the invoking function.
Limitations
-
Subqueries are not supported. For example,
x -> 2 + (SELECT 3)is invalid. -
Aggregate operations are not supported. For example,
x -> max(y)is invalid.
Examples
All examples use transform(), a higher-order function that applies a lambda expression to each element of an array.
Square each element in an array
SELECT numbers, transform(numbers, n -> n * n) AS squared_numbers
FROM (
VALUES (ARRAY(1, 2)), (ARRAY(3, 4)), (ARRAY(5, 6, 7))
) AS t(numbers);
Result:
+------------+-----------------+
| numbers | squared_numbers |
+------------+-----------------+
| [5,6,7] | [25,36,49] |
| [3,4] | [9,16] |
| [1,2] | [1,4] |
+------------+-----------------+
Format array elements as price strings
The lambda expression casts each integer to a string and appends a currency symbol.
SELECT transform(prices, n -> CAST(n AS STRING) || '$') AS price_tags
FROM (
VALUES (ARRAY(100, 200)), (ARRAY(30, 4))
) AS t(prices);
Result:
+-----------------+
| price_tags |
+-----------------+
| ["100$","200$"] |
| ["30$","4$"] |
+-----------------+
Evaluate a linear function across an array
In addition to the array column being transformed, the lambda expression can capture other columns from the same row. This example evaluates f(x) = ax + b for each element.
SELECT xvalues, a, b,
transform(xvalues, x -> a * x + b) AS linear_function_values
FROM (
VALUES (ARRAY(1, 2), 10, 5), (ARRAY(3, 4), 4, 2)
) AS t(xvalues, a, b);
Result:
+---------+----+---+------------------------+
| xvalues | a | b | linear_function_values |
+---------+----+---+------------------------+
| [3,4] | 4 | 2 | [14,18] |
| [1,2] | 10 | 5 | [15,25] |
+---------+----+---+------------------------+