4

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?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
GT.
  • 1,140
  • 13
  • 20
  • The usual suspects are missing: Postgres version and table definition (what you get with `\d tbl` in psql), which would show us exact data types and NOT NULL constraints. – Erwin Brandstetter Aug 25 '15 at 04:26

2 Answers2

5

Postgres allows boolean values in the ORDER BY clause, so here is your generalised 'X LAST':

ORDER BY (my_column = 'X')

The expression evaluates to boolean, resulting values sort this way:

FALSE (0)
TRUE (1)
NULL

Since we deal with non-null values, that's all we need. Here is your one-liner:

...
ORDER BY (zone = 'Future'), zone, status;

Related:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0

I'm not familiar postgreSQL specifically, but I've worked with similar problems in MS SQL server. As far as I know, the only "nice" way to solve a problem like this is to create a separate table of zone values and assign each one a sort sequence.

For example, let's call the table ZoneSequence:

Zone   | Sequence
------ | --------
IN1Z   |        1
IN2Z   |        2
IN3Z   |        3
Future |     1000

And so on. Then you simply join ZoneSequence into your query, and sort by the Sequence column (make sure to add good indexes!).

The good thing about this method is that it's easy to maintain when new zone codes are created, as they likely will be.

beercohol
  • 2,577
  • 13
  • 26