Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select data where a field has a min value in MySQL?

I want to select data from a table in MySQL where a specific field has the minimum value, I've tried this:

SELECT * FROM pieces WHERE MIN(price) 

Please any help?

like image 793
Sami El Hilali Avatar asked Nov 13 '12 07:11

Sami El Hilali


People also ask

How do I find the lowest value in a column in MySQL?

MySQL MIN() Function. The MIN() function in MySQL is used to return the minimum value in a set of values from the table. It is an aggregate function that is useful when we need to find the smallest number, selecting the least expensive product, etc.

Can we use MIN function in WHERE clause?

You can get the lowest or minimum value using this function from any column, even you can filter the lowest or minimum value between specified expressions using the WHERE clause.

WHERE value is min value SQL?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.

How do I select a specific field in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.


2 Answers

this will give you result that has the minimum price on all records.

SELECT * FROM pieces WHERE price =  ( SELECT MIN(price) FROM pieces ) 
  • SQLFiddle Demo
like image 161
John Woo Avatar answered Oct 16 '22 16:10

John Woo


This is how I would do it, assuming I understand the question.

SELECT * FROM pieces ORDER BY price ASC LIMIT 1 

If you are trying to select multiple rows where each of them may have the same minimum price, then @JohnWoo's answer should suffice.

Basically here we are just ordering the results by the price in ascending order (ASC) and taking the first row of the result.

like image 40
sberry Avatar answered Oct 16 '22 16:10

sberry