Sitemap
Data SQL

Data SQL

Member-only story

SQL: The HAVING Clause

3 min readDec 12, 2024

--

Hello Folks,

Press enter or click to view image in full size
generated by author in leonardo.ai

1. Basic HAVING Clause

sql
Copy code
-- Get departments where the total salary exceeds 100,000
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
HAVING SUM(salary) > 100000;

2. HAVING with Multiple Conditions

sql
Copy code
-- Get departments where the total salary exceeds 100,000 and the average salary exceeds 50,000
SELECT department_id, SUM(salary) AS total_salary, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING SUM(salary) > 100000 AND AVG(salary) > 50000;

3. HAVING with Aliases

sql
Copy code
-- Use an alias for aggregated data in the HAVING clause
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
HAVING total_salary > 100000;

4. HAVING with Conditional Aggregation

sql
Copy code
-- Get departments where more than 5 employees earn above 60,000
SELECT department_id, COUNT(CASE WHEN salary > 60000 THEN 1 END) AS high_salary_count
FROM…

--

--