Aggregation functions help summarize large datasets. Combine them with GROUP BY to analyze grouped data.
1๏ธโฃ COUNT()
Returns the number of records.
SELECT COUNT(*) FROM employees;
2๏ธโฃ SUM()
Adds up values in a column.
SELECT dept_id, SUM(salary)
FROM employees
GROUP BY dept_id;
3๏ธโฃ AVG()
Returns the average of values.
SELECT AVG(salary) FROM employees;
4๏ธโฃ MAX() / MIN()
Returns the highest/lowest value.
SELECT MAX(salary), MIN(salary) FROM employees;
5๏ธโฃ GROUP BY
Groups rows that have the same values in specified columns.
SELECT dept_id, COUNT(*)
FROM employees
GROUP BY dept_id;
6๏ธโฃ HAVING
Filters groups after aggregation (unlike WHERE which filters rows).
SELECT dept_id, AVG(salary)
FROM employees
GROUP BY dept_id
HAVING AVG(salary) > 50000;
โโโโโโโโ
Real-World Interview Questions + Answers
Q1: Whatโs the difference between WHERE and HAVING?
A: WHERE filters rows before grouping. HAVING filters after aggregation.
Q2: Can you use aggregate functions without GROUP BY?
A: Yes. Without GROUP BY, the function applies to the entire table.
Q3: How do you find departments with more than 5 employees?
SELECT dept_id, COUNT(*)
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;
Q4: Can you group by multiple columns?
A: Yes.
GROUP BY dept_id, job_title
Q5: How do you calculate total and average salary per department?
SELECT dept_id, SUM(salary), AVG(salary)
FROM employees
GROUP BY dept_id;
๐ฌ Tap โค๏ธ for more!