Faced with need of using column aliases in where condition for selection. Found possible solution here.
Let's assume we have one-to-one relationship (user-to-role) and we want to get results as following:
SELECT u.name AS u_name, r.name AS r_name
FROM users AS u
INNER JOIN roles AS r
ON u.role_id = r.role_id
WHERE u.name = 'John'
And we have corresponding idex for user.name
(just for example).
If this query is run with EXPLAIN
, it shows all indexes that are used during selection (including index for name).
Now, as we want to use aliases in WHERE
clause, based on proposed solution we can rewrite the query:
SELECT * FROM (
SELECT u.name AS u_name, r.name AS r_name
FROM users AS u
INNER JOIN roles AS r
ON u.role_id = r.role_id
) AS temp
WHERE u_name = 'John'
As you see, there's no WHERE
clause in nested select. Running this query with EXPLAIN
gives the same results (just to admit, I'm not an expert in analyzing results of 'explain', but still):
- same indexes
- same costs
- similar time of execution
And I'm a little bit confused by this result: was convinced that at least index for user name won't be used.
Q1: Does postgres use indexes in that way?
Q2: Are there possible performance issues?