Как найти минимум в sql

In this tutorial, you will learn about the MAX() and MIN() functions in SQL with the help of examples.

In SQL,

  • The MAX() function returns the maximum value of a column.
  • The MIN() function returns the minimum value of a column.

SQL MAX() Function

The syntax of the SQL MAX() function is:

SELECT MAX(columnn)
FROM table;

Here,

  • column is the name of the column you want to filter
  • table is the name of the table to fetch the data from

For example,

SELECT MAX(age)
FROM Customers;

Here, the SQL command returns the largest value from the age column.

How to use MAX() in SQL

Example: MAX() in SQL

SQL MIN() Function

The syntax of the SQL MIN() function is:

SELECT MIN(columnn)
FROM table;

Here,

  • column is the name of the column you want to filter
  • table is the name of the table to fetch the data from

For Example,

SELECT MIN(age)
FROM Customers;

Here, the SQL command returns the smallest value from the age column.

How to use MIN() in SQL

Example: MIN() in SQL

Aliases With MAX() and MIN()

In the above examples, the field names in the result sets were MIN(age) and MAX(age).

It is also possible to give custom names to these fields using the AS keyword. For example,

-- use max_age as an alias for the maximum age
SELECT MAX(age) AS max_age
FROM Customers;

Here, the field name MAX(age) is replaced with max_age in the result set.

How to use alias in SQL with MAX or MIN function

Example: MAX() in SQL with Alias

MAX() and MIN() With Strings

The MAX() and MIN() functions also work with texts. For example,

--select the minimum value of first_name from Customers

SELECT MIN(first_name) AS min_first_name
FROM Customers;

Here, the SQL command selects the minimum value of first_name based on the dictionary order.

How to use MIN or MAX with String in SQL

Example: MIN() in SQL with String

MAX() and MIN() in Nested SELECT

As we know, the MAX() function returns the maximum value. Similarly, the MIN() function returns the minimum value.

However, if we want to select the whole row containing that value, we can use the nested SELECT statement like this.

-- MIN() function in a nested SELECT statement

SELECT *
FROM Customers
WHERE age = (
    SELECT MIN(age)
    FROM Customers
);

Here, the SQL command selects all the customers with the smallest age.

How to find all rows that have min or max specified value

Example: Nested MIN() in SQL

More SQL MAX() and MIN() Examples

We can also find the highest or lowest value from two or more values using the MAX() and MIN() function. For example,

-- returns 50 as highest
SELECT MAX(20, 30, 50) as highest;

-- returns 20 as lowest
SELECT MIN(20, 30, 50) as lowest;

Let’s see how we can use MAX() and MIN() function with HAVING:

SELECT *
FROM Customers
GROUP BY country
HAVING MAX(age);

Here, the SQL command returns the maximum age in each country from the Customers table.

To learn more, visit SQL HAVING Clause.


Recommended Readings:

  • SQL Alias
  • SQL Subquery (Nested Select)

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

Описание

SQL функция MIN используется для возврата минимального значения выражения в операторе SELECT.

Синтаксис

Синтаксис для функции MIN в SQL.

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
Необязательный. Это условия, которые должны быть выполнены для выбора записей

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

Простейшим способом использования SQL функции MIN было бы возвращение одного поля, которое вычисляет значение MIN.
Например, вы можете узнать минимальную зарплату всех сотрудников.

SELECT MIN(salary) AS “Lowest salary”

  FROM employees;

В этом примере SQL функции MIN у нас выражению MIN(salary) указан псевдоним “Lowest salary”. В результате “Lowest salary” будет отображаться как имя поля при возврате набора результатов.

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

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

SELECT department,

       MIN(salary) AS “Lowest salary”

  FROM employees

GROUP BY department;

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

Here are three examples of using SQL to find and select the row with the minimum value in a given column.

The examples work in most major RDBMSs, including MySQL, MariaDB, PostgreSQL, SQLite, Oracle, and SQL Server.

Sample Data

Let’s start with the following data:

SELECT * FROM PetShow;

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 1       | Wag       | 85      |
| 2       | Scratch   | 3       |
| 3       | Tweet     | 65      |
| 4       | Bark      | 8       |
| 5       | Ruff      | 15      |
| 6       | Woof      | 20      |
+---------+-----------+---------+

Option 1

Here’s our first option for selecting the row with the minimum value from the above table:

SELECT 
    PetId,
    PetName,
    Score
FROM PetShow 
WHERE Score = ( SELECT MIN(Score) FROM PetShow );

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 2       | Scratch   | 3       |
+---------+-----------+---------+

Here, we used the MIN() function within a subquery to find the minimum value, and returned the whole row with the outer query.

When there are Multiple Rows with the Min Value

Using this method, if there are multiple rows with the minimum value, all of them are returned.

Suppose we insert another row into our table with the same score as the existing minimum score:

INSERT INTO PetShow VALUES (7, 'Punch', 3);
SELECT * FROM PetShow;

Our table now looks like this:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 1       | Wag       | 85      |
| 2       | Scratch   | 3       |
| 3       | Tweet     | 65      |
| 4       | Bark      | 8       |
| 5       | Ruff      | 15      |
| 6       | Woof      | 20      |
| 7       | Punch     | 3       |
+---------+-----------+---------+

We can see that both Scratch and Punch have got the low score of 3.

Let’s run the previous query again to return the minimum value from that column:

SELECT 
    PetId,
    PetName,
    Score
FROM PetShow 
WHERE Score = ( SELECT MIN(Score) FROM PetShow );

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 2       | Scratch   | 3       |
| 7       | Punch     | 3       |
+---------+-----------+---------+

Both rows with the minimum values are returned.

We can limit the result set to just one row if required. The exact code will depend on the RDBMS being used.

The LIMIT clause can be used with RDBSs such as PostgreSQL, MariaDB, MySQL, and SQLite:

SELECT 
    PetId,
    PetName,
    Score
FROM PetShow 
WHERE Score = ( SELECT MIN(Score) FROM PetShow )
ORDER BY PetId ASC
LIMIT 1;

Result:

+-------+---------+-------+
| PetId | PetName | Score |
+-------+---------+-------+
|     2 | Scratch |     3 |
+-------+---------+-------+

In SQL Server, we can use the TOP clause:

SELECT TOP 1
    PetId,
    PetName,
    Score
FROM PetShow 
WHERE Score = ( SELECT MIN(Score) FROM PetShow )
ORDER BY PetId ASC;

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 2       | Scratch   | 3       |
+---------+-----------+---------+

And in Oracle Database, we can do this:

SELECT
    PetId,
    PetName,
    Score
FROM PetShow 
WHERE Score = ( SELECT MIN(Score) FROM PetShow )
ORDER BY PetId ASC
FETCH FIRST 1 ROW ONLY;

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 2       | Scratch   | 3       |
+---------+-----------+---------+

Option 2

If we only want one row returned, we can actually do away with most of the other code and just get the first row out of the ordered results:

SELECT 
    PetId,
    PetName,
    Score
FROM PetShow 
ORDER BY Score ASC
LIMIT 1;

Result:

+-------+---------+-------+
| PetId | PetName | Score |
+-------+---------+-------+
|     7 | Punch   |     3 |
+-------+---------+-------+

In SQL Server:

SELECT TOP 1
    PetId,
    PetName,
    Score
FROM PetShow 
ORDER BY Score ASC;

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 2       | Scratch   | 3       |
+---------+-----------+---------+

And in Oracle Database:

SELECT
    PetId,
    PetName,
    Score
FROM PetShow 
ORDER BY Score ASC
FETCH FIRST 1 ROW ONLY;

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 2       | Scratch   | 3       |
+---------+-----------+---------+

Option 3

Another way to select the row with the minimum value is to join the table on itself, like this:

SELECT 
    p1.PetId, 
    p1.PetName, 
    p1.Score
FROM PetShow p1
LEFT JOIN PetShow p2 ON p1.Score < p2.Score
WHERE p2.PetId IS NULL;

Result:

+---------+-----------+---------+
| PetId   | PetName   | Score   |
|---------+-----------+---------|
| 1       | Wag       | 85      |
| 8       | Purr      | 85      |
+---------+-----------+---------+

As with the earlier example, we can limit the results to one row (or some other number) if required.

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

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

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

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

Таблица SQL

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

SELECT min(salary)
FROM workers;

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

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

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

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