How we can create alias of a column in table in SQL Server?
Asked
Active
Viewed 212 times
3 Answers
1
Creation of aliases is very easy
SELECT tableColumnName as ColumnAlias FROM Table
Another thing is usage of the aliases, you must remember that the aliases are available after projection (select) this mean that you can't use those aliases in FROM, WHERE, GROUP BY, HAVING
sections. Is allowed only in ORDER BY
.
EDIT: Usage of aliases
Tables:
STACK
- STACK_ID
- STACK_NAME
- STACK_ORDER
- STACK_MIN
- STACK_MAX
Wrong statement:
SELECT
STACK_NAME,
STACK_MIN,
STACK_MAX,
STACK_MIN + STACK_MAX as STACK_SUM
FROM
STACK WHERE STACK_SUM = 10;
We use in WHERE section column that is not available on this level.
To solve this we have two options
Option One - We do the calculation in where statement
SELECT
STACK_NAME,
STACK_MIN,
STACK_MAX,
STACK_MIN + STACK_MAX as STACK_SUM
FROM
STACK WHERE STACK_MIN + STACK_MAX = 10;
Option Two - We create a temporary table
WITH STACK_SUM_TAB AS (
SELECT
STACK_NAME,
STACK_MIN,
STACK_MAX,
STACK_MIN + STACK_MAX as STACK_SUM
FROM STACK
)
SELECT
STACK_NAME,
STACK_MIN,
STACK_MAX,
STACK_SUM
FROM STACK_SUM_TAB WHERE STACK_SUM = 10;

Martin Smith
- 438,706
- 87
- 741
- 845

Damian Leszczyński - Vash
- 30,365
- 9
- 60
- 95
-
Here you go. And that mr. is not needed. – Damian Leszczyński - Vash Jan 12 '11 at 11:16
0
select somecolumn as foo from bar where foo = 5

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
-
Alias are useful when you have complex queries with long column names coming from different tables. Giving them more meaningful names improves the readability of the query. – Darin Dimitrov Jan 12 '11 at 11:07
0
SELECT columnname AS [ColumnAliasName] FROM [TableName]

ashish.chotalia
- 3,696
- 27
- 28
-
SELECT t.columnname AS [ColumnAliasName] FROM [TableName] t WHERE t.columnname = [Your Condition value here] – ashish.chotalia Jan 12 '11 at 11:33