๐ SQL MIN and MAX โ Find Minimum and Maximum Values
๐งฒ Introduction โ What are MIN and MAX in SQL?
The MIN()
and MAX()
functions in SQL are used to retrieve the lowest and highest values in a column. These are powerful tools when analyzing data trends, identifying outliers, or setting boundaries for queries and reports.
๐ฏ In this guide, youโll learn how to:
- Use
MIN()
andMAX()
on numeric, date, and text columns - Combine with
GROUP BY
andHAVING
- Handle
NULL
values appropriately
โ 1. Basic Syntax for MIN and MAX
SELECT MIN(column_name), MAX(column_name)
FROM table_name;
โ Retrieves the smallest and largest values from the specified column.
๐ข 2. Example โ Salary Range
SELECT MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employees;
โ Shows the salary boundaries in the employees table.
๐ 3. MIN and MAX with Dates
SELECT MIN(hire_date) AS first_hired,
MAX(hire_date) AS most_recent_hired
FROM employees;
โ Identifies earliest and latest hiring dates.
๐ 4. Use with GROUP BY
SELECT department,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees
GROUP BY department;
โ Retrieves min and max salary per department.
๐งฎ 5. Combine with HAVING
SELECT department, MAX(salary) AS top_salary
FROM employees
GROUP BY department
HAVING MAX(salary) > 100000;
โ Filters groups where top salaries exceed 100,000.
๐ 6. MIN/MAX with Text Columns
SELECT MIN(last_name), MAX(last_name)
FROM employees;
โ Alphabetically finds the first and last names in the dataset.
๐ Best Practices
โ Do This | โ Avoid This |
---|---|
Alias results for clarity | Leaving raw column names |
Pair with GROUP BY for segmentation | Using without context or sorting |
Handle NULLs properly (they’re ignored) | Assuming NULL = 0 or ” |
๐ Summary โ Recap & Next Steps
The MIN()
and MAX()
functions are essential for identifying data boundaries, including numeric ranges, date windows, and alphabetical limits.
๐ Key Takeaways:
- Use
MIN()
to find the lowest value;MAX()
for the highest - Works with numbers, dates, and strings
- Combine with
GROUP BY
andHAVING
for grouped insights - Ignores NULLs unless handled using
COALESCE()
โ๏ธ Real-World Relevance:
Used in pricing analytics, trend reports, HR records, audit trails, and data integrity checks.
โก๏ธ Next: Explore COUNT()
and conditional aggregation techniques.
โ FAQ โ SQL MIN and MAX Functions
โ Do MIN and MAX include NULL values?
โ No. They ignore NULLs by default.
โ Can MIN and MAX be used on text columns?
โ Yes. They return the alphabetically first and last values.
โ How do I get min/max per category?
โ
Use GROUP BY
and select the column you want to group by.
โ Can I use them in subqueries?
โ Absolutely. Example:
SELECT name FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
โ Are MIN and MAX efficient?
โ Yes, especially when used on indexed columns.
Share Now :