How to Write an ORDER BY Clause with Exceptions using SQL

In SQL, the ORDER BY clause is commonly used to order the results of a query. It allows you to select one or more columns to order the results, and in most cases, it’s probably all you need.

But what if you need to make an exception?

What if you want the results to be ordered alphabetically, except for one row? Or several rows?

Or perhaps you simply want to put any NULL values to the end, while ordering the non-NULL results.

Either way, there’s a neat trick you can use that will enable you to do this. And the good part is, it’s simple.

You can cater for all of the above scenarios by adding a CASE expression to your ORDER BY clause.

Continue reading