Как найти минимальное значение в таблице sql

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.

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)

Given the following table in SQL Server 2005:

ID   Col1   Col2   Col3
--   ----   ----   ----
1       3     34     76  
2      32    976     24
3       7    235      3
4     245      1    792

What is the best way to write the query that yields the following result (i.e. one that yields the final column — a column containing the minium values out of Col1, Col2, and Col 3 for each row)?

ID   Col1   Col2   Col3  TheMin
--   ----   ----   ----  ------
1       3     34     76       3
2      32    976     24      24
3       7    235      3       3
4     245      1    792       1

UPDATE:

For clarification (as I have said in the coments) in the real scenario the database is properly normalized. These «array» columns are not in an actual table but are in a result set that is required in a report. And the new requirement is that the report also needs this MinValue column. I can’t change the underlying result set and therefore I was looking to T-SQL for a handy «get out of jail card».

I tried the CASE approach mentioned below and it works, although it is a bit cumbersome. It is also more complicated than stated in the answers because you need to cater for the fact that there are two min values in the same row.

Anyway, I thought I’d post my current solution which, given my constraints, works pretty well. It uses the UNPIVOT operator:

with cte (ID, Col1, Col2, Col3)
as
(
    select ID, Col1, Col2, Col3
    from TestTable
)
select cte.ID, Col1, Col2, Col3, TheMin from cte
join
(
    select
        ID, min(Amount) as TheMin
    from 
        cte 
        UNPIVOT (Amount for AmountCol in (Col1, Col2, Col3)) as unpvt
    group by ID
) as minValues
on cte.ID = minValues.ID

I’ll say upfront that I don’t expect this to offer the best performance, but given the circumstances (I can’t redesign all the queries just for the new MinValue column requirement), it is a pretty elegant «get out of jail card».

Salman A's user avatar

Salman A

259k82 gold badges428 silver badges520 bronze badges

asked Dec 15, 2008 at 13:27

stucampbell's user avatar

2

There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it’s not too bad.

Select Id,
       Case When Col1 < Col2 And Col1 < Col3 Then Col1
            When Col2 < Col1 And Col2 < Col3 Then Col2 
            Else Col3
            End As TheMin
From   YourTableNameHere

answered Dec 15, 2008 at 13:39

George Mastros's user avatar

George MastrosGeorge Mastros

24k4 gold badges50 silver badges59 bronze badges

7

Using CROSS APPLY:

SELECT ID, Col1, Col2, Col3, MinValue
FROM YourTable
CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A

SQL Fiddle

Stefan Steiger's user avatar

answered Apr 23, 2015 at 21:35

Nizam's user avatar

NizamNizam

4,5393 gold badges41 silver badges60 bronze badges

8

SELECT ID, Col1, Col2, Col3, 
    (SELECT MIN(Col) FROM (VALUES (Col1), (Col2), (Col3)) AS X(Col)) AS TheMin
FROM Table

The OP was tagged as sql-server, and this is an SQL Server specific answer. May not work on other DBMSs. (Search for least for Postgres derived DBs and some others).

answered Jan 4, 2016 at 11:03

dsz's user avatar

dszdsz

4,39538 silver badges32 bronze badges

5

On MySQL, use this:

select least(col1, col2, col3) FROM yourtable

HappyTown's user avatar

HappyTown

5,8967 gold badges36 silver badges51 bronze badges

answered Apr 3, 2014 at 9:46

user3493139's user avatar

user3493139user3493139

3973 silver badges3 bronze badges

9

You can use the «brute force» approach with a twist:

SELECT CASE
    WHEN Col1 <= Col2 AND Col1 <= Col3 THEN Col1
    WHEN                  Col2 <= Col3 THEN Col2
    ELSE                                    Col3
END AS [Min Value] FROM [Your Table]

When the first when condition fails it guarantees that Col1 is not the smallest value therefore you can eliminate it from rest of the conditions. Likewise for subsequent conditions. For five columns your query becomes:

SELECT CASE
    WHEN Col1 <= Col2 AND Col1 <= Col3 AND Col1 <= Col4 AND Col1 <= Col5 THEN Col1
    WHEN                  Col2 <= Col3 AND Col2 <= Col4 AND Col2 <= Col5 THEN Col2
    WHEN                                   Col3 <= Col4 AND Col3 <= Col5 THEN Col3
    WHEN                                                    Col4 <= Col5 THEN Col4
    ELSE                                                                      Col5
END AS [Min Value] FROM [Your Table]

Note that if there is a tie between two or more columns then <= ensures that we exit the CASE statement as early as possible.

answered Mar 2, 2015 at 13:09

Salman A's user avatar

Salman ASalman A

259k82 gold badges428 silver badges520 bronze badges

1

If the columns were integers as in your example I would create a function:

create function f_min_int(@a as int, @b as int) 
returns int
as
begin
    return case when @a < @b then @a else coalesce(@b,@a) end
end

then when I need to use it I would do :

select col1, col2, col3, dbo.f_min_int(dbo.f_min_int(col1,col2),col3)

if you have 5 colums then the above becomes

select col1, col2, col3, col4, col5,
dbo.f_min_int(dbo.f_min_int(dbo.f_min_int(dbo.f_min_int(col1,col2),col3),col4),col5)

answered Aug 28, 2012 at 13:48

Georgios's user avatar

GeorgiosGeorgios

691 silver badge2 bronze badges

2

The best way to do that is probably not to do it — it’s strange that people insist on storing their data in a way that requires SQL «gymnastics» to extract meaningful information, when there are far easier ways to achieve the desired result if you just structure your schema a little better :-)

The right way to do this, in my opinion, is to have the following table:

ID    Col    Val
--    ---    ---
 1      1      3
 1      2     34
 1      3     76

 2      1     32
 2      2    976
 2      3     24

 3      1      7
 3      2    235
 3      3      3

 4      1    245
 4      2      1
 4      3    792

with ID/Col as the primary key (and possibly Col as an extra key, depending on your needs). Then your query becomes a simple select min(val) from tbl and you can still treat the individual ‘old columns’ separately by using where col = 2 in your other queries. This also allows for easy expansion should the number of ‘old columns’ grow.

This makes your queries so much easier. The general guideline I tend to use is, if you ever have something that looks like an array in a database row, you’re probably doing something wrong and should think about restructuring the data.


However, if for some reason you can’t change those columns, I’d suggest using insert and update triggers and add another column which these triggers set to the minimum on Col1/2/3. This will move the ‘cost’ of the operation away from the select to the update/insert where it belongs — most database tables in my experience are read far more often than written so incurring the cost on write tends to be more efficient over time.

In other words, the minimum for a row only changes when one of the other columns change, so that’s when you should be calculating it, not every time you select (which is wasted if the data isn’t changing). You would then end up with a table like:

ID   Col1   Col2   Col3   MinVal
--   ----   ----   ----   ------
 1      3     34     76        3
 2     32    976     24       24
 3      7    235      3        3
 4    245      1    792        1

Any other option that has to make decisions at select time is usually a bad idea performance-wise, since the data only changes on insert/update — the addition of another column takes up more space in the DB and will be slightly slower for the inserts and updates but can be much faster for selects — the preferred approach should depend on your priorities there but, as stated, most tables are read far more often than they’re written.

answered Dec 15, 2008 at 13:43

paxdiablo's user avatar

paxdiablopaxdiablo

847k233 gold badges1568 silver badges1943 bronze badges

6

You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.

Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
From   YourTable T
       Inner Join (
         Select A.Id, Min(A.Col1) As TheMin
         From   (
                Select Id, Col1
                From   YourTable

                Union All

                Select Id, Col2
                From   YourTable

                Union All

                Select Id, Col3
                From   YourTable
                ) As A
         Group By A.Id
       ) As A
       On T.Id = A.Id

answered Dec 15, 2008 at 13:51

George Mastros's user avatar

George MastrosGeorge Mastros

24k4 gold badges50 silver badges59 bronze badges

2

This is brute force but works

 select case when col1 <= col2 and col1 <= col3 then col1
           case when col2 <= col1 and col2 <= col3 then col2
           case when col3 <= col1 and col3 <= col2 then col3
    as 'TheMin'
           end

from Table T

… because min() works only on one column and not across columns.

answered Dec 15, 2008 at 13:40

Learning's user avatar

LearningLearning

7,9793 gold badges35 silver badges46 bronze badges

1

Both this question
And this question try to answer this.

The recap is that Oracle has a built in function for this, with Sql Server you are stuck either defining a user-defined-function or using case statements.

Community's user avatar

answered Dec 16, 2008 at 2:40

Sam Saffron's user avatar

Sam SaffronSam Saffron

128k78 gold badges326 silver badges505 bronze badges

For multiple columns its best to use a CASE statement, however for two numeric columns i and j you can use simple math:

min(i,j) = (i+j)/2 — abs(i-j)/2

This formula can be used to get the minimum value of multiple columns but its really messy past 2, min(i,j,k) would be min(i,min(j,k))

answered Oct 11, 2016 at 15:50

crowley's user avatar

crowleycrowley

1001 silver badge5 bronze badges

If you’re able to make a stored procedure, it could take an array of values, and you could just call that.

answered Dec 15, 2008 at 13:44

Kev's user avatar

KevKev

15.7k15 gold badges79 silver badges112 bronze badges

4

select *,
case when column1 < columnl2 And column1 < column3 then column1
when columnl2 < column1 And columnl2 < column3 then columnl2
else column3
end As minValue
from   tbl_example

answered Dec 15, 2008 at 13:46

Phil Corcoran's user avatar

1

A little twist on the union query:

DECLARE @Foo TABLE (ID INT, Col1 INT, Col2 INT, Col3 INT)

INSERT @Foo (ID, Col1, Col2, Col3)
VALUES
(1, 3, 34, 76),
(2, 32, 976, 24),
(3, 7, 235, 3),
(4, 245, 1, 792)

SELECT
    ID,
    Col1,
    Col2,
    Col3,
    (
        SELECT MIN(T.Col)
        FROM
        (
            SELECT Foo.Col1 AS Col UNION ALL
            SELECT Foo.Col2 AS Col UNION ALL
            SELECT Foo.Col3 AS Col 
        ) AS T
    ) AS TheMin
FROM
    @Foo AS Foo

answered Aug 30, 2011 at 20:53

Lamprey's user avatar

If you use SQL 2005 you can do something neat like this:

;WITH    res
          AS ( SELECT   t.YourID ,
                        CAST(( SELECT   Col1 AS c01 ,
                                        Col2 AS c02 ,
                                        Col3 AS c03 ,
                                        Col4 AS c04 ,
                                        Col5 AS c05
                               FROM     YourTable AS cols
                               WHERE    YourID = t.YourID
                             FOR
                               XML AUTO ,
                                   ELEMENTS
                             ) AS XML) AS colslist
               FROM     YourTable AS t
             )
    SELECT  YourID ,
            colslist.query('for $c in //cols return min(data($c/*))').value('.',
                                            'real') AS YourMin ,
            colslist.query('for $c in //cols return avg(data($c/*))').value('.',
                                            'real') AS YourAvg ,
            colslist.query('for $c in //cols return max(data($c/*))').value('.',
                                            'real') AS YourMax
    FROM    res

This way you don’t get lost in so many operators :)

However, this could be slower than the other choice.

It’s your choice…

SteveC's user avatar

SteveC

15.6k23 gold badges101 silver badges173 bronze badges

answered Dec 15, 2008 at 15:53

leoinfo's user avatar

leoinfoleoinfo

7,8408 gold badges36 silver badges48 bronze badges

2

If you know what values you are looking for, usually a status code, the following can be helpful:

select case when 0 in (PAGE1STATUS ,PAGE2STATUS ,PAGE3STATUS,
PAGE4STATUS,PAGE5STATUS ,PAGE6STATUS) then 0 else 1 end
FROM CUSTOMERS_FORMS

answered Aug 28, 2013 at 19:47

Israel Margulies's user avatar

Israel MarguliesIsrael Margulies

8,6062 gold badges30 silver badges26 bronze badges

Below I use a temp table to get the minimum of several dates. The first temp table queries several joined tables to get various dates (as well as other values for the query), the second temp table then gets the various columns and the minimum date using as many passes as there are date columns.

This is essentially like the union query, the same number of passes are required, but may be more efficient (based on experience, but would need testing). Efficiency wasn’t an issue in this case (8,000 records). One could index etc.

--==================== this gets minimums and global min
if object_id('tempdb..#temp1') is not null
    drop table #temp1
if object_id('tempdb..#temp2') is not null
    drop table #temp2

select r.recordid ,  r.ReferenceNumber, i.InventionTitle, RecordDate, i.ReceivedDate
, min(fi.uploaddate) [Min File Upload], min(fi.CorrespondenceDate) [Min File Correspondence]
into #temp1
from record r 
join Invention i on i.inventionid = r.recordid
left join LnkRecordFile lrf on lrf.recordid = r.recordid
left join fileinformation fi on fi.fileid = lrf.fileid
where r.recorddate > '2015-05-26'
 group by  r.recordid, recorddate, i.ReceivedDate,
 r.ReferenceNumber, i.InventionTitle



select recordid, recorddate [min date]
into #temp2
from #temp1

update #temp2
set [min date] = ReceivedDate 
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
where t1.ReceivedDate < [min date] and  t1.ReceivedDate > '2001-01-01'

update #temp2 
set [min date] = t1.[Min File Upload]
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
where t1.[Min File Upload] < [min date] and  t1.[Min File Upload] > '2001-01-01'

update #temp2
set [min date] = t1.[Min File Correspondence]
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
where t1.[Min File Correspondence] < [min date] and t1.[Min File Correspondence] > '2001-01-01'


select t1.*, t2.[min date] [LOWEST DATE]
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
order by t1.recordid

answered Jan 2, 2016 at 0:37

user3438020's user avatar

SELECT [ID],
            (
                SELECT MIN([value].[MinValue])
                FROM
                (
                    VALUES
                        ([Col1]),
                        ([Col1]),
                        ([Col2]),
                        ([Col3])
                ) AS [value] ([MinValue])
           ) AS [MinValue]
FROM Table;

answered Nov 10, 2017 at 10:11

Tino Jose Thannippara's user avatar

I know that question is old, but I was still in the need of the answer and was not happy with other answers so I had to devise my own which is a twist on @paxdiablo´s answer.


I came from land of SAP ASE 16.0, and I only needed a peek at statistics of certain data which are IMHO validly stored in different columns of a single row (they represent different times — when arrival of something was planned, what it was expected when the action started and finally what was the actual time). Thus I had transposed columns into the rows of temporary table and preformed my query over this as usually.

N.B. Not the one-size-fits-all solution ahead!

CREATE TABLE #tempTable (ID int, columnName varchar(20), dataValue int)

INSERT INTO #tempTable 
  SELECT ID, 'Col1', Col1
    FROM sourceTable
   WHERE Col1 IS NOT NULL
INSERT INTO #tempTable 
  SELECT ID, 'Col2', Col2
    FROM sourceTable
   WHERE Col2 IS NOT NULL
INSERT INTO #tempTable 
  SELECT ID, 'Col3', Col3
    FROM sourceTable
   WHERE Col3 IS NOT NULL

SELECT ID
     , min(dataValue) AS 'Min'
     , max(dataValue) AS 'Max'
     , max(dataValue) - min(dataValue) AS 'Diff' 
  FROM #tempTable 
  GROUP BY ID

This took some 30 seconds on source set of 630000 rows and used only index-data, so not the thing to run in time-critical process but for things like one-time data inspection or end-of-the-day report you might be fine (but verify this with your peers or superiors, please!).
Main bonus of this style for me was that I could readily use more/less columns and change grouping, filtering, etc., especially once data was copyied over.

The additional data (columnName, maxes, …) were to aid me in my search, so you might not need them; I left them here to maybe spark some ideas :-).

answered Apr 18, 2019 at 13:25

Rao's user avatar

RaoRao

7827 silver badges17 bronze badges

case
when Col1 < Col2 and Col1 < Col3
then Col1
when Col2 is null and Col3 is null
then Col1
when Col1 < Col2 and Col3 is null
then Col1
when Col1 < Col3 and Col2 is null
then Col1
when Col2 < Col1 and Col2 < Col3
then Col2
when Col1 is null and Col3 is null
then Col2
when Col2 < Col1 and Col3 is null
then Col2
when Col2 < Col3 and Col1 is null
then Col2
when Col3 < Col1 and Col3 < Col2
then Col3
when Col1 is null and Col2 is null
then Col3
when Col3 < Col1 and Col2 is null
then Col3
when Col3 < Col2 and Col1 is null
then Col3
when Col2 = Col3
then Col2
when Col1 = Col3
then Col1
when Col1 = Col2
then Col1
when Col2 = Col3 and Col1 = Col3
then Col1
else null end as ‘MIN’

answered Jul 19, 2021 at 23:43

Emily's user avatar

EmilyEmily

91 bronze badge

1

В этом учебном материале вы узнаете, как использовать 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.

Summary: in this tutorial, you will learn how to use the SQL MIN function to get the minimum value in a set.

Introduction to SQL MIN function

The MIN function returns the minimum value in a set of values. The MIN function ignores the NULL values. The following is the syntax of the MIN function:

MIN(DISTINCT or ALL expression)

The ALL modifier instructs the MIN function to find the minimum value in all values including duplicates. The MIN() function uses the ALL modifier by default so you don’t have to specify it explicitly.

Unlike other aggregate functions e.g., SUM, COUNT, and AVG, the DISTINCT modifier is not applicable to the MIN() function. The DISTINCT modifier is only for ISO compatibility.

SQL MIN function examples

Let’s take a look at the products table in the sample database:

products table

Simple MIN function example

To find the lowest unit price of products in the products table, you use the MIN() function as follows:

SELECT MIN(unitprice) FROM products;

SQL MIN example

To get the cheapest products, you have to use a subquery that uses the MIN() function as the following query:

SELECT productid, productname, unitprice FROM products WHERE unitprice = ( SELECT MIN(unitprice) FROM products);

SQL MIN subquery

The outer query gets the cheapest products whose unit prices match the lowest price returned by the subquery. If multiple products have the same unit price as the lowest price, the query will return more than one row.

SQL MIN function with GROUP BY clause example

To find the lowest unit price of the product in each category, you use the MIN() function with a GROUP BY clause:

SELECT categoryid, MIN(unitprice) FROM products GROUP BY categoryid;

SQL MIN GROUP BY

The GROUP BY clause divides the products by categoryid into groups. For each group, the MIN() function returns the lowest unit price.

SQL MIN function with HAVING clause example

To get the category that has the lowest unit price less than $7, you use the MIN() function with the GROUP BY and HAVING clauses as follows:

SELECT categoryid, MIN(unitprice) FROM products GROUP BY categoryid HAVING MIN(unitprice) < 7;

SQL MIN HAVING example

SQL MIN with correlated subquery example

To get the cheapest product in each category, you use the  MIN() function in a correlated subquery as follows:

SELECT categoryid, productid, productName, unitprice FROM products a WHERE unitprice = ( SELECT MIN(unitprice) FROM products b WHERE b.categoryid = a.categoryid)

The outer query scans all rows in the products table and returns the products that have unit prices match the lowest price in each category returned by the correlated subquery.

In this tutorial, we have shown you how to use SQL MIN function to get the minimum value in a set.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти долю от чего либо
  • Как найти торгового представителя сталкер
  • Как найти индивидуалку форум
  • Как найти свои картинки в интернете
  • Не сматывается ремень безопасности как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии