web analytics

Can I use column alias in SQL where clause?

Options

codeling 1602 - 6666
@2015-12-31 13:17:35

Standard SQL doesn't allow you to refer to a column alias in a WHERE clause, except for GROUP BY, ORDER BY, or HAVING clauses.

--wrong

SELECT order_id, (order_price X 0.85) as discount_price from order where discount_price >=100;
@2015-12-31 13:26:14

Workaround 1, using subquery

select * from

(

  SELECT order_id, (order_price X 0.85) as discount_price from order

) x

order by discount_price >= 100;
@2015-12-31 13:34:46

Workaround 2, using with clause

with discount_order as

(

   SELECT order_id, (order_price X 0.85) as discount_price from order

)

select * from discount_order where discount_price >= 100;

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com