0

How we can create alias of a column in table in SQL Server?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ram singh
  • 1
  • 4

3 Answers3

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
0
select somecolumn as foo from bar where foo = 5
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • thnks sir can u explain why we use this alias concept plz – ram singh Jan 12 '11 at 11:06
  • 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