WebArch WebArch - 6 months ago 7
SQL Question

Reordering MySQL rows based on a certain row

I have a table in MySQL and this table contains the information of the adverts in my website. In some cases, a row need to go on top of query result to be shown first in the page and this might be needed for some other rows frequently. I'm looking for a proper way to push up a specific row to the top of the query result.

What is the best solution to accomplish this task?

Answer

let assume your special row has a field like SpecialAd

 SELECT *
 FROM YourTable
 ORDER BY CASE 
              WHEN `SpecialAd` = true THEN 0
                                      ELSE 1
          END,
          OtherSortField

with this all SpecialAd will be show first, and you can use the second SortField to sort inside each group.

Comments