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():
The function transform() can be also employed to safely cast the elements of an array to strings:
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():
Find the array elements containing at least one value greater than 100
with any_match():
Capitalize the first 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():