How to use Min and Max Function in MySQL or MariaDB - MySQL Developer Tutorial

How to use Min and Max Function in MySQL or MariaDB

Scenario:

Let's say you are working as MySQL Developer, you have Customer table with SaleAmount. You are asked to write a query that should return Max SaleAmount and Min SaleAmount from the Customer table.


Solution:

You can use Max and Min aggregate functions in MySQL to find the Maximum and Minimum values.

Let's create Customer Table with sample data so we can use Max and Min functions.




Create table Customer
 (Id int,
  FName VARCHAR(50),
  LName VARCHAR(50),
  CountryShortName CHAR(2),
  SaleAmount Int);

-- Insert Rows in Customer Table
insert into Customer
Values (
1,'Raza','M','PK',10),
(2,'Rita','John','US',12),
(3,'Sukhi','Singh',Null,25),
(4,'James','Smith','CA',60),
(5,'Robert','Ladson','US',54),
(6,'Alice','John','US',87),
(6,'John',Null,'US',Null);


Let's run the below query with Max and Min functions to finder the answer of our question.


SELECT Max(saleamount) AS MaxSaleAmount, 
       Min(saleamount) AS MinSaleAmount 
FROM   customer; 




How to use Max and Min function in MySQL or MariaDB