Reputation: 135
Simple question: How to use aliases after SELECT statement? Let's say i have query like this:
SELECT salary/12 AS sal
FROM sdatabase
WHERE sal > 1000
Of course it won't work because database will throw me an error. I know I can just replace sal
with salary/12
like this:
WHERE salary/12 > 1000
but I think it is less readable. So is there anything I can do with it or this is just the way it's done?
Upvotes: 1
Views: 851
Reputation: 16908
If you are learning How to use Alias in WHERE statement, Then @Jarlh's solution is fine but in practical, using the filter condition directly as below make more sense. This exclude use of a sub-query with the same result.
SELECT salary/12 AS sal
FROM sdatabase
WHERE salary > 12000
Upvotes: 0
Reputation: 4099
You can try Common Table Expression (CTE) -
WITH cte AS
(SELECT salary/12 AS sal
FROM sdatabase
WHERE sal > 1000)
SELECT *
FROM cte
WHERE sal > 1000
Upvotes: 0
Reputation: 2205
Logically, WHERE
clause is calculated before SELECT
. That's why you cannot use column sal
in WHERE
. It's not like in other languages where code is executed from top to bottom. A simplified order looks like this:
You can find more information about it by typing logical query processing
in your browser.
Upvotes: 1
Reputation: 1
From a chronological stand point your alias is not available in the "WHERE", so you need a subQuery to achieve this...
SELECT * FROM
( SELECT salary/12 AS sal FROM sdatabase )
sq WHERE sal > 1000
Upvotes: 0
Reputation: 44795
Wrap the original query up as a derived table (subquery):
select *
from
(
SELECT salary/12 AS sal
FROM sdatabase
) dt
WHERE sal > 1000
Upvotes: 4