Reputation: 513
I have a table whose values are suppose
c,d,b,a
I want to sort the values except 'a'
. It should always be at the bottom. The order should be
b,c,d,a
.
Upvotes: 0
Views: 62
Reputation: 44891
You can use a case statement to do this:
select * from table1
order by case when val = 'a' then 1 else 0 end, val
This will sort all values that are not 'a' before 'a', and then by the value.
As pointed out by Mr Zorn in a comment, and by Luke101 in another answer this statement can be simplified as:
select * from table1
order by val = 'a', val
The former solution should work across all ANSI compliant databases, the latter works in MySQL, Postgresql and some others (but not MSSQL for instance).
Upvotes: 5
Reputation: 11556
First select the columns from table which NOT IN
a
and the sort those values and then UNION
the a
column.
SELECT t.name FROM
(
SELECT * FROM tbl
WHERE name NOT IN ('a')
ORDER BY name
)t
UNION
SELECT * FROM tbl
WHERE name IN ('a');
Upvotes: 0