Override ORDER BY in SQL with CASE WHEN

Did you know you can override the order that ORDER BY sorts by in SQL? I didn't — not until recently, at least. How it came up, I was writing a query that subdivided years into decades — including a catch-all “Pre-1950s” category. When I ordered by decade, though, “Pre-1950s” came out at the bottom — which is to say, 𝘢𝘧𝘵𝘦𝘳 the 2020s. Naturally, I wanted it on top, in chronological order. That’s when I learned this very handy trick: 𝐎𝐑𝐃𝐄𝐑 𝐁𝐘     𝐂𝐀𝐒𝐄 𝐖𝐇𝐄𝐍 𝐝𝐞𝐜𝐚𝐝𝐞 = '𝐏𝐫𝐞-1950𝐬' 𝐓𝐇𝐄𝐍 0 𝐄𝐋𝐒𝐄 1 𝐄𝐍𝐃,    𝐝𝐞𝐜𝐚𝐝𝐞; ORDER BY is basically creating an ad hoc table with a zero next to “Pre-1950s” and a 1 next to everything else: It’s like a temporary sort key. SQL does the preliminary sort according to the 0 and 1’s, and then the standard sorting by decade takes over after that. I’d never realized you could 𝘢𝘤𝘵𝘪𝘷𝘦𝘭𝘺 𝘣𝘶𝘪𝘭𝘥 𝘢𝘯 𝘰𝘳𝘥𝘦𝘳 within ORDER BY — I had always perceived its role as more passive than that. But now: A nifty new brush in the SQL paintbox! #dataanalytics #dataanalyticsjourney #sql #orderby

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories