I want to arrange pending orders by eta in asc order and completed orders in desc order, with all completed orders appearing at the bottom of the list. Not sure if this is possible in a single query.
Example data from orders table:
order | status | eta |
---|---|---|
1 | pending | 20-01-2025 |
2 | complete | 15-01-2025 |
3 | ordered | 28-01-2025 |
4 | complete | 16-01-2025 |
5 | sailing | 25-01-2025 |
I would like the above data to be displayed as follows:
order | status | eta |
---|---|---|
1 | pending | 20-01-2025 |
3 | sailing | 25-01-2025 |
5 | ordered | 28-01-2025 |
4 | complete | 16-01-2025 |
2 | complete | 15-01-2025 |
in the above result only the eta column is ordered, where all ‘complete’ orders at the bottom
I am using Laravel to build my app, with a Postgres backend, but I am sure any SQL solution will help. I am trying to avoid running separate queries and concat them.
6
Answers
Something like this will work in sql – you haven’t told us what the tables are called
I would agree with previous comment where you should provide Data Sample and what you have tried.
Having said that, you can try the following query:
Find the example here
fiddle
The
status = 'complete'
evaluates toboolean
, wherefalse
sorts beforetrue
.If the column is defined
NOT NULL
, you are all set.If the column isn’t defined
NOT NULL
, usestatus IS NOT DISTINCT FROM 'complete'
instead to make sure only ‘completed’ is sorted last.ASC
andDESC
are syntax elements and cannot be parameterized. For data types that can be "inverted", like numeric types, you can work around this limitation by multplying with -1 for descending order. So I convert the date withEXTRACT()
and then multiply with the same expression. In this case a simpleWHEN status = 'complete'
covers null values as well, as only the first branch is only entered ontrue
.Or an optimized variant of what you found yourself:
fiddle
All nice trickery. But it won’t use plain indexes. This is more verbose, but less confusing and typically faster with an index on
(status, eta)
:fiddle
See:
And avoid reserved words like "order" as identifiers.
It is simple to Sort the records by One Column in ASC and Another Column in DSC You can just use:
SQL Query Syntax: SELECT Col1,Col2,… FROM TABLE ORDER BY ASC Col1, DESC Col2;
for further assistance refer this W3 Schools Website Link:See Example 2 Well it is for MYSQL But most of them should work.
An option, if available, is creating a ENUM for the
status
column. Then declare the column as the enum type defined. Sorting is then determined by the sequence of defined values in the enum. (see demo).