Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL alias for SELECT statement

Tags:

alias

sql

select

I would like to do something like

(SELECT ... FROM ...) AS my_select WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name) 

Is it possible to somehow do the "AS my_select" part (i.e. assign an alias to a SELECT statement)?

(Note: This is a theoretical question. I realize that I can do it without assign an alias to a SELECT statement, but I would like to know whether I can do it with that.)

like image 215
Paul S. Avatar asked Jul 13 '12 22:07

Paul S.


People also ask

Can alias Use same SELECT statement?

No there isn't a way to refer to aliases, but you can assign the expression to a variable, and then refer to the variable in the same select clause. Inside a select statement variable assignment is always done by the infix operator := . *In a SET statement, it can be either = or := .

How do you specify an alias in SQL?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];

What is SELECT an alias for?

SQL SELECT AS is used to assign temporary names to table or column name or both. This is known as creating Alias in SQL.

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.


2 Answers

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT.. FROM (      SELECT ...      FROM ...      ) my_select WHERE ... 

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list. WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear) AS -- Define the CTE query. (     SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear     FROM Sales.SalesOrderHeader     WHERE SalesPersonID IS NOT NULL ) -- Define the outer query referencing the CTE name. SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear FROM Sales_CTE GROUP BY SalesYear, SalesPersonID ORDER BY SalesPersonID, SalesYear; 

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

like image 72
Roland Bouman Avatar answered Sep 29 '22 01:09

Roland Bouman


You can do this using the WITH clause of the SELECT statement:

; WITH my_select As (SELECT ... FROM ...)  SELECT * FROM foo WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name) 

That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...

like image 44
RBarryYoung Avatar answered Sep 29 '22 03:09

RBarryYoung