When I discovered NULLS LAST
, I kinda hoped it could be generalised to 'X LAST' in a CASE
statement in the ORDER BY
portion of a query.
Not so, it would seem.
I'm trying to sort a table by two columns (easy), but get the output in a specific order (easy), with one specific value of one column to appear last (got it done... ugly).
Let's say that the columns are zone
and status
(don't blame me for naming a column zone
- I didn't name them). status
only takes 2 values ('U' and 'S'), whereas zone
can take any of about 100 values.
One subset of zone
's values is (in pseudo-regexp) IN[0-7]Z
, and those are first in the result. That's easy to do with a CASE
.
zone
can also take the value 'Future', which should appear LAST in the result.
In my typical kludgy-munge way, I have simply imposed a CASE
value of 1000 as follows:
group by zone, status
order by (
case when zone='IN1Z' then 1
when zone='IN2Z' then 2
when zone='IN3Z' then 3
.
. -- other IN[X]Z etc
.
when zone = 'Future' then 1000
else 11 -- [number of defined cases +1]
end), zone, status
This works, but it's obviously a kludge, and I wonder if there might be one-liner doing the same.
Is there a cleaner way to achieve the same result?
Postgres allows boolean
values in the ORDER BY
clause. For your generalised 'X LAST':
ORDER BY (my_column = 'X')
The expression evaluates to boolean
, which sorts this way:
false -- think '0'
true -- think '1'
null -- NULLS LAST is default sort order
Since we deal with notnull values, that's all we need. Here is your one-liner:
ORDER BY (zone = 'Future'), zone, status;
Related: