Skip to main content

Scopes

Scopes can be nested with curly braces as in:

v := {
v := 1
v
}
v + 1 // result is 2

Note that the v of the inner scope overrides the v of the outer scope.

Curly braces are not needed for the top-level scope.

An alternative syntax to create nested scopes uses WITH, similarly to SQL.

WITH‚Äč

WITH assigns an identifier to an expression, which can then be used in the expression body.

Syntax:

WITH <identifier 1> AS (<expression 1>), [... <identifier n> AS (<expression n>)]
<expression body>

For example:

WITH v AS (1)
v + 1 // result is 2

WITH regional_sales AS (
SELECT region, SUM(amount) AS total_sales
FROM orders
GROUP BY region
), top_region AS (
SELECT region
FROM regional_sales
ORDER BY total_sales DESC
LIMIT 1
)
...