MySql - Finding minimum and maximum values

MySQL - Finding Minimum and Maximum Values (MIN, MAX)

Finding Minimum and Maximum Values (MIN, MAX) in MySQL

Introduction to MIN and MAX Functions in MySQL

In MySQL, the MIN and MAX functions are aggregate functions that help retrieve the minimum and maximum values from a set of records in a table. These functions are essential for data analysis, reporting, and decision-making processes where identifying extremes is necessary.

Understanding how to use MIN and MAX effectively can help you write powerful SQL queries to determine things like the highest salary, the earliest date, the cheapest product, or the latest transaction.

Syntax of MIN and MAX Functions


SELECT MIN(column_name) AS min_value
FROM table_name
WHERE condition;

SELECT MAX(column_name) AS max_value
FROM table_name
WHERE condition;

Here:

  • column_name: The column from which to find the minimum or maximum value.
  • table_name: The name of the table you are querying.
  • condition: Optional. Filters the rows considered by the function.

Creating a Sample Dataset

For illustration, let’s create a products table.


CREATE TABLE products (
    product_id INT PRIMARY KEY,
    product_name VARCHAR(100),
    category VARCHAR(50),
    price DECIMAL(10, 2),
    stock_quantity INT,
    date_added DATE
);

Insert some sample data:


INSERT INTO products (product_id, product_name, category, price, stock_quantity, date_added) VALUES
(1, 'Laptop', 'Electronics', 800.00, 50, '2024-05-01'),
(2, 'Smartphone', 'Electronics', 500.00, 100, '2024-05-03'),
(3, 'Tablet', 'Electronics', 300.00, 80, '2024-05-05'),
(4, 'Headphones', 'Accessories', 80.00, 200, '2024-05-07'),
(5, 'Charger', 'Accessories', 25.00, 300, '2024-05-08'),
(6, 'Mouse', 'Accessories', 15.00, 150, '2024-05-10'),
(7, 'Monitor', 'Electronics', 250.00, 30, '2024-05-12');

Basic Usage of MIN and MAX

Finding the Cheapest Product


SELECT MIN(price) AS cheapest_price
FROM products;

Result


+----------------+
| cheapest_price |
+----------------+
| 15.00          |
+----------------+

Finding the Most Expensive Product


SELECT MAX(price) AS most_expensive_price
FROM products;

Result


+----------------------+
| most_expensive_price |
+----------------------+
| 800.00               |
+----------------------+

Finding Minimum and Maximum in Different Columns

Finding the Product with the Least Stock


SELECT MIN(stock_quantity) AS least_stock
FROM products;

Result


+-------------+
| least_stock |
+-------------+
| 30          |
+-------------+

Finding the Product with the Most Stock


SELECT MAX(stock_quantity) AS most_stock
FROM products;

Result


+------------+
| most_stock |
+------------+
| 300        |
+------------+

Using MIN and MAX with GROUP BY

When you want to find the minimum and maximum values for each group, combine MIN or MAX with GROUP BY.

Example: Minimum Price Per Category


SELECT category, MIN(price) AS min_price
FROM products
GROUP BY category;

Result


+-------------+-----------+
| category    | min_price |
+-------------+-----------+
| Accessories | 15.00     |
| Electronics | 250.00    |
+-------------+-----------+

Example: Maximum Stock Per Category


SELECT category, MAX(stock_quantity) AS max_stock
FROM products
GROUP BY category;

Result


+-------------+-----------+
| category    | max_stock |
+-------------+-----------+
| Accessories | 300       |
| Electronics | 100       |
+-------------+-----------+

MIN and MAX with Conditions

Example: Maximum Price of Electronics


SELECT MAX(price) AS max_electronics_price
FROM products
WHERE category = 'Electronics';

Result


+-----------------------+
| max_electronics_price |
+-----------------------+
| 800.00                |
+-----------------------+

Example: Minimum Price of Accessories


SELECT MIN(price) AS min_accessories_price
FROM products
WHERE category = 'Accessories';

Result


+-----------------------+
| min_accessories_price |
+-----------------------+
| 15.00                 |
+-----------------------+

Finding Corresponding Records for MIN and MAX Values

Sometimes, it is not enough to know just the minimum or maximum value β€” you may also want to know which record holds that value.

Example: Product with the Minimum Price


SELECT *
FROM products
WHERE price = (SELECT MIN(price) FROM products);

Result


+------------+-------------+-------------+-------+---------------+------------+
| product_id | product_name| category    | price | stock_quantity| date_added |
+------------+-------------+-------------+-------+---------------+------------+
| 6          | Mouse       | Accessories | 15.00 | 150           | 2024-05-10 |
+------------+-------------+-------------+-------+---------------+------------+

Example: Product with the Maximum Stock


SELECT *
FROM products
WHERE stock_quantity = (SELECT MAX(stock_quantity) FROM products);

MIN and MAX on Date Columns

The MIN and MAX functions are also useful for date fields, like finding the oldest or newest records.

Example: Earliest Product Added


SELECT MIN(date_added) AS earliest_date
FROM products;

Result


+---------------+
| earliest_date |
+---------------+
| 2024-05-01    |
+---------------+

Example: Latest Product Added


SELECT MAX(date_added) AS latest_date
FROM products;

Result


+-------------+
| latest_date |
+-------------+
| 2024-05-12  |
+-------------+

MIN and MAX with JOIN Operations

You can combine MIN and MAX with JOINs for advanced querying across multiple tables.

Assuming Another Table: suppliers


CREATE TABLE suppliers (
    supplier_id INT PRIMARY KEY,
    supplier_name VARCHAR(100)
);

INSERT INTO suppliers (supplier_id, supplier_name) VALUES
(1, 'Alpha Supplies'),
(2, 'Beta Electronics');

ALTER TABLE products ADD supplier_id INT;

UPDATE products
SET supplier_id = 1
WHERE category = 'Accessories';

UPDATE products
SET supplier_id = 2
WHERE category = 'Electronics';

Query to Get Maximum Price Per Supplier


SELECT s.supplier_name, MAX(p.price) AS max_price
FROM products p
JOIN suppliers s ON p.supplier_id = s.supplier_id
GROUP BY s.supplier_name;

Handling NULL Values with MIN and MAX

By default, MIN and MAX ignore NULL values.

Example with NULL Prices


INSERT INTO products (product_id, product_name, category, price, stock_quantity, date_added, supplier_id)
VALUES (8, 'USB Cable', 'Accessories', NULL, 100, '2024-05-15', 1);

SELECT MIN(price) AS min_price
FROM products;

The NULL price does not affect the result, as MIN only considers non-NULL values.

MIN and MAX with Window Functions (MySQL 8+)

Window functions provide row-wise MIN and MAX without collapsing the result into a single row.

Example: Maximum Price per Category Without GROUP BY


SELECT product_name, category, price,
MAX(price) OVER (PARTITION BY category) AS max_price_in_category
FROM products;

The MIN and MAX functions are fundamental tools in SQL and data analysis. They help pinpoint critical insights about the extremes in your dataset, whether those are values, dates, quantities, or other metrics. By mastering these functions, you can build powerful queries that reveal trends, opportunities, and anomalies in your data.

With proper use alongside GROUP BY, JOINs, window functions, and subqueries, MIN and MAX can greatly enhance the versatility and depth of your MySQL querying capabilities.

logo

MySQL

Beginner 5 Hours
MySQL - Finding Minimum and Maximum Values (MIN, MAX)

Finding Minimum and Maximum Values (MIN, MAX) in MySQL

Introduction to MIN and MAX Functions in MySQL

In MySQL, the MIN and MAX functions are aggregate functions that help retrieve the minimum and maximum values from a set of records in a table. These functions are essential for data analysis, reporting, and decision-making processes where identifying extremes is necessary.

Understanding how to use MIN and MAX effectively can help you write powerful SQL queries to determine things like the highest salary, the earliest date, the cheapest product, or the latest transaction.

Syntax of MIN and MAX Functions

SELECT MIN(column_name) AS min_value FROM table_name WHERE condition; SELECT MAX(column_name) AS max_value FROM table_name WHERE condition;

Here:

  • column_name: The column from which to find the minimum or maximum value.
  • table_name: The name of the table you are querying.
  • condition: Optional. Filters the rows considered by the function.

Creating a Sample Dataset

For illustration, let’s create a products table.

CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(100), category VARCHAR(50), price DECIMAL(10, 2), stock_quantity INT, date_added DATE );

Insert some sample data:

INSERT INTO products (product_id, product_name, category, price, stock_quantity, date_added) VALUES (1, 'Laptop', 'Electronics', 800.00, 50, '2024-05-01'), (2, 'Smartphone', 'Electronics', 500.00, 100, '2024-05-03'), (3, 'Tablet', 'Electronics', 300.00, 80, '2024-05-05'), (4, 'Headphones', 'Accessories', 80.00, 200, '2024-05-07'), (5, 'Charger', 'Accessories', 25.00, 300, '2024-05-08'), (6, 'Mouse', 'Accessories', 15.00, 150, '2024-05-10'), (7, 'Monitor', 'Electronics', 250.00, 30, '2024-05-12');

Basic Usage of MIN and MAX

Finding the Cheapest Product

SELECT MIN(price) AS cheapest_price FROM products;

Result

+----------------+ | cheapest_price | +----------------+ | 15.00 | +----------------+

Finding the Most Expensive Product

SELECT MAX(price) AS most_expensive_price FROM products;

Result

+----------------------+ | most_expensive_price | +----------------------+ | 800.00 | +----------------------+

Finding Minimum and Maximum in Different Columns

Finding the Product with the Least Stock

SELECT MIN(stock_quantity) AS least_stock FROM products;

Result

+-------------+ | least_stock | +-------------+ | 30 | +-------------+

Finding the Product with the Most Stock

SELECT MAX(stock_quantity) AS most_stock FROM products;

Result

+------------+ | most_stock | +------------+ | 300 | +------------+

Using MIN and MAX with GROUP BY

When you want to find the minimum and maximum values for each group, combine MIN or MAX with GROUP BY.

Example: Minimum Price Per Category

SELECT category, MIN(price) AS min_price FROM products GROUP BY category;

Result

+-------------+-----------+ | category | min_price | +-------------+-----------+ | Accessories | 15.00 | | Electronics | 250.00 | +-------------+-----------+

Example: Maximum Stock Per Category

SELECT category, MAX(stock_quantity) AS max_stock FROM products GROUP BY category;

Result

+-------------+-----------+ | category | max_stock | +-------------+-----------+ | Accessories | 300 | | Electronics | 100 | +-------------+-----------+

MIN and MAX with Conditions

Example: Maximum Price of Electronics

SELECT MAX(price) AS max_electronics_price FROM products WHERE category = 'Electronics';

Result

+-----------------------+ | max_electronics_price | +-----------------------+ | 800.00 | +-----------------------+

Example: Minimum Price of Accessories

SELECT MIN(price) AS min_accessories_price FROM products WHERE category = 'Accessories';

Result

+-----------------------+ | min_accessories_price | +-----------------------+ | 15.00 | +-----------------------+

Finding Corresponding Records for MIN and MAX Values

Sometimes, it is not enough to know just the minimum or maximum value — you may also want to know which record holds that value.

Example: Product with the Minimum Price

SELECT * FROM products WHERE price = (SELECT MIN(price) FROM products);

Result

+------------+-------------+-------------+-------+---------------+------------+ | product_id | product_name| category | price | stock_quantity| date_added | +------------+-------------+-------------+-------+---------------+------------+ | 6 | Mouse | Accessories | 15.00 | 150 | 2024-05-10 | +------------+-------------+-------------+-------+---------------+------------+

Example: Product with the Maximum Stock

SELECT * FROM products WHERE stock_quantity = (SELECT MAX(stock_quantity) FROM products);

MIN and MAX on Date Columns

The MIN and MAX functions are also useful for date fields, like finding the oldest or newest records.

Example: Earliest Product Added

SELECT MIN(date_added) AS earliest_date FROM products;

Result

+---------------+ | earliest_date | +---------------+ | 2024-05-01 | +---------------+

Example: Latest Product Added

SELECT MAX(date_added) AS latest_date FROM products;

Result

+-------------+ | latest_date | +-------------+ | 2024-05-12 | +-------------+

MIN and MAX with JOIN Operations

You can combine MIN and MAX with JOINs for advanced querying across multiple tables.

Assuming Another Table: suppliers

CREATE TABLE suppliers ( supplier_id INT PRIMARY KEY, supplier_name VARCHAR(100) );
INSERT INTO suppliers (supplier_id, supplier_name) VALUES (1, 'Alpha Supplies'), (2, 'Beta Electronics');
ALTER TABLE products ADD supplier_id INT; UPDATE products SET supplier_id = 1 WHERE category = 'Accessories'; UPDATE products SET supplier_id = 2 WHERE category = 'Electronics';

Query to Get Maximum Price Per Supplier

SELECT s.supplier_name, MAX(p.price) AS max_price FROM products p JOIN suppliers s ON p.supplier_id = s.supplier_id GROUP BY s.supplier_name;

Handling NULL Values with MIN and MAX

By default, MIN and MAX ignore NULL values.

Example with NULL Prices

INSERT INTO products (product_id, product_name, category, price, stock_quantity, date_added, supplier_id) VALUES (8, 'USB Cable', 'Accessories', NULL, 100, '2024-05-15', 1);
SELECT MIN(price) AS min_price FROM products;

The NULL price does not affect the result, as MIN only considers non-NULL values.

MIN and MAX with Window Functions (MySQL 8+)

Window functions provide row-wise MIN and MAX without collapsing the result into a single row.

Example: Maximum Price per Category Without GROUP BY

SELECT product_name, category, price, MAX(price) OVER (PARTITION BY category) AS max_price_in_category FROM products;

The MIN and MAX functions are fundamental tools in SQL and data analysis. They help pinpoint critical insights about the extremes in your dataset, whether those are values, dates, quantities, or other metrics. By mastering these functions, you can build powerful queries that reveal trends, opportunities, and anomalies in your data.

With proper use alongside GROUP BY, JOINs, window functions, and subqueries, MIN and MAX can greatly enhance the versatility and depth of your MySQL querying capabilities.

Related Tutorials

Frequently Asked Questions for MySQL

Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.

To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.

MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.

Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.

Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.

DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.

A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.

The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.

Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.

 A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.

 Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.

 Use the command: CREATE DATABASE database_name; to create a new MySQL database.

Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.

Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.

Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.

CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.

MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.

A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.

Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.

Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.

A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.

Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.

Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.

JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.

Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.

line

Copyrights © 2024 letsupdateskills All rights reserved