Popular Searches
Popular Course Categories
Popular Courses

Finding Minimum and Maximum Values Using MIN and MAX

Finding Minimum and Maximum Values Using MIN and MAX

Aggregate Functions and Data Grouping

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

Course: MySQL Training

Topic: Finding Minimum and Maximum Values Using MIN() and MAX()

Course Link: MySQL Training Course

Demo Link: Register for a Course Demo


1. Introduction to MIN() and MAX() in MySQL

MySQL provides aggregate functions such as MIN() and MAX() to identify the smallest and largest values in a column or expression. These functions are useful when analyzing numeric values, dates, times, and text values.

The MIN() function returns the minimum value from the selected records, while the MAX() function returns the maximum value. Both functions are commonly used in sales reports, employee management systems, product catalogs, inventory databases, financial analysis, and data reporting.

For example, a business may use MIN() to find the lowest product price and MAX() to identify the highest product price. An HR department may use these functions to find the earliest joining date or the latest joining date among employees.

Example

Consider a table named products containing the following records:

product_id product_name price
1 Keyboard 1500.00
2 Mouse 800.00
3 Monitor 12000.00
4 Laptop 55000.00

To find the lowest and highest prices, execute:

SELECT
    MIN(price) AS minimum_price,
    MAX(price) AS maximum_price
FROM products;

Expected output:

minimum_price maximum_price
800.00 55000.00

The minimum price is 800.00, and the maximum price is 55000.00.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the purpose of the MIN() and MAX() aggregate functions.
  • Find the smallest value in a numeric column.
  • Find the largest value in a numeric column.
  • Use aliases to provide meaningful names for calculated results.
  • Combine MIN() and MAX() in a single SQL query.
  • Filter records before calculating minimum and maximum values.
  • Calculate minimum and maximum values for groups using GROUP BY.
  • Filter grouped results using HAVING.
  • Find the earliest and latest dates in a table.
  • Understand how NULL values affect aggregate functions.
  • Use aggregate functions in practical database reporting and analysis.
  • Identify common errors when working with minimum and maximum values.

3. Understanding Aggregate Functions

An aggregate function performs a calculation on a collection of values and returns a summarized result. Instead of returning every individual value, it produces a result based on the selected records.

MySQL supports several aggregate functions, including SUM(), COUNT(), AVG(), MIN(), and MAX().

Function Purpose Example
MIN() Returns the smallest value. MIN(price)
MAX() Returns the largest value. MAX(price)
SUM() Adds numeric values. SUM(amount)
COUNT() Counts rows or non-NULL values. COUNT(*)
AVG() Calculates the average of non-NULL numeric values. AVG(price)

3.1 What Is MIN()?

MIN() is an aggregate function that returns the smallest non-NULL value from the selected values. It can be used with numeric values, dates, times, and strings.

3.2 What Is MAX()?

MAX() is an aggregate function that returns the largest non-NULL value from the selected values. Its result depends on the data type and comparison rules used by MySQL.

3.3 Why Are MIN() and MAX() Important?

  • They help identify the lowest and highest values in a dataset.
  • They simplify reporting and data analysis.
  • They help detect price ranges and value limits.
  • They can be used to identify earliest and latest dates.
  • They support grouped summaries, such as minimum salary by department.
  • They help analysts understand the range and distribution of data.

4. Creating a Sample Database and Table

To practise these functions, create a database and a sample product table.

4.1 Create a Database

CREATE DATABASE company_db;

This statement creates a database named company_db. If it already exists, MySQL will report an error unless you use an appropriate existence check.

4.2 Select the Database

USE company_db;

This statement selects the database for subsequent SQL operations.

4.3 Create the Products Table

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

The table contains product names, categories, prices, inventory quantities, and creation dates. The DECIMAL(10, 2) data type is appropriate for many monetary values because it supports fixed decimal precision.

4.4 Insert Sample Records

INSERT INTO products
(product_id, product_name, category, price, stock_quantity, created_at)
VALUES
(1, 'Keyboard', 'Accessories', 1500.00, 25, '2026-01-05'),
(2, 'Mouse', 'Accessories', 800.00, 50, '2026-01-08'),
(3, 'Monitor', 'Electronics', 12000.00, 15, '2026-01-12'),
(4, 'Laptop', 'Electronics', 55000.00, 10, '2026-02-02'),
(5, 'Printer', 'Electronics', 18000.00, 8, '2026-02-10'),
(6, 'Office Chair', 'Furniture', 7500.00, 20, '2026-02-15'),
(7, 'Office Desk', 'Furniture', 15000.00, 12, '2026-03-01'),
(8, 'Webcam', 'Accessories', 3200.00, 30, '2026-03-06');

These records provide different prices, stock quantities, categories, and dates for practising minimum and maximum calculations.

4.5 View the Table Records

SELECT *
FROM products;

Viewing the records helps you understand the data before applying aggregate functions.

5. Finding the Minimum Value Using MIN()

The MIN() function finds the smallest value among the selected records. It is frequently used to identify the lowest price, smallest quantity, earliest date, or minimum recorded measurement.

5.1 Basic Syntax

SELECT MIN(column_name) AS minimum_value
FROM table_name;

Explanation:

  • SELECT specifies the value to retrieve.
  • MIN() finds the smallest value.
  • column_name identifies the column being evaluated.
  • AS minimum_value assigns a readable name to the result.
  • FROM table_name identifies the source table.

5.2 Find the Lowest Product Price

SELECT MIN(price) AS lowest_price
FROM products;

Expected output:

lowest_price
800.00

The lowest price is 800.00, corresponding to the Mouse product.

5.3 Find the Minimum Stock Quantity

SELECT MIN(stock_quantity) AS minimum_stock
FROM products;

Expected output:

minimum_stock
8

This query returns the smallest stock quantity recorded among all products.

5.4 Find the Earliest Product Date

SELECT MIN(created_at) AS earliest_product_date
FROM products;

Expected output:

earliest_product_date
2026-01-05

For date columns, MIN() returns the earliest non-NULL date.

6. Finding the Maximum Value Using MAX()

The MAX() function finds the largest value among the selected records. It can be used to identify the highest price, greatest stock quantity, latest date, or maximum recorded measurement.

6.1 Basic Syntax

SELECT MAX(column_name) AS maximum_value
FROM table_name;

6.2 Find the Highest Product Price

SELECT MAX(price) AS highest_price
FROM products;

Expected output:

highest_price
55000.00

The highest price is 55000.00, corresponding to the Laptop product.

6.3 Find the Maximum Stock Quantity

SELECT MAX(stock_quantity) AS maximum_stock
FROM products;

Expected output:

maximum_stock
50

This query returns the largest stock quantity recorded in the table.

6.4 Find the Latest Product Date

SELECT MAX(created_at) AS latest_product_date
FROM products;

Expected output:

latest_product_date
2026-03-06

For date columns, MAX() returns the latest non-NULL date.

7. Using MIN() and MAX() Together

You can use both aggregate functions in a single query to find the lowest and highest values at the same time. This approach is efficient and useful for reporting.

7.1 Find the Lowest and Highest Prices

SELECT
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price
FROM products;

Expected output:

lowest_price highest_price
800.00 55000.00

7.2 Find the Minimum and Maximum Stock

SELECT
    MIN(stock_quantity) AS minimum_stock,
    MAX(stock_quantity) AS maximum_stock
FROM products;

This query returns the smallest and largest stock quantities in one result row.

7.3 Find Minimum and Maximum Dates

SELECT
    MIN(created_at) AS earliest_date,
    MAX(created_at) AS latest_date
FROM products;

This query provides the earliest and latest dates recorded in the table.

7.4 Calculate the Difference Between Maximum and Minimum

You can subtract the minimum value from the maximum value to calculate the range of a numeric column.

SELECT
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price,
    MAX(price) - MIN(price) AS price_range
FROM products;

Expected output:

lowest_price highest_price price_range
800.00 55000.00 54200.00

The price range is calculated as 55000.00 − 800.00 = 54200.00.

8. Using MIN() and MAX() with WHERE

The WHERE clause filters rows before the aggregate functions are evaluated. This allows you to find the minimum or maximum value for a selected category, status, date range, or other condition.

8.1 Find the Lowest Price in Electronics

SELECT MIN(price) AS lowest_electronics_price
FROM products
WHERE category = 'Electronics';

Expected output:

lowest_electronics_price
12000.00

Only products belonging to the Electronics category are included in the calculation.

8.2 Find the Highest Price in Accessories

SELECT MAX(price) AS highest_accessories_price
FROM products
WHERE category = 'Accessories';

Expected output:

highest_accessories_price
3200.00

8.3 Find the Lowest Price Above a Threshold

SELECT MIN(price) AS lowest_price_above_5000
FROM products
WHERE price > 5000;

This query returns the smallest price among products priced above 5000.

8.4 Find the Highest Price Within a Date Range

SELECT MAX(price) AS highest_price_in_period
FROM products
WHERE created_at >= '2026-02-01'
  AND created_at < '2026-03-01';

This query finds the maximum product price among records dated in February 2026. The date condition uses an inclusive start and exclusive end, which is a useful pattern for date and date-time filtering.

8.5 Use Multiple Conditions

SELECT MIN(price) AS lowest_price
FROM products
WHERE category = 'Electronics'
  AND stock_quantity > 5;

This query returns the minimum price among Electronics products whose stock quantity is greater than five.

9. Using MIN() and MAX() with GROUP BY

The GROUP BY clause divides records into groups and calculates the minimum or maximum value separately for each group. This is useful when comparing different product categories, departments, regions, or customers.

9.1 Minimum Price by Category

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

Expected output:

category lowest_price
Accessories 800.00
Electronics 12000.00
Furniture 7500.00

Each category appears once, showing its lowest recorded product price.

9.2 Maximum Price by Category

SELECT
    category,
    MAX(price) AS highest_price
FROM products
GROUP BY category;

Expected output:

category highest_price
Accessories 3200.00
Electronics 55000.00
Furniture 15000.00

9.3 Minimum and Maximum Prices by Category

SELECT
    category,
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price
FROM products
GROUP BY category;

This query provides the price range for every category in a single result set.

9.4 Grouping by Multiple Columns

SELECT
    category,
    created_at,
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price
FROM products
GROUP BY category, created_at
ORDER BY category, created_at;

This query groups products by both category and creation date. Each unique combination produces a separate group.

10. Filtering Groups with HAVING

The HAVING clause filters grouped results based on aggregate calculations. Use it when you want to return only groups whose minimum or maximum value meets a condition.

10.1 Categories with a Maximum Price Above 10000

SELECT
    category,
    MAX(price) AS highest_price
FROM products
GROUP BY category
HAVING MAX(price) > 10000;

This query returns only categories whose highest product price is greater than 10000.

10.2 Categories with a Minimum Price Below 5000

SELECT
    category,
    MIN(price) AS lowest_price
FROM products
GROUP BY category
HAVING MIN(price) < 5000;

This query returns categories that contain at least one product with a price below 5000, because their minimum price is below that threshold.

10.3 Difference Between WHERE and HAVING

WHERE HAVING
Filters individual records before grouping. Filters groups after aggregate calculations.
Commonly checks regular column values. Commonly checks aggregate results.
WHERE category = 'Electronics' HAVING MAX(price) > 10000

10.4 Combining WHERE and HAVING

SELECT
    category,
    MAX(price) AS highest_price
FROM products
WHERE stock_quantity > 5
GROUP BY category
HAVING MAX(price) > 10000;

First, MySQL filters out products whose stock quantity is five or less. It then groups the remaining products by category and returns only groups whose maximum price exceeds 10000.

11. Using MIN() and MAX() with ORDER BY and LIMIT

Aggregate functions return calculated values, while ORDER BY sorts the result rows. LIMIT restricts how many rows are returned.

11.1 Sort Categories by Maximum Price

SELECT
    category,
    MAX(price) AS highest_price
FROM products
GROUP BY category
ORDER BY highest_price DESC;

This query displays categories from the highest maximum price to the lowest.

11.2 Display the Category with the Highest Maximum Price

SELECT
    category,
    MAX(price) AS highest_price
FROM products
GROUP BY category
ORDER BY highest_price DESC
LIMIT 1;

This returns one category with the highest category-level maximum price. If multiple categories share the same value, add a secondary ordering column for predictable selection.

11.3 Sort Categories by Minimum Price

SELECT
    category,
    MIN(price) AS lowest_price
FROM products
GROUP BY category
ORDER BY lowest_price ASC;

This query sorts categories from the lowest minimum price to the highest.

12. Finding the Record Associated with a Minimum or Maximum Value

An important distinction is that MIN() and MAX() return the minimum or maximum value, not the entire row containing that value. If you need the associated product name or employee details, you must retrieve the matching record separately.

12.1 Find the Product with the Lowest Price

SELECT product_id, product_name, price
FROM products
WHERE price = (
    SELECT MIN(price)
    FROM products
);

This query returns the product record or records whose price equals the minimum price in the table.

12.2 Find the Product with the Highest Price

SELECT product_id, product_name, price
FROM products
WHERE price = (
    SELECT MAX(price)
    FROM products
);

This query returns the product record or records whose price equals the maximum price in the table.

12.3 Why Use a Subquery?

A subquery is a query placed inside another SQL statement. In these examples, the inner query calculates the minimum or maximum price, and the outer query retrieves the records matching that value.

  • The inner query finds the required minimum or maximum value.
  • The outer query compares each product's price with that value.
  • All matching records are returned, including ties.

12.4 Find the Lowest Price in Each Category with Product Details

SELECT p.product_id, p.product_name, p.category, p.price
FROM products p
JOIN (
    SELECT category, MIN(price) AS lowest_price
    FROM products
    GROUP BY category
) AS category_min
    ON p.category = category_min.category
   AND p.price = category_min.lowest_price;

This query returns the product or products that have the lowest price in each category. If multiple products share the minimum price in a category, all matching products are returned.

13. Using MIN() and MAX() with Date and Time Values

The MIN() and MAX() functions are not limited to numeric data. They can also evaluate date and time columns.

13.1 Find the Earliest Date

SELECT MIN(created_at) AS earliest_date
FROM products;

This query returns the earliest non-NULL date in the table.

13.2 Find the Latest Date

SELECT MAX(created_at) AS latest_date
FROM products;

This query returns the latest non-NULL date in the table.

13.3 Find the Date Range

SELECT
    MIN(created_at) AS first_date,
    MAX(created_at) AS last_date
FROM products;

This query identifies the date range covered by the records.

13.4 Find the Earliest and Latest Sale for Each Category

If a table contains transaction dates, you can group by category and find the date range for each category.

SELECT
    category,
    MIN(created_at) AS earliest_date,
    MAX(created_at) AS latest_date
FROM products
GROUP BY category;

This is useful for analyzing when products or records first appeared and when the most recent records were created.

14. Understanding NULL Values in MIN() and MAX()

In MySQL, NULL represents a missing or unknown value. The MIN() and MAX() aggregate functions ignore NULL values and calculate their results using non-NULL values.

14.1 Example with NULL Values

CREATE TABLE price_test (
    item_id INT PRIMARY KEY,
    price DECIMAL(10, 2)
);

INSERT INTO price_test (item_id, price)
VALUES
(1, 100.00),
(2, 250.00),
(3, NULL),
(4, 400.00);

SELECT
    MIN(price) AS minimum_price,
    MAX(price) AS maximum_price
FROM price_test;

Expected output:

minimum_price maximum_price
100.00 400.00

The NULL value is ignored, so the minimum is 100.00 and the maximum is 400.00.

14.2 What Happens When All Values Are NULL?

SELECT
    MIN(price) AS minimum_price,
    MAX(price) AS maximum_price
FROM price_test
WHERE price IS NULL;

Both functions return NULL because the selected rows contain no non-NULL price values.

14.3 What Happens When No Rows Match?

SELECT
    MIN(price) AS minimum_price,
    MAX(price) AS maximum_price
FROM products
WHERE category = 'Books';

If no records match the condition, both aggregate functions return NULL. This is different from returning zero, because zero is a numeric value while NULL indicates that no applicable value was found.

14.4 Display a Default Value with COALESCE()

SELECT
    COALESCE(MIN(price), 0) AS minimum_price,
    COALESCE(MAX(price), 0) AS maximum_price
FROM products
WHERE category = 'Books';

COALESCE() returns the first non-NULL expression. In this example, it displays zero when an aggregate result is NULL. Use this only when zero is an appropriate reporting default for missing results.

15. MIN() and MAX() with Text Columns

The MIN() and MAX() functions can also work with text columns. For strings, MySQL determines the minimum and maximum according to the column's character set and collation rules.

15.1 Find the Alphabetically Earliest Product Name

SELECT MIN(product_name) AS earliest_name
FROM products;

The result is the minimum string according to the applicable collation. It should not be interpreted as the product with the lowest price.

15.2 Find the Alphabetically Greatest Product Name

SELECT MAX(product_name) AS greatest_name
FROM products;

The result is the maximum string according to the applicable collation rules.

15.3 Important Note About Text Comparison

  • Text comparison depends on the column's character set and collation.
  • Some collations compare strings without distinguishing letter case.
  • Accents and other character differences may be treated differently by different collations.
  • Use numeric columns with MIN() and MAX() when you need the lowest or highest numeric value.
  • Do not assume that the minimum or maximum string represents the earliest or latest business event unless the column's ordering rules match that requirement.

16. Difference Between MIN(), MAX(), and ORDER BY

Both aggregate functions and sorting can help identify extreme values, but they operate differently.

Method Purpose Example
MIN(price) Returns the smallest price value. SELECT MIN(price) FROM products;
MAX(price) Returns the largest price value. SELECT MAX(price) FROM products;
ORDER BY price ASC LIMIT 1 Returns one row with the lowest price, subject to the ordering. SELECT * FROM products ORDER BY price ASC LIMIT 1;
ORDER BY price DESC LIMIT 1 Returns one row with the highest price, subject to the ordering. SELECT * FROM products ORDER BY price DESC LIMIT 1;

16.1 When Should You Use MIN() or MAX()?

Use MIN() or MAX() when you need the extreme value itself, such as the lowest price or latest date.

16.2 When Should You Use ORDER BY?

Use ORDER BY when you need to sort records or retrieve the complete row associated with an extreme value. Add a secondary ordering column if ties must be resolved predictably.

17. Common Errors and Troubleshooting

17.1 Using an Incorrect Column Name

Problem: The query refers to a column that does not exist.

SELECT MIN(product_price)
FROM products;

If the table has a column named price instead of product_price, MySQL reports an unknown-column error.

Solution: Verify the table structure.

DESCRIBE products;

17.2 Expecting MIN() to Return the Entire Row

Problem: The query returns only a minimum value, but the developer also needs the product name and ID.

Solution: Use a subquery to identify the minimum value and retrieve the matching records, or use an appropriately ordered query when one row is sufficient.

17.3 Getting NULL Instead of a Number

Problem: The result is NULL.

Possible causes:

  • No rows match the WHERE condition.
  • All selected values are NULL.
  • The table contains no applicable values for the requested calculation.

Solution: Inspect the data and filter conditions. If required, use COALESCE() to display a default value.

17.4 Confusing Minimum Price with Minimum Stock

Problem: The query calculates a minimum from the wrong column.

Solution: Confirm which value you need to evaluate. Use MIN(price) for the lowest price and MIN(stock_quantity) for the smallest stock quantity.

17.5 Incorrect Results After Joining Tables

Problem: The query produces unexpected grouped values after a JOIN.

Solution: Review the join conditions and ensure the query is grouping at the intended level. Remember that joins can duplicate rows, although duplicate copies of the same value do not change a basic MIN() or MAX() result. Duplicated or incorrectly matched records can still cause other reporting errors.

17.6 Using WHERE with Aggregate Results

Problem: A query attempts to filter groups using MIN() or MAX() inside the WHERE clause.

SELECT category, MAX(price) AS highest_price
FROM products
WHERE MAX(price) > 10000
GROUP BY category;

This is not the correct way to filter groups by an aggregate value.

Solution: Use HAVING.

SELECT category, MAX(price) AS highest_price
FROM products
GROUP BY category
HAVING MAX(price) > 10000;

18. Best Practices for MIN() and MAX()

  • Choose the correct column for the calculation.
  • Use descriptive aliases such as lowest_price and highest_price.
  • Combine both functions in one query when comparing minimum and maximum values.
  • Use WHERE to limit the records included in the calculation.
  • Use GROUP BY to calculate minimum and maximum values for categories or other groups.
  • Use HAVING to filter groups based on aggregate results.
  • Remember that NULL values are ignored by these aggregate functions.
  • Use appropriate numeric data types for prices, quantities, and measurements.
  • Use date and time data types for dates instead of storing dates as arbitrary text.
  • Use subqueries or joins when you need the full record associated with a minimum or maximum value.
  • Account for ties when retrieving records with the highest or lowest value.
  • Use an explicit secondary sort column when a query with LIMIT must return a predictable row.
  • Validate query results against sample records when troubleshooting.
  • Review execution plans and indexes when querying large datasets.

19. Practical Exercises

Use the products table to practise the following tasks.

Exercise 1: Find the Lowest Product Price

Write a query to find the minimum value in the price column.

Exercise 2: Find the Highest Product Price

Write a query to find the maximum value in the price column.

Exercise 3: Find Minimum and Maximum Stock

Display the minimum and maximum values in the stock_quantity column.

Exercise 4: Find the Price Range

Calculate the difference between the highest and lowest product prices.

Exercise 5: Find the Lowest Electronics Price

Find the minimum price among products in the Electronics category.

Exercise 6: Find the Highest Accessories Price

Find the maximum price among products in the Accessories category.

Exercise 7: Minimum and Maximum by Category

Display the lowest and highest prices for each category.

Exercise 8: Filter Categories by Maximum Price

Display categories whose maximum product price is greater than 10000.

Exercise 9: Find the Earliest and Latest Dates

Find the earliest and latest dates in the created_at column.

Exercise 10: Retrieve the Highest-Priced Product

Display the product ID, name, and price for every product matching the maximum price.

20. Practice Solutions

Solution 1: Lowest Product Price

SELECT MIN(price) AS lowest_price
FROM products;

Solution 2: Highest Product Price

SELECT MAX(price) AS highest_price
FROM products;

Solution 3: Minimum and Maximum Stock

SELECT
    MIN(stock_quantity) AS minimum_stock,
    MAX(stock_quantity) AS maximum_stock
FROM products;

Solution 4: Price Range

SELECT
    MAX(price) - MIN(price) AS price_range
FROM products;

Solution 5: Lowest Electronics Price

SELECT MIN(price) AS lowest_electronics_price
FROM products
WHERE category = 'Electronics';

Solution 6: Highest Accessories Price

SELECT MAX(price) AS highest_accessories_price
FROM products
WHERE category = 'Accessories';

Solution 7: Minimum and Maximum by Category

SELECT
    category,
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price
FROM products
GROUP BY category;

Solution 8: Categories with Maximum Price Above 10000

SELECT
    category,
    MAX(price) AS highest_price
FROM products
GROUP BY category
HAVING MAX(price) > 10000;

Solution 9: Earliest and Latest Dates

SELECT
    MIN(created_at) AS earliest_date,
    MAX(created_at) AS latest_date
FROM products;

Solution 10: Highest-Priced Product

SELECT product_id, product_name, price
FROM products
WHERE price = (
    SELECT MAX(price)
    FROM products
);

21. Mini Project: Product Price Range Report

Project objective: Create a product analysis report using MySQL's MIN() and MAX() functions.

Project Requirements

  • Find the lowest price across all products.
  • Find the highest price across all products.
  • Calculate the overall price range.
  • Find the minimum and maximum prices for each category.
  • Identify the category with the highest maximum price.
  • Identify products with the lowest and highest prices.
  • Display the earliest and latest product creation dates.
  • Filter categories using a maximum-price threshold.

Project Query 1: Overall Price Summary

SELECT
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price,
    MAX(price) - MIN(price) AS price_range
FROM products;

Project Query 2: Category Price Summary

SELECT
    category,
    MIN(price) AS lowest_price,
    MAX(price) AS highest_price,
    MAX(price) - MIN(price) AS category_price_range
FROM products
GROUP BY category
ORDER BY highest_price DESC;

Project Query 3: Products with Extreme Prices

SELECT product_id, product_name, category, price
FROM products
WHERE price = (SELECT MIN(price) FROM products)
   OR price = (SELECT MAX(price) FROM products);

Project Query 4: Product Date Range

SELECT
    MIN(created_at) AS earliest_product_date,
    MAX(created_at) AS latest_product_date
FROM products;

Expected Learning Outcome

After completing this project, you should be able to analyze product price ranges, identify extreme values, compare categories, and generate useful summaries for business reporting.

22. Interview Questions and Answers

Q1. What is MIN() in MySQL?

Answer: MIN() is an aggregate function that returns the smallest non-NULL value from the selected values.

Q2. What is MAX() in MySQL?

Answer: MAX() is an aggregate function that returns the largest non-NULL value from the selected values.

Q3. Can MIN() and MAX() be used in the same query?

Answer: Yes. Both functions can be included in one SELECT statement to calculate the minimum and maximum values together.

Q4. Do MIN() and MAX() ignore NULL values?

Answer: Yes. Both functions ignore NULL values. If no non-NULL values are available in the selected set, they return NULL.

Q5. Can MIN() and MAX() be used with WHERE?

Answer: Yes. The WHERE clause filters the records before the aggregate functions calculate their results.

Q6. What is the purpose of GROUP BY with MIN() and MAX()?

Answer: GROUP BY divides records into groups and calculates a minimum or maximum value separately for each group.

Q7. What is the difference between WHERE and HAVING?

Answer: WHERE filters individual rows before aggregation, while HAVING filters groups after aggregate calculations.

Q8. Can MIN() and MAX() work with date columns?

Answer: Yes. MIN() can return the earliest date, while MAX() can return the latest date among the selected non-NULL dates.

Q9. Do MIN() and MAX() return the complete row?

Answer: No. They return an aggregate value. To retrieve the full row associated with an extreme value, use a subquery or another suitable query pattern.

Q10. How can you find the product with the highest price?

Answer: Use a subquery to calculate the maximum price and retrieve records matching that value.

SELECT product_id, product_name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);

Q11. What is the difference between MAX() and ORDER BY DESC?

Answer: MAX() returns the maximum value, whereas ORDER BY DESC sorts records from highest to lowest. ORDER BY with LIMIT can retrieve a row, while MAX() returns the aggregate value itself.

Q12. Can MIN() and MAX() be used with text columns?

Answer: Yes. They compare strings according to the applicable character set and collation rules.

23. Quick Revision Checklist

  • MIN(column_name) returns the smallest non-NULL value.
  • MAX(column_name) returns the largest non-NULL value.
  • Use aliases to give aggregate results meaningful names.
  • Use both functions in one query to compare minimum and maximum values.
  • Use WHERE to filter rows before calculating the result.
  • Use GROUP BY to calculate values for individual groups.
  • Use HAVING to filter groups based on aggregate results.
  • Use date columns to find the earliest and latest dates.
  • Use a subquery when you need the complete record associated with a minimum or maximum value.
  • Remember that ties can produce multiple matching records.
  • Understand that NULL values are ignored by MIN() and MAX().
  • Use COALESCE() when a default display value is required.
  • Check column names, filters, and data types when troubleshooting.

24. Conclusion

The MIN() and MAX() functions are essential MySQL aggregate functions for finding the smallest and largest values in a dataset. They can be applied to numeric columns, dates, times, and text values according to the applicable comparison rules.

By combining these functions with WHERE, GROUP BY, HAVING, ORDER BY, and subqueries, you can identify price ranges, compare categories, locate the earliest and latest dates, and retrieve records associated with extreme values.

Practise the examples and exercises in this lesson to develop confidence in using MIN() and MAX() for real-world MySQL database tasks.

Learn More: Explore the MySQL Training Course and register for a course demo to continue learning SQL and database concepts.

whatsapp