I found a SQL statement to the effect of:
SELECT * FROM Users x
My question is: what is x? I have never seen this before.
Thanks.
x is an Alias for the table Users.
Using Table Aliases
The readability of a SELECT statement can be improved by giving a table an alias, also known as a correlation name or range variable. A table alias can be assigned either with or without the AS keyword:
SELECT * FROM Users x
SELECT * FROM Users AS x
It's an alias. The AS keyword is optional and has been left out, but it is the same as:
SELECT * FROM Users AS x
This means you can (in some implementations of SQL, SQL Server being one of them, must) use x in the rest of the query to refer back to the table Users specified here. For example:
SELECT x.MyColumn
FROM Users x
WHERE x.AnotherColumn = 42
There are three general use cases for aliases:
Readability. For long table names or when the name will be used many times, it can improve readability. For example, imagine the following without the alias:
SELECT x.SomeColumn, x.SomeOtherColumn, x.AThirdColumn
FROM [my crAzy Table Name with spaces in it] x
WHERE x.AnotherColumn = 42
Disambiguation. Often used for self-joins, note the use of the same table twice. You must use an alias to differentiate the two instances of the Users table:
SELECT x.SomeColumn, COUNT(y.SomeColumn)
FROM Users x
INNER JOIN Users y ON x.SomeOtherColumn < y.SomeOtherColumn
GROUP BY x.SomeColumn
Sub-queries in a FROM or JOIN clause (also called derived tables) must have a name. This is done by specifying an alias:
SELECT x.SomeColumn
FROM
(
SELECT SomeColumn
FROM Users
) x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With