1

I need to use the computed values (after 'as' keyword) of two functions in sql in the next statement. I want to use it because the time of computations decreases x2 in this case.

I have the following statement:

SELECT f1() as f_1, f2() as f_2, f_1 - f_2 as f1_minus_f2 FROM mytable

where f1(), f2() - some functions

1 Answers1

2

1) You can use expression itself (if functions are deterministic):

SELECT f1() as f_1, f2() as f_2, f1() - f2() as f1_minus_f2 
FROM mytable

2) Use subquery:

SELECT sub.f_1, sub.f_2, sub.f_1 - sub.f_2 as f1_minus_f2
FROM (
   SELECT f1() as f_1, f2() as f_2
   FROM mytable
) sub

The reason you cannot use it as you want is all-at-once rule:

"All-at-Once Operations" means that all expressions in the same logical query process phase are evaluated logically at the same time.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275