Wednesday, June 26, 2013

SQL sort in custom order

I came across a requirement where in I had to fetch records from DB in some specific order.
Example, Get all the records from credit_card table with all master_cards first, visa 2nd, amex 3rd etc.
The regular sort by clause doesn't work.

The solution is here:
SELECT * FROM TABLE_CREDIT_CARD
      ORDER BY CASE
            WHEN CARD_TYPE='MASTER_CARD' THEN 1
            WHEN CARD_TYPE='VISA' THEN 2
            WHEN CARD_TYPE='MAESTRO' THEN 3
            WHEN CARD_TYPE='AMEX' THEN 4
            ELSE 5

      END

No comments:

Post a Comment