SQL Query

How to SQL Query with GROUP BY and Aggregates in SQL

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

How to SQL Query with GROUP BY and Aggregates in SQL

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:

Related Content

From Our Blog

Try it yourself

Practice this query in our interactive SQL sandbox.