Search code examples
mysqlsqlsql-order-byunion

Query with ORDER BY clause and sending certain rows at the end of the results separately


Given that I want to query over a single table and this table has this structure and data

price | weight
 100      0
 200     10
 500      0
 300     10

I would like to apply an ORDER BY price DESC but I want also results with weight = 10 to be at the end of the results (and these results also applying the ORDER BY price DESC).

Results Query A         WHERE weight <> 10
----------------
price | weight
100       0
500       0

Results Query B         WHERE weight = 10
----------------
price | weight
200       10
300       10

I have thought in using UNION but I can't achieve this which is what I want:

EXPECTED RESULT      <= order by price DESC
----------------
price | weight
500       0
100       0
300      10      <=
200      10      <= but maintaining rows with weight 10 at the end of the results

How would you do that? Thanks in advance


Solution

  • If you sort first by the boolean expression weight = 10, all such rows will be placed at the bottom of the resultset:

    ORDER BY weight = 10,
             price DESC
    

    because weight = 10 is evaluated as 1 for true and 0 for false.