1

I have this table

id  value 
1   OK
2   xminimum
3   NO
4   YES

I want to sort this table by value where minimum is always first then the rest according to alphabetic order of value column

Meaning:

xminimum
NO
OK
YES

I wrote this query:

Select *
from table_a
order by case when value='xminimum' then 1 else ????? end

I don't know what to put in the else... conceptually it should be else value end so it means alphabetic order.. but I can not combine integer with text.

How do I fix it?

3
  • Have you tried else 2, or else 0? Then add another item , value to the ORDER BY. Commented Jan 11, 2017 at 9:49
  • Didn't think of that. It works.. excellent :) post it as reply so I can accept Commented Jan 11, 2017 at 9:51
  • @jarlh, you should be posting that as answer Commented Jan 11, 2017 at 9:54

3 Answers 3

4

As requested, copied from my comment:

Select *
from table_a
order by case when value='xminimum' then 1 else 2 end, value
Sign up to request clarification or add additional context in comments.

Comments

2

Another solution:

SELECT *
FROM table_a
ORDER BY value <> 'xminimum', value;

4 Comments

What happens if a value is NULL?
NULL <> x is always NULL, as by default the NULLs are first my solution was wrong, good point :-) I update it.
I just checked, NULLS LAST is the default in ascending order, so my solution was correct in the end :D And the answer to your question is: "It will be put as the last result." :-)
Thanks for clearing that out! (Some dbms products may have NULLS FIRST as default.)
1

Do it like you have and add the value column as second column to sort by:

SELECT *
FROM table_a
ORDER BY CASE WHEN value='xminimum' THEN 1 ELSE 2 END, value

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.