SELECT *
FROM case_study
ORDER BY CASE
WHEN expiry_date_case > CURDATE() THEN 3
WHEN expiry_date_case IS NULL THEN 2
WHEN expiry_date_case < CURDATE() THEN 1
END DESC
The above query work's fine, But i want to sort the items
by expiry date in ASC in one case and DESC in one case.How to acheive this it should be some thing like this
pseudo query
WHEN expiry_date_case > CURDATE() THEN 3 expiry_date_case ASC
WHEN expiry_date_case IS NULL THEN 2
WHEN expiry_date_case < CURDATE() THEN 1 expiry_date_case DESC
SQL order by case can be used when we have to order the data on a conditional basis and define the criteria on which the ordering will be done based on a certain condition.
Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY .
MySQL by default will make the ORDER BY option in queries case sensitive. This means that rows with the same starting letters (but different case) may be ordered non-alphabetically.
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Here is a more generic form of doing the sorting, where you can use multiple conditions for ordering other than date
SELECT *
FROM case_study
ORDER BY
CASE
WHEN expiry_date_case > CURDATE() THEN 3
WHEN expiry_date_case IS NULL THEN 2
WHEN expiry_date_case < CURDATE() THEN 1
END DESC,
case when expiry_date_case > CURDATE() then expiry_date_case end,
case when expiry_date_case < CURDATE() then expiry_date_case end desc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With