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

Yasser Shaikh
Oct 4, 2012 · 1 min read

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. :)

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Yasser Shaikh

Written by

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade