Sometimes a SQL query ends up needing an expression to be represented more than once. For example, some queries I've worked on have required a complex-to-calculate denominator that needs to be reused in multiple division calculations.
Usually one just duplicates the expression, but this is undesirable when:
- the SQL for the expression is particularly long
- or, particularly computationally expensive to calculate
select t.numerator1 / denominator, t.numerator2 / denominator,from mytable tlet demoninator = ....some complex calculation ... -- 'let' is NOT valid SQL
select t.numerator1 / v.denominator, t.numerator2 / v.denominator,from mytable touter apply ( select demoninator = ....some complex calculation ...) v
select v.variable1, v.variable2, v.variable3from mytable touter apply ( select variable1 = ..., variable2 = ..., variable3 = ...) v