Search code examples
mysqlsqlsql-order-bysql-limit

SQL | LIMIT Clause | limit not achieved


I have the following query to get iPhones from table1 by color and limited to 10

SELECT * FROM table1 WHERE color = 'black' LIMIT 10

The above code works perfectly, When the black iPhones in table1 less than 10 I want to complete the iPhone's number to 10 with red color which I have also in table1 in one query


Solution

  • You can filter on both colors, and do a conditional sort:

    SELECT * 
    FROM table1 
    WHERE color in ('black', 'red')
    ORDER BY color = 'red'
    LIMIT 10
    

    Condition color = 'red' yields 1 when fulfilled, else 0 - so this actually puts 'black' first.

    You can also use field() here:

    SELECT * 
    FROM table1 
    WHERE color in ('black', 'red')
    ORDER BY FIELD(color, 'black', 'red')
    LIMIT 10