Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways to alias a column

Tags:

alias

sql

What is the difference between

select  empName as EmployeeName from employees

versus

select  EmployeeName = empName from employees

from a technical point of view. Not sure if this is just SQL server specific or not.

Appreciate your answers.

like image 469
ManiP Avatar asked May 25 '11 13:05

ManiP


People also ask

How do I specify a column alias?

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

What is column aliases?

A column alias is a temporary, alternate name for a column. Aliases are specified in the SELECT clause to name or rename columns so that the result table is clearer or easier to read. Aliases are often used to name a column that is the result of an arithmetic expression or summary function. An alias is one word only.

Why would you column use aliases?

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.

How can I alias column name in SQL Server?

SQL Server column alias To assign a column or an expression a temporary name during the query execution, you use a column alias. In this syntax, you use the AS keyword to separate the column name or expression and the alias.


2 Answers

I'd prefer the first one, since the second one is not portable -

select  EmployeeName = empName from employees

is either a syntax error (at least in SQLite and Oracle), or it might not give you what you expect (comparing two columns EmployeeName and empName and returning the comparison result as a boolean/integer), whereas

select  empName EmployeeName from employees

is the same as

  select  empName as EmployeeName from employees

which is my preferred variant.

like image 65
Frank Schmitt Avatar answered Sep 28 '22 00:09

Frank Schmitt


The main advantage of the second syntax is that it allows the column aliases to be all lined up which can be of benefit for long expressions.

SELECT foo,
       bar,
       baz = ROW_NUMBER() OVER (PARTITION BY foo ORDER BY bar)
FROM T
like image 27
Martin Smith Avatar answered Sep 27 '22 23:09

Martin Smith