GROUP BY Deep Dive
GROUP BY is the most used clause in analytical SQL. If you understand this well, half your interview is done.
What is the rule for using GROUP BY?
-- 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).
Find the number of employees and total salary per department, ordered by total salary.
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.
Group employees by department AND job_title, count each combination.
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.
Find departments where total salary bill exceeds 500000 AND headcount is more than 5.
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.
What is the difference between COUNT(*), COUNT(1) and COUNT(column)?
-- 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.
Show the year-wise count of employees hired.
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 →