user960567 user960567 - 1 month ago 8
SQL Question

Use Alias in Select Query

I need to ask how can use Alias in Select Query,

I need this

SELECT (Complex SubQuery) AS A, (Another Sub Query WHERE ID = A) FROM TABLE

Answer

You cannot do this:

SELECT (Complex SubQuery) AS A, (Another Sub Query WHERE ID = A) FROM TABLE

You can however do this:

SELECT (Another Sub Query WHERE ID = A.somecolumn)
FROM table
JOIN SELECT (Complex SubQuery) AS A on (A.X = TABLE.Y)

Or

SELECT (Another Sub Query)
FROM table
WHERE table.afield IN (SELECT Complex SubQuery.otherfield)

The problem is that you cannot refer to aliases like this in the SELECT and WHERE clauses, because they will not have evaluated by the time the select or where part is executed.
You can also use a having clause, but having clauses do not use indexes and should be avoided if possible.

Comments