Lambda functions
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.
Limits
Subqueries are not supported, such as
x->2+(SELECT3).Aggregations are not supported, such as
x -> max(y).
Syntax
The syntax is: parameter list -> expression or code block
Parameter list: The parameters that the lambda function accepts. The list can be empty or contain one or more parameters.
->: Separates the parameter list from the expression or code block.
Examples
Example 1: Calculate the square of values in an array column
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);The following result is returned:
+------------+-----------------+ | numbers | squared_numbers | +------------+-----------------+ | [5,6,7] | [25,36,49] | | [3,4] | [9,16] | | [1,2] | [1,4] | +------------+-----------------+Example 2: Convert an array to a string
SELECT transform(prices, n -> CAST(n AS STRING ) || '$') as price_tags FROM ( VALUES (ARRAY(100, 200)),(ARRAY(30, 4)) ) AS t(prices);The following result is returned:
+------------+ | price_tags | +------------+ | ["30$","4$"] | | ["100$","200$"] | +------------+Example 3: Calculate the value of a linear function
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);The following result is returned:
+------------+------------+------------+------------------------+ | xvalues | a | b | linear_function_values | +------------+------------+------------+------------------------+ | [3,4] | 4 | 2 | [14,18] | | [1,2] | 10 | 5 | [15,25] | +------------+------------+------------+------------------------+