PostgreSQL - conditional ordering
conditional order can be performed with CASE
, like here:
select *
from test
order by
flag
, case when flag then date end desc
, case when not flag then date end asc
Postgres order by condition when and then
Based on your description, that should be
ORDER BY CASE WHEN created <= '2020-09-14 10:00:00
THEN "type"
END,
created DESC
Postgresql conditional order by with multiple cases
Although dynamic SQL should be used rarely, this is case where the performance probably will be better:
BEGIN
..
EXECUTE format('SELECT .. ORDER BY %I %s', _sortcol,
CASE _sortdir WHEN 'desc' THEN 'desc'
WHEN 'asc' THEN 'asc'
ELSE 'asc' END);
When you use dynamic SQL, then you have to think about protection against SQL injection every time. Every string parameter have to be escaped or limited to safe value only.
Postgres: conditional ORDER BY
You can do what you describe using window functions. Something like this:
select *
from example e
order by primary_sort,
(case when count(*) over (partition by primary_sort, record_id) > 1 then record_sort
end) nulls last,
alt_sort;
This does not return the results you specify. But some variation is probably what you intend.
ORDER BY CASE WHEN ... ELSE ... END in PostgreSQL
You can use this trick to shorten the logic:
ORDER BY (CASE WHEN boolean_column THEN text_column END) ASC,
text_column DESC
It is still two order by
keys though.
Conditional Order By
SQL Fiddle
select
row_number() over() id, *
from (
select
r.routeid,
p.pointid,
label,
type,
labelstart,
labelend
from
route r
inner join
point p on p.routeid = r.routeid
where
r.type = 'E' and p.label % 2 = 0
or
r.type = 'O' and p.label % 2 != 0
or
r.type = 'A'
order by
r.routeid, r.progres, r.id,
case labelstart < labelend
when true then label
else label * - 1
end
) s
Related Topics
Extract Email Address from String Using Tsql
How to Remove All Newline from a Variable in SQL Server
How to Check If a Directory Exists Using SQL Server
Is Too Many Left Joins a Code Smell
How to Search for Names with Apostrophe in SQL Server
Understanding Bitmap Indexes in Postgresql
Ora-01779: Cannot Modify a Column Which Maps to a Non Key-Preserved Table
Predict The Number of Rows in Output
Adding a Non-Nullable Column to Existing Table Fails. Is The "Value" Attribute Being Ignored
How to Limit The Amount of Results Returned in Sybase
How to Deal with Spark Udf Input/Output of Primitive Nullable Type
Can't Connect to SQL 2012 Remotely by Ip and Named Instance
Sql Datetime Format to Date Only
Oracle 11G: Unpivot Multiple Columns and Include Column Name
Does Sqlite Support Replication