If you want to do the same for a UNION request, for example, if you have:
select id,name from friends UNION select id,name from friends order by id=5 desc
... you will get an exception in PostgreSQL:
You can use column names only for the result, not expressions or functions. TIP: add an expression / function to each SELECT or move UNION to the from clause
To get around this, you should use the following:
select id,name, (id=5) AS is_five from friends UNION select id,name, (id=5) AS is_five from friends order by is_five DESC, id DESC
The expression (id = 5) will return 't' OR 'f', depending on whether the column value is equal to or not the expected value (5), so the order will order the columns 't' first, then the rest.
Ucello Dec 08 '17 at 9:21 a.m. 2017-12-08 09:21
source share