PostgreSQL GROUP BY
The GROUP BY
clause groups rows sharing similar values into summary rows, often used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), MAX()
.
Key Topics
1. Basic Syntax
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
Rows are grouped by department, and the count of employees is returned for each group.
2. Grouping by Multiple Columns
SELECT department, job_title, AVG(salary)
FROM employees
GROUP BY department, job_title;
This groups rows by department and job_title, calculating the average salary for each unique combination.
Best Practices
- Ensure columns in the
SELECT
either appear inGROUP BY
or are used in aggregate functions. - Use
GROUP BY
for meaningful summaries and analytics on large datasets.
Key Takeaways
GROUP BY
clusters rows with identical values in specified columns.- Aggregate functions operate on each group separately.