TIL: You can use column aliases in an ORDER BY clause

The execution plan for the two queries, one using the alias in the ORDER BY and the other copying the text of the calculated value, is identical

This is almost certainly something a lot of other people know, but I've somehow managed to not learn it in the many (many!) years of using SQL Server that I have under my belt...

You can use the alias of a column / calculated value in the ORDER BY of your query, i.e. you don't have to repeat the "meat" of the column definition

To put it another way, the following queries are identical - as can be seen from the execution plans I screen-grabbed:

SELECT	S.UniqueId,
	S.SalesID,
	S.SalesDate,
	S.SaleValue,
	CAST(DATEPART(year, S.SalesDate) AS NVARCHAR) + '/' + FORMAT(DATEPART(month, S.SalesDate), '00') [SaleMonth]
FROM	[dbo].[SalesDb] S
ORDER
BY	CAST(DATEPART(year, S.SalesDate) AS NVARCHAR) + '/' + FORMAT(DATEPART(month, S.SalesDate), '00')

SELECT	S.UniqueId,
	S.SalesID,
	S.SalesDate,
	S.SaleValue,
	CAST(DATEPART(year, S.SalesDate) AS NVARCHAR) + '/' + FORMAT(DATEPART(month, S.SalesDate), '00') [SaleMonth]
FROM	[dbo].[SalesDb] S
ORDER
BY	[SaleMonth]

The very obvious advantage of this is that in the second query there's not a large glob of SQL repeated which avoids the opportunity for error in copying it across and also the opportunity for the two to become out of synch, along with all the subtle issues that can introduce.

Now to re-visit some queries and strip some duplicated code out of them!

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment