PostgreSQL: order by column, with specific NON-NULL value LAST

孤者浪人 提交于 2019-12-06 04:59:23
Erwin Brandstetter

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:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!