SQL MIN and MAX Functions

Here is a clear and practical guide to the SQL MIN() and MAX() functions, including examples, behavior notes, and best practices.


✅ What MIN() and MAX() Do

  • MIN() returns the smallest value in a column

  • MAX() returns the largest value in a column

Both work on numeric, text, and date types.


✅ Basic Syntax

SELECT MIN(column_name) AS smallest_value,
MAX(column_name) AS largest_value
FROM table_name;

📌 Examples

1. Find the lowest and highest product price

SELECT MIN(price) AS min_price,
MAX(price) AS max_price
FROM products;

2. Find oldest and newest date

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

3. MIN/MAX on text (lexicographical order)

Alphabetically first/last value:

SELECT MIN(name) AS first_name,
MAX(name) AS last_name
FROM customers;

🔥 Using MIN/MAX with GROUP BY

Apply MIN/MAX per category or group:

SELECT department,
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employees
GROUP BY department;

🧠 Important Behavior Notes

NULL values are ignored by both MIN() and MAX()
✔ MIN/MAX work on text, numbers, dates
✔ When mixing with other columns, you must use GROUP BY


🔐 Common Real-World Use Case

Find the earliest and latest login per user:

SELECT user_id,
MIN(login_time) AS first_login,
MAX(login_time) AS last_login
FROM logins
GROUP BY user_id;

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *