1. GROUP BY
GROUP BY
is used to group rows that have the same values in one or more columns. It’s often used with aggregate functions like COUNT()
, SUM()
, AVG()
, MAX()
, MIN()
.
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
👉 This query returns the number of employees in each department.
2. HAVING
HAVING
is like a WHERE
clause, but it’s applied after grouping. You use it to filter groups.
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
👉 This returns only departments that have more than 5 employees.
(WHERE
cannot be used here because COUNT()
is an aggregate function.)
3. ROLLUP
ROLLUP
is used with GROUP BY
to generate subtotals and grand totals automatically.
Example:
SELECT department, job_title, SUM(salary) AS total_salary
FROM employees
GROUP BY ROLLUP (department, job_title);
👉 This query will produce:
- Total salary for each
(department, job_title)
pair - Total salary for each
department
(subtotal) - Total salary for all employees (grand total)
🔹 Example Data (Employees Table)
employee_id | department | job_title | salary |
---|---|---|---|
1 | HR | Manager | 5000 |
2 | HR | Recruiter | 3000 |
3 | IT | Developer | 6000 |
4 | IT | Developer | 6500 |
5 | IT | Analyst | 5500 |
🔹 Sample ROLLUP
Output
For the query above:
department | job_title | total_salary |
---|---|---|
HR | Manager | 5000 |
HR | Recruiter | 3000 |
HR | NULL | 8000 (subtotal for HR) |
IT | Developer | 12500 |
IT | Analyst | 5500 |
IT | NULL | 18000 (subtotal for IT) |
NULL | NULL | 26000 (grand total) |
✅ Summary:
GROUP BY
→ groups rows.HAVING
→ filters groups (after aggregation).ROLLUP
→ adds subtotals & grand totals.