8

I want to sort by a column where I want numbers to be ASC, but the last 2 rows should always be 0 then 1 (if they exists)

For example:

  • 8
  • 6
  • 10
  • 0
  • 2
  • 1

becomes

  • 2
  • 6
  • 8
  • 10
  • 0
  • 1

How would this be possible?

2 Answers 2

11

I think the clearest is to order both by

CASE WHEN column_name = 0
     THEN 0
     WHEN column_name = 1
     THEN 1
     ELSE -1
 END

(which puts all values except 0 and 1 before 0, and 0 before 1) and by column_name (so that the non-0, non-1 values appear in order).

For example:

SELECT column_name
  FROM table_name
 ORDER
    BY CASE WHEN column_name = 0
            THEN 0
            WHEN column_name = 1
            THEN 1
            ELSE -1
        END,
       column_name
;
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT * 
FROM YOURTABLE
ORDER BY CASE YOURCOLUMN
         WHEN YOURCOLUMN=0 THEN 0
         WHEN YOURCOLUMN=1 THEN 1
         ELSE -99
         END;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.