Navigation menu_icon

MySQL: ORDER BY single column multi order

25 September, 2016 at 05:09 PM

Problem was preety straight forward, client wanted to filter search reasult by date. As usual like always there is a but. Here the but is sorting pattern will change based on your visiting date.

Say Current date is 2016-09-23

Data Order Would be:
_________________________________________
Date		|Title		|Status	|
=========================================
2016-09-23	|Hello Java	|Active	|
-----------------------------------------
2016-09-24	|Hello C#	|Active	|
-----------------------------------------
2016-09-25	|Hello Angular	|Active	|
-----------------------------------------
2016-09-26	|Hello C++	|Active	|
-----------------------------------------
2016-09-27	|Hello CSS	|Active	|
-----------------------------------------
2016-09-22	|Hello PHP	|Passed	|
-----------------------------------------
2016-09-21	|Hello HTML	|Passed	|
-----------------------------------------

On the other hand if the current date is 2016-09-25

Data Order Would be:
_________________________________________
Date		|Title		|Status	|
=========================================
2016-09-25	|Hello Angular	|Active	|
-----------------------------------------
2016-09-26	|Hello C++	|Active	|
-----------------------------------------
2016-09-27	|Hello CSS	|Active	|
-----------------------------------------
2016-09-24	|Hello C#	|Passed	|
-----------------------------------------
2016-09-23	|Hello Java	|Passed	|
-----------------------------------------
2016-09-22	|Hello PHP	|Passed	|
-----------------------------------------
2016-09-21	|Hello HTML	|Passed	|
-----------------------------------------

That is, past time will be listed bellow the list as descending order but current & future date will be listed on top of the list but ascending order.

Here is solution query

SELECT date, title, (CASE WHEN date<CURDATE() THEN 'Passed' ELSE 'Active' END) FROM multi_order ORDER BY (CASE WHEN date<CURDATE() THEN CURRENT_TIMESTAMP()-TIMESTAMP(date) ELSE -1 END) ASC, date ASC

Here the table structure for you guys to play arround. Though the query can be optimized. That part is for the reader

CREATE TABLE IF NOT EXISTS `multi_order` (
  `date` date NOT NULL,
  `title` text,
  PRIMARY KEY (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `multi_order` (`date`, `title`) VALUES
	('2016-09-21', 'Hello Html'),
	('2016-09-22', 'Hello PHP'),
	('2016-09-23', 'Hello Java'),
	('2016-09-24', 'Hello C#'),
	('2016-09-25', 'Hello Angular'),
	('2016-09-26', 'Hello C++'),
	('2016-09-27', 'Hello CSS');
Back to Nafiul Alam Chowdhury's Blogs