Database Agnostic – Using SQL ORDER BY for Complex Criteria

database-agnosticorder-by

Let's say my relation is like so

enter image description here

and I wanted to sort by rank, but A's and B's first. So my relation will look like

enter image description here

At first I tried to just have two relations, where I order both of them by rank, then union the two relations, but they just end up getting jumbled together. I've also tried using cases, but I don't understand how it works. I kept getting errors about mixing characters with integers.

Edit: Forgot to mention that the first relation above is what I end up with after a somewhat complex number of views. For example, I created two views, one which only has A and B classes, then I ordered that by rank. Second view just C classes, ordered that by rank. Then I unioned them, but they just get mixed.

Best Answer

You only need a CASE expression in the ORDER BY, to divide the rows into two groups, so the ones with class 'A' or 'B' are put in first group (1) and the all the others in the second (2):

ORDER BY 
    CASE WHEN class IN ('A', 'B') THEN 1 ELSE 2 END,
    rank ;