Paste this into a new question or an answer at dba.stackexchange.com:
<!-- --> > CREATE TABLE table1 ( > `id` INTEGER, > `title` VARCHAR(18), > `rank_index` VARCHAR(4) > ); > > INSERT INTO table1 > (`id`, `title`, `rank_index`) > VALUES > ('1', 'An awesome product', NULL), > ('2', 'Another product', '3'), > ('3', 'Baby car', NULL), > ('4', 'Green carpet', '1'), > ('5', 'Toy', NULL); > > <pre> > ✓ > > ✓ > </pre> <!-- --> > SELECT t1.id, t1.`title`,t1.`rank_index` > FROM table1 t1 CROSS JOIN ( SELECT MAX(id) maxid FROM table1) t2 > ORDER BY IF(rank_index IS NULL, maxid - id + 1 , rank_index - 0.5) ASC > > <pre> > id | title | rank_index > -: | :----------------- | :--------- > 4 | Green carpet | 1 > 5 | Toy | <em>null</em> > 2 | Another product | 3 > 3 | Baby car | <em>null</em> > 1 | An awesome product | <em>null</em> > </pre> *db<>fiddle [here](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c99d5e43761dfa66503eca8d37bb0617)*
back to fiddle