SQL GROUP BY

Basic GROUP BY

This counts how many employees are in each department.

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

Using Aggregate Functions

This calculates the average price per product category.

SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category;

GROUP BY Multiple Columns

Groups data by both department and role.

SELECT department, role, COUNT(*) AS count
FROM employees
GROUP BY department, role;

GROUP BY with ORDER BY

Sorts departments by employee count in descending order.

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
ORDER BY total DESC;

Filtering with HAVING

Only shows departments with more than 10 employees.

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING total > 10;

Best Practices

  • Use HAVING for filtering aggregated results
  • Make sure non-aggregated columns in SELECT appear in GROUP BY
  • Use column aliases for cleaner and clearer queries

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic