Monday, 18 February 2008

T-SQL alias play around

I noticed an interesting feature of T-SQL reagarding field alias in a sql statement. The field alias cannot be used in a WHERE clause but can be used in ORDER BY .

To test this I have created a table called Test with two columns: ID and TestDate. The ID is an identity column and TestDate is DateTime. I populated several ramdom records in the table.

First I run the following sql :
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where TestDate > '01/03/2006'
order by RealDate

5 2006-02-01 00:00:00.000 01/02/2006
3 2006-02-10 00:00:00.000 10/02/2006
1 2006-02-23 00:00:00.000 23/02/2006
2 2006-02-25 00:00:00.000 25/02/2006
4 2006-04-08 00:00:00.000 08/04/2006

The result shows the date time field is sorted properly and alias RealDate is used for sorting.

Then I run this:
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where TestDate > '01/03/2006'
order by DisplayDate

5 2006-02-01 00:00:00.000 01/02/2006
4 2006-04-08 00:00:00.000 08/04/2006
3 2006-02-10 00:00:00.000 10/02/2006
1 2006-02-23 00:00:00.000 23/02/2006
2 2006-02-25 00:00:00.000 25/02/2006

The result shows the sorting is by the varchar field and this is what I have expected.

Then I run this:
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where DisplayDate > '01/03/2006'
order by DisplayDate

Msg 207, Level 16, State 1, Line 1
Invalid column name 'DisplayDate'.

And this:
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where RealDate > '01/03/2006'
order by DisplayDate

Msg 207, Level 16, State 1, Line 1
Invalid column name 'RealDate'.

The two error messages above show we can't use alias in a where clause.