New! GraphQL.NET Cookbook by Senthil Kumar Balu

Using Expressions for SORT Order in SQL Server

You might want to sort the results of an query in a different order from the traditional sort (Ascending/Descending) order.

For example , you wish to sort the Department records by GroupName and force the GroupName “Manufacturing” to be sorted first.

How to use expression to sort records in SQL Server ?

You could do this by using the expression which would provide the sort order that you require.

Here’s a sample query demonstrating how this can be done.

Use AdventureWorks2014
GO
SELECT * from HumanResources.Department
ORDER BY CASE GroupName   
WHEN 'Manufacturing' THEN NULL      
ELSE GroupName      
END;  

SNAGHTML8450788

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.