Min And Max in PostgreSql
MIN() and MAX() in PostgreSQL
The MIN() and MAX() functions in PostgreSQL return the smallest and largest values in a column, respectively.
1. Using MIN() to Find the Smallest Value
SELECT MIN(salary) FROM employees;
✅ Returns the lowest salary in the employees table.
2. Using MAX() to Find the Largest Value
SELECT MAX(salary) FROM employees;
✅ Returns the highest salary in the employees table.
3. Using MIN() and MAX() with a WHERE Condition
SELECT MIN(salary) FROM employees WHERE department = 'IT';
✅ Returns the lowest salary in the IT department.
SELECT MAX(salary) FROM employees WHERE department = 'Finance';
✅ Returns the highest salary in the Finance department.
4. Using MIN() and MAX() with GROUP BY
SELECT department, MIN(salary), MAX(salary) FROM employees GROUP BY department;
✅ Returns the lowest and highest salary for each department.
5. Using MIN() and MAX() with Dates
SELECT MIN(order_date) AS earliest_order, MAX(order_date) AS latest_order FROM orders;
✅ Returns the earliest and latest order dates.
6. Using MIN() and MAX() with HAVING
SELECT department, MAX(salary) FROM employees GROUP BY department HAVING MAX(salary) > 50000;
✅ Returns departments where the highest salary is greater than 50,000.