๐ฅ Letโs move to the next topic in the SQL Roadmap:
โ
GROUP BY & Aggregation Functions
๐ง 1. What is GROUP BY?
GROUP BY is used to group rows with same values
๐ It helps you summarize data
๐ก Example Table: employees
name department salary
Amit IT 60000
Neha HR 40000
Ravi IT 70000
Sara HR 50000
๐ Without GROUP BY
SELECT AVG(salary) FROM employees;
โ Gives overall average
๐ With GROUP BY
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
โ Gives average salary per department
โก 2. Aggregation Functions
These functions perform calculations on data
๐น COUNT() โ number of rows
SELECT COUNT() FROM employees;
๐น SUM() โ total
SELECT SUM(salary) FROM employees;
๐น AVG() โ average
SELECT AVG(salary) FROM employees;
๐น MIN() โ smallest value
SELECT MIN(salary) FROM employees;
๐น MAX() โ largest value
SELECT MAX(salary) FROM employees;
๐ฏ 3. GROUP BY + Aggregation
๐ Count employees in each department
SELECT department, COUNT()
FROM employees
GROUP BY department;
๐ Total salary per department
SELECT department, SUM(salary)
FROM employees
GROUP BY department;
๐ Highest salary per department
SELECT department, MAX(salary)
FROM employees
GROUP BY department;
๐จ 4. Important Rule (Interview Favorite)
๐ Every column in SELECT must be:
- Either inside GROUP BY
- Or used with aggregation function
โ Wrong:
SELECT name, AVG(salary) FROM employees;
โ
Correct:
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
๐ฏ 5. Practice Tasks
1. Count total employees
2. Find total salary of all employees
3. Find average salary per department
4. Find maximum salary in each department
5. Count employees in each department
โ
Practice Task Solution
โ
1. Count total employees
SELECT COUNT() FROM employees;
โ
2. Find total salary of all employees
SELECT SUM(salary) FROM employees;
โ
3. Find average salary per department
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
โ
4. Find maximum salary in each department
SELECT department, MAX(salary)
FROM employees
GROUP BY department;
โ
5. Count employees in each department
SELECT department, COUNT()
FROM employees
GROUP BY department;
โก Mini Challenge ๐ฅ
๐ Find department with highest average salary
โก Mini Challenge Solution ๐ฅ
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC
LIMIT 1;
โก Double Tap โค๏ธ For More
Post #2725
6.72K
- โค 25