Home > Enterprise >  How to get ORDER BY to output alphabetically when looking for the cheapest item(s)
How to get ORDER BY to output alphabetically when looking for the cheapest item(s)

Time:03-05

I have a table that looks like this:

     Products

| id |   name  | price |
|  1 | peaches |   3   |
|  2 | oranges |   3   |
|  3 | lemons  |   3   |
|  4 | apricots|   3   |

I need to be able to find the cheapest product on the list the price but if they are all the same price then just output the one of the cheapest in alphabetical order. Which in this case would be apricots 3.

The query I wrote worked for all cases apart from this specific one in which there are more than 1 of the same "cheapest" price.

SELECT name, MIN(price)
FROM Products
ORDER BY name ASC, price

In this case, it's outputting peaches 3 because it's the first item on the list. How can I get it to output the variable in alphabetical order when the MIN(price) is the same across all the variables?

CodePudding user response:

use this

SELECT name, MIN(price)
FROM Products
ORDER BY price,name

CodePudding user response:

You can do:

select *
from products
order by price, name
limit 1
  • Related