π½ SQL MIN() Function β How to Find the Smallest Value in a Column
The SQL MIN() function is one of the most used aggregate functions in SQL. It helps you retrieve the minimum (smallest) value in a specific column, whether it’s numeric, text, or date-based.
In this tutorial, youβll learn:
- β
What the
MIN()function does - π§ Syntax and usage
- π Real-life examples
- β οΈ Tips to avoid common mistakes
β What is SQL MIN()?
The MIN() function returns the smallest value from a group of rows in a column. Itβs perfect for identifying the lowest price, earliest date, or alphabetically first text.
π§ Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
column_name: The column you want to find the minimum value in.table_name: The table containing the data.WHERE: Optional condition to filter records.
π SQL MIN() Function Examples
π§ͺ Example 1: Find the Lowest Salary
SELECT MIN(salary) AS lowest_salary
FROM employees;
π° This returns the minimum salary in the employees table.
π§ͺ Example 2: Get the Earliest Hire Date
SELECT MIN(hire_date) AS first_hired
FROM employees;
π Use this to find when the first employee joined.
π§ͺ Example 3: Find Minimum Score per Student
SELECT student_id, MIN(score) AS lowest_score
FROM test_results
GROUP BY student_id;
π Useful in analytics to find the worst performance per student.
π§ͺ Example 4: Alphabetically First Name
SELECT MIN(last_name) AS first_name
FROM customers;
π€ Returns the name that comes first alphabetically.
π§ MIN() with GROUP BY
Use GROUP BY to apply MIN() to each group in your dataset:
SELECT department_id, MIN(salary) AS min_salary
FROM employees
GROUP BY department_id;
This returns the lowest salary in each department.
π§ Pro Tip: Use MIN() in Subqueries
SELECT *
FROM employees
WHERE salary = (
SELECT MIN(salary)
FROM employees
);
βοΈ This retrieves all employees earning the minimum salary.
β οΈ Common SQL MIN() Mistakes
| β Mistake | β Fix |
|---|---|
Using MIN() with multiple columns without GROUP BY | Use GROUP BY with all non-aggregated columns |
| Expecting multiple values | MIN() returns a single value per group |
| Including NULLs | MIN() automatically ignores NULLs |
π SQL MIN() Function Use Cases
- π’ HR: Find the lowest salary
- π Retail: Get the cheapest product
- π Events: Identify the earliest transaction
- π Exams: Report lowest marks per student
π Summary
| Feature | Description |
|---|---|
| Function | MIN() |
| Returns | The smallest value |
| Works with | Numbers, text, dates |
| Ignores NULLs | β Yes |
| Use with GROUP BY | β Yes |