In Postgres, I am trying to have a SQL which orders by multiple columns. The first column will always be priority DESC NULLS LAST
. The second one needs to be dynamic based on some conditions (for ease of example, here I have WHEN 1 = 1
).
SELECT id, title, priority
FROM post
ORDER BY
priority DESC NULLS LAST,
CASE WHEN 1 = 1 THEN created_at ASC ELSE created_at DESC END;
This throws an error:
syntax error at or near "ASC"
LINE 5: CASE WHEN 1 = 1 THEN created_at ASC ELSE created_at ...
How can I have CASE
in the second key of the ORDER BY
?
2
Answers
You can not use
DESC
orASC
in case when … else … end.This is ORDER BY part: ORDER BY <expression> DESC.
Try use date difference with any
anchor
date – integer value.Or convert date to bigint and use sign (+/-)
Fiddle
You can’t use ASC or DESC directly in the CASE statement, same is also described in below stack overflow post
Case statement for Order By clause with Desc/Asc sort
Instead you can do below