Как найти минимальное значение mysql

Summary: in this tutorial, you will learn how to use the MySQL MIN() function to find the minimum value in a set of values.

Introduction to MySQL MIN() function

The MIN() function returns the minimum value in a set of values. The MIN() function is very useful in some scenarios such as finding the smallest number, selecting the least expensive product, or getting the lowest credit limit.

Here is the basic syntax of the MIN function:

MIN(DISTINCT expression);Code language: SQL (Structured Query Language) (sql)

In this syntax, the MIN() function accepts an expression which can be a column or a valid expression that involves columns.

The DISTINCT has no effect on the MIN() function like other aggregate functions such as SUM(), AVG()and COUNT().

MySQL MIN function examples

We’ll use the products table in the sample database for the demonstration.

A) Using MySQL MIN() function to find the minimum value in all rows

This query uses the MIN() function to get the lowest price of all product from the products table:

SELECT 
    MIN(buyPrice)
FROM
    products;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL MIN Function Example

In this example, the query checks all values in the column buyPrice of the products table and returns the lowest value.

B) Using MySQL MIN() with a WHERE clause example

This example uses the MIN() function to find the lowest buy price of all motorcycles:

SELECT 
    MIN(buyPrice)
FROM
    products
WHERE
    productline = 'Motorcycles';Code language: SQL (Structured Query Language) (sql)

In this example:

  • First, specify a condition in the WHERE clause that gets only products whose product line is Motorcycles.
  • Second, use the MIN() function to get the lowest value of the buy price of all motorcycles.

Here is the output:

MySQL MIN with a WHERE clause

C) Using MySQL MIN() with a subquery example

To find not only the price but also other product’s information such as product code and product name, you use the MIN() function in a subquery as shown in the following query:

SELECT 
    productCode, 
    productName, 
    buyPrice
FROM
    products
WHERE
    buyPrice = (
        SELECT 
            MIN(buyPrice)
        FROM
            products);Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL MIN with Subquery

How it works.

  • The subquery returns the lowest buy price product in the products table.
  • The outer query selects the product whose buy price is equal to the lowest price returned from the subquery.

D) Using MySQL MIN() function with a GROUP BY example

Like other aggregate functions, the MIN() function is often used with the GROUP BY clause to find the minimum values for every group.

This example uses the MIN() function with a GROUP BY clause to get the lowest buy price product for each product line:

SELECT 
    productline, 
    MIN(buyprice)
FROM
    products
GROUP BY productline;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL MIN with GROUP BY clause

In this example:

  • First, the GROUP BY clause groups products by product line.
  • Second, the MIN() function returns the lowest buy price product in each product line.

E) Using MySQL MIN() function with a HAVING clause example

This query finds product lines which have the lowest buy prices less than 21:

SELECT 
    productLine, 
    MIN(buyPrice)
FROM
    products
GROUP BY 
    productline
HAVING 
    MIN(buyPrice) < 25
ORDER BY 
    MIN(buyPrice);Code language: SQL (Structured Query Language) (sql)

MySQL MIN with a HAVING clause example

F) Using MySQL MIN() with a correlated subquery

The following query selects the lowest priced product in every product line by combining the MIN function with a correlated subquery:

SELECT 
    productline, 
    productCode, 
    productName, 
    buyprice
FROM
    products a
WHERE
    buyprice = (
        SELECT 
            MIN(buyprice)
        FROM
            products b
        WHERE
            b.productline = a.productline);Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL MIN with Correlated Subquery

In this example, for each product line from the outer query, the correlated subquery selects the lowest priced product in the product line and returns the lowest price.

The returned lowest price is then used as an input for the outer query to find the related product data including product line, product code, product name and buy price.

If you want to achieve the same result without using the MIN() function and a subquery, you can use a self join as follows:

SELECT 
    a.productline, 
    a.productCode, 
    a.productName, 
    a.buyprice
FROM
    products a
LEFT JOIN products b 
    ON a.productline = b.productline
        AND b.buyprice < a.buyprice
WHERE
    b.productcode IS NULL;Code language: SQL (Structured Query Language) (sql)

Try It Out

In this tutorial, you have learned how to use the MySQL MIN() function to find the minimum value in a set of values.

Was this tutorial helpful?

The MySQL MIN() function is an aggregate function that returns the minimum value from an expression.

Typically, the expression would be a range of values returned as separate rows in a column, and you can use this function to find the minimum value from the returned rows. If there are no matching rows, MIN() returns NULL.

For example, you can use this function to find out which city has the smallest population out of a list of cities.

Syntax

The syntax of MIN() goes like this:

MIN([DISTINCT] expr) [over_clause]

Where expr is the expression for which you want the minimum value.

The over_clause is an optional clause that works with window functions. Note that the over_clause can only be used if you don’t use the DISTINCT keyword.

The (optional) DISTINCT keyword can be used to eliminate duplicate values.

Basic Example

First, here’s the raw data that we’ll use in this example:

USE world;
SELECT Name, Population
FROM City
WHERE CountryCode = 'THA';

Result:

+-------------------+------------+
| Name              | Population |
+-------------------+------------+
| Bangkok           |    6320174 |
| Nonthaburi        |     292100 |
| Nakhon Ratchasima |     181400 |
| Chiang Mai        |     171100 |
| Udon Thani        |     158100 |
| Hat Yai           |     148632 |
| Khon Kaen         |     126500 |
| Pak Kret          |     126055 |
| Nakhon Sawan      |     123800 |
| Ubon Ratchathani  |     116300 |
| Songkhla          |      94900 |
| Nakhon Pathom     |      94100 |
+-------------------+------------+

We can use the MIN() function to find the city with the smallest population (i.e. the row with the smallest value in its population column).

USE world;
SELECT MIN(Population) AS 'Minimum Value'
FROM City
WHERE CountryCode = 'THA';

Result:

+---------------+
| Minimum Value |
+---------------+
|         94100 |
+---------------+

The GROUP BY Clause

We can use the GROUP BY clause to list out each district, along with the population of that district’s smallest city (by population):

USE world;
SELECT District, MIN(Population) AS 'Minimum Value'
FROM City
WHERE CountryCode = 'AUS'
GROUP BY District;

Result:

+-----------------+---------------+
| District        | Minimum Value |
+-----------------+---------------+
| New South Wales |        219761 |
| Victoria        |        125382 |
| Queensland      |         92273 |
| West Australia  |       1096829 |
| South Australia |        978100 |
| Capital Region  |        322723 |
| Tasmania        |        126118 |
+-----------------+---------------+

The ORDER BY Clause

We can also use the ORDER BY clause to specify a column with which to order by:

USE world;
SELECT District, MIN(Population) AS 'Minimum Value'
FROM City
WHERE CountryCode = 'AUS'
GROUP BY District
ORDER BY `Minimum Value` ASC;

Result:

+-----------------+---------------+
| District        | Minimum Value |
+-----------------+---------------+
| Queensland      |         92273 |
| Victoria        |        125382 |
| Tasmania        |        126118 |
| New South Wales |        219761 |
| Capital Region  |        322723 |
| South Australia |        978100 |
| West Australia  |       1096829 |
+-----------------+---------------+

This orders the results in ascending order, which lists the minimum value first.

Note that, when ordering by a multi-word alias (like `Minimum Value`), you need to use the backtick character (`) instead of the apostrophe (') to surround the two words.

Find the Minimum Character Length

The MIN() function isn’t limited to just columns with numerical data. You can also combine MIN() with other functions to return minimum values in other areas.

For example, using our sample data, we can find the value with the minimum number of characters in the City column:

SELECT MIN(CHAR_LENGTH(Name)) AS 'Minimum Character Length'
FROM city;

Result:

+--------------------------+
| Minimum Character Length |
+--------------------------+
|                        3 |
+--------------------------+

We can also see this by using the following query (which doesn’t involve the MIN() function):

SELECT Name, CHAR_LENGTH(Name) AS 'Character Length'
FROM city
ORDER BY `Character Length`
LIMIT 10;

Result:

+------+------------------+
| Name | Character Length |
+------+------------------+
| Ome  |                3 |
| Yao  |                3 |
| Qom  |                3 |
| Itu  |                3 |
| Tsu  |                3 |
| Ube  |                3 |
| Ise  |                3 |
| Uji  |                3 |
| Ede  |                3 |
| Ota  |                3 |
+------+------------------+

Seeing as multiple cities have the same character length, we can adjust this query to return only the distinct values:

SELECT DISTINCT CHAR_LENGTH(Name) AS 'Character Length'
FROM city
ORDER BY `Character Length`
LIMIT 10;

Result:

+------------------+
| Character Length |
+------------------+
|                3 |
|                4 |
|                5 |
|                6 |
|                7 |
|                8 |
|                9 |
|               10 |
|               11 |
|               12 |
+------------------+

Using an OVER Clause

As mentioned, the syntax allows for an OVER clause to be included in your queries. Basically, the OVER clause allows you to specify how to partition query rows into groups for processing by the window function.

Here’s an example:

SELECT 
    District,
    Name AS City,
    Population AS 'City Population',
    MIN(Population) OVER(PARTITION BY District) AS 'District Minimum'
FROM City
WHERE CountryCode = 'AUS'
ORDER BY `District Minimum` DESC;

Result:

+-----------------+---------------+-----------------+------------------+
| District        | City          | City Population | District Minimum |
+-----------------+---------------+-----------------+------------------+
| West Australia  | Perth         |         1096829 |          1096829 |
| South Australia | Adelaide      |          978100 |           978100 |
| Capital Region  | Canberra      |          322723 |           322723 |
| New South Wales | Sydney        |         3276207 |           219761 |
| New South Wales | Wollongong    |          219761 |           219761 |
| New South Wales | Newcastle     |          270324 |           219761 |
| New South Wales | Central Coast |          227657 |           219761 |
| Tasmania        | Hobart        |          126118 |           126118 |
| Victoria        | Melbourne     |         2865329 |           125382 |
| Victoria        | Geelong       |          125382 |           125382 |
| Queensland      | Townsville    |          109914 |            92273 |
| Queensland      | Brisbane      |         1291117 |            92273 |
| Queensland      | Cairns        |           92273 |            92273 |
| Queensland      | Gold Coast    |          311932 |            92273 |
+-----------------+---------------+-----------------+------------------+

This example partitions the rows by District, providing the minimum value for each partition (district). This allows you to see more granular data, such as each city’s population, along with the population of the smallest city (by population) in the same district.

В этом учебном пособии вы узнаете, как использовать MySQL функцию MIN с синтаксисом и примерами.

Описание

MySQL функция MIN возвращает минимальное значение выражения.

Синтаксис

Синтаксис MySQL функции MIN:

SELECT MIN(aggregate_expression)
FROM tables
[WHERE conditions];

ИЛИ синтаксис для функции MIN при группировке результатов по одному или нескольким столбцам:

SELECT expression1, expression2, … expression_n,
MIN(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, … expression_n;

Параметры или аргументы

expression1, expression2, … expression_n – выражения, которые не инкапсулированы в функции MIN, и должны быть включены в предложение GROUP BY в конце SQL запроса.

aggregate_expression – это столбец или выражение, из которого будет возвращено минимальное значение.

tables – таблицы, из которых вы хотите получить записи. Должна быть хотя бы одна таблица, указанная в предложении FROM.

WHERE conditions – необязательный. Это условия, которые должны быть выполнены для выбранных записей.

Применение

Функция MIN может использоваться в следующих версиях MySQL:

  • MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23

Пример с одним выражением

Рассмотрим примеры MySQL функции MIN, чтобы понять, как использовать функцию MIN в MySQL.

Например, вы, возможно, захотите узнать, какова минимальная заработная плата всех сотрудников.

SELECT MIN(salary) AS “Минимальная зарплата”

  FROM employees;

В этом примере выражению MIN (salary) присвоили псевдоним “Минимальная зарплата”. В результате в качестве имени поля при возврате результирующего набора будет отображаться “Минимальная зарплата”.

Пример: использование GROUP BY

В некоторых случаях вам потребуется использовать предложение GROUP BY с функцией MIN.

Например, вы также можете использовать функцию MIN, чтобы вернуть название отдела и минимальную зарплату в отделе.

SELECT department, MIN(salary) AS “Lowest salary”

  FROM employees

GROUP BY department;

Поскольку вы указали один столбец в своем операторе SELECT, который не инкапсулирован в функцию MIN, вы должны использовать предложение GROUP BY. Поэтому поле department должно быть обязательно указано в разделе GROUP BY.

MIN() in MySQL

Introduction to MySQL MIN() Function

MySQL MIN() function is an SQL query that returns the minimum value from a set of values recorded in a database table. Usually, MIN() is an aggregate function that can be used to calculate over a range of values returned by the SELECT query statement to find the minimum record from those separated rows in the table. MIN() function receives a conditional expression that can be a column name or valid term involving columns. The function returns a NULL value if no condition matches. Suppose we can use this function to find out the least population of a city from a list of cities.

Syntax with Explanation:

MIN ( [DISTINCT] Expression)

The term ‘Expression’ requires a numeric value that can either be a field in a table or a formula. This keyword allows for removing the duplicate values from the list of records in the database table. But almost it will be the same result without distinct keywords, too; it has not much effect on MIN () like on other SUM (), COUNT (), or AVG () aggregate functions.

Also,

MIN([DISTINCT] expression) [over_clause]

The over_clause is not compulsory but can be associated with window tasks. So, over_clause is used only if we don’t add the DISTINCT keyword in the MIN() function.

How Does MIN() Function Work in MySQL?

As we know that MIN() function is used to find the minimum value from the total rows selected by the select statement, we can now easily get the benefits in our business or product management. For example, it will allow getting the low-selling product of your company, a less expensive item, or a minimum quantity of the product in your store consumed by the customers.

We can apply this SQL query in our Databases which returns the result. MySQL MIN() SQL statement is shown below:

SELECT MIN ([Column_Name]) FROM [Source]

A database table as a source can return the minimum value present in the specified column by using the MIN() function.

Examples to Implement MIN() in MySQL

Given below are the examples of MIN() in MySQL:

Example #1 – Get minimum value in a column

Let us take the below-shown screenshot of records from a table of Products.

MIN() in MySQL 1

After inspection of all product prices, we applied the MIN() to get the product whose price is lower than others.

SELECT MIN(Price) AS SmallestPrice FROM Products;

Output:

MIN() in MySQL 2

Example #2 – With WHERE clause

Here we use MIN() to return the smallest value from a particular condition using the WHERE keyword with the SELECT statement.

SELECT MIN(Price) AS SmallestPrice FROM Products WHERE SupplierID=2;

Output:

min function with where clause

We have the smallest value for the only price whose SupplierID is two from the Products table. We can also use any multi-word alias (like SmallestPrice) to define the lowest value, as in the above query.

Example #3 – Sub-query statement

To provide not only the minimum price from the products table but also to show the row information, including other fields, we have used MIN() in a subquery form as follows:

SELECT * From Products WHERE Price = (SELECT MIN(Price) AS SmallestPrice FROM Products);

Output:

min function in a subquery statement

The inner query returns the lowest price, and the outer query provides the row information of the lowest price field in the products table.

Example #4 – With GROUP BY Clause

This function with the GROUP BY clause helps find the minimum value for every group based on the criteria.

SELECT SupplierID , MIN(Price) FROM Products GROUP BY SupplierID;

Output:

min function with group by clause

SupplierID groups the product fields from the Products table, but the minimum prices are arranged randomly, not ascending or descending.

Example #5 – With ORDER BY clause

This function with the ORDER BY clause helps to specify the column with which we can order by the minimum value for every group based on the criteria.

SELECT SupplierID , MIN(Price) FROM Products
GROUP BY SupplierID
ORDER BY MIN(price);

Output:

min function with order by clause

Now, the fields are grouped by SupplierID, and the result set is ordered based on MIN(Price) in ascending order, where the first small minimum value is set first and the next greater minimum at last.

Note: We can also use ASC or DESC to set an order BY clause like “ORDER BY MIN(Price) ASC”.

Example #6 – With HAVING clause

We use the HAVING clause with MIN() function to filter these groups based on a certain condition.

SELECT SupplierID , MIN(Price) FROM Products
GROUP BY SupplierID
HAVING MIN(Price) <50
ORDER BY MIN(price);

Output:

having clause

In the above query, firstly, we have used MIN() to get the lowest price from a group of Products with GROUP BY clause association, and again, based on the HAVING clause, we have applied the MIN function to get the lowest prices which are less than 50 in the table.

Next, suppose we want names of suppliers instead of supplier ids; then, we can even use the JOIN clause with the above query. We need to apply INNER JOIN for both the tables, Products, and Suppliers.

The example uses the Suppliers table data for supplier ID 1, 2, and 3.

min in mysql 6

Now the SQL statement for this is as follows:

SELECT SupplierName, MIN(Price) FROM Products
INNER JOIN Suppliers
USING (SupplierID)
GROUP BY SupplierName
HAVING MIN(Price) <50
ORDER BY MIN(price);

Output:
example 7

Example #7 – Find the Minimum Character Length

With MIN(), we can find the minimum value from numeric data in the column field and implement it in other areas. We can combine MySQL MIN() function with other functions like CHAR_LENGTH.

For example, taking the same Products table, we can write the following query and find the minimum number of characters in the ProductName column:

SELECT MIN(CHAR_LENGTH(ProductName)) AS 'Min Char Length'
FROM Products;

Output:

find minimum character length

Conclusion

So, MIN() function helps deal with many cases, such as getting the lowest number, the cheapest item, the least expensive product, the lowest credit limit, and the smallest payment from consumers. Hence, in this article, you all might have discovered some important usages of the MIN() function in MySQL with syntaxes and examples that will help you to treat the functional queries related to databases and tables with the areas of business or any industry with massive data stored.

Функция MIN() в SQL возвращает минимальное значение поля из всех найденных строк, которые удовлетворяют вашему запросу.

Синтаксис MIN()

SELECT MIN(поле_таблицы)
FROM имя_таблицы
WHERE условие_для_поиска;

Примеры запросов

Таблица SQL

1. Вывести минимальную заработную заработную плату сотрудников

SELECT min(salary)
FROM workers;

2. Вывести минимальную заработную плату среди сотрудников женского пола

SELECT MIN(salary)
FROM workers
WHERE sex = 'Женский';

Метки: MIN, SQL, Математические функции.

Добавить комментарий