1

The following SQL works:

select
  column1
from
  table1
where
  column1 > 10

The following doesn't:

select
  abs(column1 - column2) column_diff
from
  table1
where
  column_diff > 10

Why? How should I fix it? All I want to say is that 'give me all the rows with the absolute value of the difference of the two columns greater than 10'. Thanks.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
user2725109
  • 2,286
  • 4
  • 27
  • 46
  • 2
    Use a subquery, CTE, or put the expression in the `where` clause. That is how SQL works. – Gordon Linoff Sep 19 '17 at 18:31
  • 3
    Possible duplicate of [Referring to a Column Alias in a WHERE Clause](https://stackoverflow.com/questions/8370114/referring-to-a-column-alias-in-a-where-clause) – Tab Alleman Sep 19 '17 at 18:35

1 Answers1

1

Your query won't work because sql engine will compile your query in following steps:

  1. from clause
  2. where clause

  3. select clause

So, while executing where clause, alias column_diff won't be available hence the query won't work.

Solution:

select 
     abs(column1 - column2) as column_diff
         from
           table1
               where
                 abs(column1-column2) >10;

Hope it helps!

Harshil Doshi
  • 3,497
  • 3
  • 14
  • 37