← 30 Days of SQL
Day 5 / 30Aggregations

GROUP BY Deep Dive

GROUP BY is the most used clause in analytical SQL. If you understand this well, half your interview is done.

1
Easy

What is the rule for using GROUP BY?

SQL Answer
-- Every column in SELECT that is NOT inside an aggregate
-- function MUST appear in GROUP BY.

-- CORRECT:
SELECT department, COUNT(*)
FROM employees
GROUP BY department;

-- WRONG (will error):
SELECT department, name, COUNT(*)
FROM employees
GROUP BY department;
💡

"name" is not in GROUP BY and not in an aggregate — this errors in standard SQL (MySQL in non-strict mode may allow it but return arbitrary values).

2
Easy

Find the number of employees and total salary per department, ordered by total salary.

SQL Answer
SELECT department,
       COUNT(*) AS headcount,
       SUM(salary) AS total_salary
FROM employees
GROUP BY department
ORDER BY total_salary DESC;
💡

Classic analytical query. This exact pattern appears in business reports, dashboards, and MIS sheets.

3
Medium

Group employees by department AND job_title, count each combination.

SQL Answer
SELECT department,
       job_title,
       COUNT(*) AS count
FROM employees
GROUP BY department, job_title
ORDER BY department, count DESC;
💡

You can GROUP BY multiple columns. The result is one row per unique combination of all grouped columns.

4
Medium

Find departments where total salary bill exceeds 500000 AND headcount is more than 5.

SQL Answer
SELECT department,
       COUNT(*) AS headcount,
       SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 500000
   AND COUNT(*) > 5;
💡

Multiple conditions in HAVING use AND/OR just like WHERE. This type of query is used in HR and finance reporting.

5
Medium

What is the difference between COUNT(*), COUNT(1) and COUNT(column)?

SQL Answer
-- COUNT(*): counts all rows including NULLs
SELECT COUNT(*) FROM employees;

-- COUNT(1): same as COUNT(*), just a constant
SELECT COUNT(1) FROM employees;

-- COUNT(column): counts non-NULL values only
SELECT COUNT(manager_id) FROM employees;
💡

COUNT(*) and COUNT(1) give the same result and similar performance. COUNT(column) is different — it skips NULLs. Common interview trick question.

6
Medium

Show the year-wise count of employees hired.

SQL Answer
SELECT YEAR(hire_date) AS hire_year,
       COUNT(*) AS hired
FROM employees
GROUP BY YEAR(hire_date)
ORDER BY hire_year;
💡

YEAR() extracts the year from a date. In PostgreSQL use EXTRACT(YEAR FROM hire_date). This is a common trend analysis query.

EVIKA ACADEMY · SQL FOR DATA ANALYTICS

Want to master SQL with live practice?

Join our SQL for Data Analytics course — live classes in Noida and online across India.

Book Free Demo Class →
← PREVIOUSDay 4: Aggregate Functions — COUNT, SUM, AVG, MAX, MINNEXT →Day 6: INNER JOIN
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY