Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server extra text after table name in SELECT

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.

like image 886
user807566 Avatar asked Jul 29 '26 20:07

user807566


2 Answers

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
like image 159
Tim Schmelter Avatar answered Aug 01 '26 13:08

Tim Schmelter


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:

  1. 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
    
  2. 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
    
  3. 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
    
like image 31
lc. Avatar answered Aug 01 '26 12:08

lc.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!