Lambda expressions
Lambda expressions are anonymous functions which are passed as arguments to higher-order SQL functions.
Lambda expressions are written with ->
:
Limitations
Most SQL expressions can be used in a lambda body, with a few exceptions:
- Subqueries are not supported:
x -> 2 + (SELECT 3)
- Aggregations are not supported:
x -> max(y)
Examples
Obtain the squared elements of an array column with
transform
:
Results:
numbers | squared_numbers |
---|---|
[1, 2] | [1, 4] |
[3, 4] | [9, 16] |
[5, 6, 7] | [25, 36, 49] |
The function transform
can be also
employed to safely cast the elements of an array to strings:
Results:
price_tags |
---|
[100] |
[30] |
Besides the array column being manipulated, other columns can be
captured as well within the lambda expression. The following statement
provides a showcase of this feature for calculating the value of the
linear function f(x) = ax + b
with transform
:
Results:
xvalues | a | b | linear_function_values |
---|---|---|---|
[1, 2] | 10 | 5 | [15, 25] |
[3, 4] | 4 | 2 | [14, 18] |
Find the array elements containing at least one value greater than 100
with any_match
:
Capitalize the f word in a string via regexp_replace
:
Lambda expressions can be also applied in aggregation functions.
Following statement is a sample the overly complex calculation of the
sum of all elements of a column by making use of reduce_agg
:
Was this page helpful?