ข้ามไปยังเนื้อหาหลัก

PostgreSQL MIN

The `MIN` function in PostgreSQL is a mathematical function used to find the smallest value in a set of values. It is commonly utilized in SQL queries to derive the minimum value from a column in a table.

Usage

The `MIN` function is used when you need to determine the lowest value from a dataset, such as the lowest price, age, or salary. It is often used in conjunction with the `SELECT` statement to retrieve this minimum value.


SELECT MIN(column_name)
FROM table_name
[WHERE condition];

In this syntax, `MIN(column_name)` calculates the smallest value in the specified column from the selected table.

Examples

1. Basic Usage


SELECT MIN(age)
FROM employees;

This query retrieves the minimum age from the `employees` table, identifying the youngest employee.

2. With a WHERE Clause


SELECT MIN(salary)
FROM employees
WHERE department = 'Sales';

Here, the minimum salary is determined only for employees in the 'Sales' department, filtering the data set with a `WHERE` clause.

3. Grouped Results


SELECT department, MIN(salary)
FROM employees
GROUP BY department;

This query retrieves the lowest salary for each department, using `MIN` in conjunction with `GROUP BY` to segment the results.

4. Handling NULL Values


SELECT MIN(bonus)
FROM employees;

In this example, if the `bonus` column contains `NULL` values, the `MIN` function will ignore them and compute the minimum from the non-NULL values only.

Tips and Best Practices

  • Use with GROUP BY. Pair `MIN` with `GROUP BY` to find the smallest values within grouped categories.
  • Combine with WHERE. Apply `WHERE` clauses to filter data before using `MIN` for more precise results.
  • Avoid NULL values. Remember that `MIN` ignores `NULL` values; ensure `NULL` handling aligns with your data needs. Consider using `COALESCE` if you need to treat `NULL` as zero or another default value.
  • Optimize performance. Use indexes on columns involved in `MIN` queries to enhance query performance. Be cautious with large, non-indexed datasets as they may lead to slower queries.
  • Compatible Data Types. `MIN` can be used with numeric, date/time, and string data types. Ensure your data type is compatible for accurate results.