PostgreSQL MIN and MAX
MIN() and MAX() are aggregate functions in PostgreSQL that return the smallest and largest values in a column, respectively.
Key Topics
1. Basic Syntax
To get the overall minimum or maximum value:
SELECT MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees;
2. Using GROUP BY
Apply MIN() or MAX() per group of rows:
SELECT department,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees
GROUP BY department;
Each department is listed along with its minimum and maximum salary.
Best Practices
- Index columns used with
MIN()orMAX()for performance, especially if you use them frequently. - Use
GROUP BYto get min/max values segmented by categories.
Key Takeaways
MIN()andMAX()scan columns for the smallest and largest values.- They can be used in conjunction with
GROUP BYto aggregate data by groups.