Home > Database > Mysql Tutorial > How to Select Rows with the Minimum Value in a MySQL Table?

How to Select Rows with the Minimum Value in a MySQL Table?

Mary-Kate Olsen
Release: 2024-10-27 03:41:03
Original
1032 people have browsed it

How to Select Rows with the Minimum Value in a MySQL Table?

Getting Minimal Fields in MySQL

Selecting data from a table where a specific field holds the minimum value can be a common task when managing data in MySQL. To do this, one must avoid the mistake of using the MIN() function incorrectly.

Incorrect Approach:

As mentioned in the query provided, using MIN(field) directly will not return the row with the lowest value. Instead, it will return the minimum value among all rows.

Correct Approach:

The solution lies in combining the MIN() function with the WHERE clause. Here's the correct query:

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )
Copy after login

This query will retrieve all rows where the price field matches the minimum price obtained from the subquery.

Example:

Imagine a table named pieces with the following columns:

| id | name  | price |
|----|-------|-------|
| 1  | Bolt  | 3.50  |
| 2  | Nut   | 1.25  |
| 3  | Screw | 2.99  |
| 4  | Washer| 0.50  |
Copy after login

Executing the correct query will return the following result:

| id | name  | price |
|----|-------|-------|
| 4  | Washer| 0.50  |
Copy after login

Thus, the row with the lowest price (Washer with a price of 0.50) is extracted.

The above is the detailed content of How to Select Rows with the Minimum Value in a MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template