Categories
Uncategorized

How to keep a specific row as the first result in SQL using order by

Introduction
To understand this, I have prepared a user table with two columns: first_name and last_name. Below is the result of a simple select statement.

Sql query: Simple select and order by first_name
[sourcecode language=”sql”]
SELECT * FROM dbo.Users 
ORDER BY dbo.Users.first_name
[/sourcecode]

Screenshot from Sql Server Management Studio:


Now I want to have the row with firstName as “Yasser” to be the first row, so using the following query I have managed to achieve this.

Sql query: Simple select and order by first_name and excluding ‘Yasser’
[sourcecode language=”sql”]
SELECT * FROM dbo.Users 
ORDER BY CASE dbo.Users.first_name WHEN ‘Yasser’ THEN 0 ELSE 1 END, dbo.Users.first_name
[/sourcecode]

Screenshot from Sql Server Management Studio:


Hope this helps you. 🙂