Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting in case mysql

Tags:

php

mysql

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
like image 384
mask man Avatar asked Jun 03 '15 11:06

mask man


People also ask

Can you ORDER BY a case statement in SQL?

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.

Can we use ORDER BY in case?

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 .

Is MySQL ORDER BY case sensitive?

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.

How do I sort items in MySQL?

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.


1 Answers

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
like image 134
Abhik Chakraborty Avatar answered Oct 01 '22 03:10

Abhik Chakraborty