Search⌘ K
AI Features

GROUP BY and HAVING

Explore how to group data by categories using the GROUP BY clause and filter those groups based on aggregated values with HAVING. Learn the difference between WHERE and HAVING filters, write queries that summarize salaries and employee counts by department, and apply these concepts to gain analytical insights from grouped data.

Step 1: Start with a question

In the last lesson, you asked: What is the total salary cost for the whole company?

Now, let’s ask something smarter: “What’s the total salary cost for each department?” That’s where GROUP BY comes in; it summarizes data by group, not as a single total.

Prompt: Write a SQL query that shows each department and its total salary cost from the employees table.

Powered by AI
5 Prompts Remaining
Prompt AI WidgetOur tool is designed to help you to understand concepts and ask any follow up questions. Ask a question to get started.

Step 2: Run and observe

AI will likely produce:

MySQL
SELECT department,
SUM(salary) AS "Total Salary"
FROM employees
GROUP BY department;

 Run it. This is your first grouped ...