SQL Query

PostgreSQL: SQL Query with GROUP BY and Aggregates

PostgreSQL guide: Summarize data using GROUP BY with SUM, AVG, COUNT, MIN, MAX.

This guide is specifically for PostgreSQL syntax.

SQL Query with GROUP BY and Aggregates

Summarize data using GROUP BY with SUM, AVG, COUNT, MIN, MAX.

Quick Answer

SELECT department, SUM(salary), AVG(salary) FROM employees GROUP BY department;

Explanation

GROUP BY groups rows by specified columns. Aggregate functions (SUM, AVG, COUNT, MIN, MAX) calculate values for each group.

Query Variants

Sum

SELECT department, SUM(salary) as total_salary FROM employees GROUP BY department;

Average

SELECT department, ROUND(AVG(salary), 2) as avg_salary FROM employees GROUP BY department;

Multiple

SELECT department, COUNT(*) as emp_count, SUM(salary) as total, AVG(salary) as avg, MAX(salary) as highest, MIN(salary) as lowest FROM employees GROUP BY department;

Pro Tips

  • All non-aggregated columns must be in GROUP BY
  • Use HAVING to filter groups
  • ROUND() for cleaner decimal output

Related SQL Queries

Continue learning with more SQL query examples:


PostgreSQL-Specific Notes

This page covers PostgreSQL syntax. Other databases may have different syntax for similar operations.

Related Content

From Our Blog

Try it yourself

Practice this query in our interactive SQL sandbox.