Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort by empty string ASC then by ID DESC

For some reason i cant manage to sort results 1st by empty string and then by id DESC,
its look like ORDER BY url ASC is sorting by length of string .

How to tell query to sort by empty not by length and than by id desc ?

EXAMPLE LINK

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * FROM r WHERE r.type IN('product','manual_change') ORDER BY url ASC, id DESC


        CREATE TABLE `r` (
      `id` int(11) NOT NULL,
      `id_type` int(11) NOT NULL,
      `type` enum('category','product','manufacturer','manual_change') NOT NULL,
      `redirect_type` tinyint(1) NOT NULL,
      `url` varchar(300) NOT NULL,
      `link_from` varchar(300) NOT NULL COMMENT 'manual change, use url as LINK_TO'
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;



    INSERT INTO `r` (`id`, `id_type`, `type`, `redirect_type`, `url`, `link_from`) VALUES
    (38, 0, 'manual_change', 0, '', ''),
    (39, 0, 'manual_change', 0, 'example1.com', ''),
    (29, 27406, 'product', 0, 'example11.com', ''),
    (42, 0, 'manual_change', 0, 'example111.com', ''),
    (41, 27339, 'product', 0, 'example1111.com', ''),
    (24, 27382, 'product', 0, 'example1111.com', ''),
    (43, 0, 'manual_change', 0, 'example.com', ''),
    (22, 27352, 'product', 0, 'example.com', ''),
    (20, 27319, 'product', 0, 'example.com', ''),
    (19, 27322, 'product', 0, 'example.com', '');

>Solution :

You can order by case:

SELECT * 
FROM r 
WHERE r.type IN('product','manual_change') 
ORDER BY case when r.url='' then r.url end desc,id desc ;

https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=9273bc6070ce3b278e2f65d6f791d1c9

I suggest better using null rather than empty strings

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading