Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 706
Imran Qadir Baksh - Baloch Avatar asked Nov 03 '11 11:11

Imran Qadir Baksh - Baloch


People also ask

Can I use alias in SELECT statement?

Table aliases can be used in SELECT lists and in the FROM clause to show the complete record or selective columns from a table. Table aliases can be used in WHERE, GROUP BY, HAVING, and ORDER BY clauses.

How alias use in SQL query?

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query. An alias is created with the AS keyword.

When would you typically use an alias in a SELECT statement?

Aliases are useful when table or column names are big or not very readable. These are preferred when there are more than one table involved in a query.


1 Answers

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.

like image 173
Johan Avatar answered Oct 19 '22 14:10

Johan