In this article, we will dig into the functionality of HAVING to understand its usage and how it differs from the WHERE clause. Through many practical cases, we will fully analyze the practical application of HAVING in SQL.
HAVING clause overview
HAVING
The clause is specifically used to filter aggregated data, i.e. it is used forGROUP BY
The result set of the statement. When executing SQL queries, we usually useWHERE
Filter the original data and then useHAVING
Further filter the grouped data.
1. Basic syntax of HAVING
SELECT List name, Aggregation function FROM Table name GROUP BY List name HAVING condition;
2. The difference between WHERE and HAVING
Comparison items | WHERE clause | HAVING clause |
---|---|---|
Range of action | Act on single-line data | Acted on the aggregated data |
Object of action | Normal column | Aggregation functions (SUM, AVG, COUNT, etc.) |
Use scenarios | Filter raw data | Filter the aggregated data |
Syntax location | existGROUP BY Before |
existGROUP BY after |
Calculate the impact | Affects the dataset size before grouping | Affects the size of the grouped dataset |
In SQL query optimization, it is recommended to use it as much as possible.WHERE
Conduct preliminary screening to reduceGROUP BY
The amount of data to be processed to improve query efficiency.
Application example of HAVING clause
Case 1: Calculate the number of employees in each department and filter departments with more than 3 employees
SELECT department, COUNT(*) AS emp_count FROM employees GROUP BY department HAVING COUNT(*) > 3;
📌Analysis:
GROUP BY department
Grouped by department.COUNT(*)
Calculate the number of employees in each department.HAVING COUNT(*) > 3
Only departments with more than 3 employees are retained.
Case 2: Screening departments with average salary above 5,000
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department HAVING AVG(salary) > 5000;
📌Analysis:
calculate
department
Average salary within the group.HAVING
Filter out departments with average salary less than 5,000.
Case 3: Using WHERE and HAVING at the same time
SELECT department, SUM(salary) AS total_salary FROM employees WHERE salary > 3000 GROUP BY department HAVING SUM(salary) > 20000;
📌Analysis:
WHERE salary > 3000
First screen employees whose salary is higher than 3,000.GROUP BY department
Grouped by department.HAVING SUM(salary) > 20000
Only departments with total salary of more than 20,000 are retained.
Advanced usage of HAVING clauses
1. Use multiple conditions to filter
SELECT department, COUNT(*) AS emp_count, AVG(salary) AS avg_salary FROM employees GROUP BY department HAVING COUNT(*) > 5 AND AVG(salary) > 6000;
📌Analysis:
HAVING
Support logical operatorsAND
、OR
Combining multiple conditions.Filter out departments with less than 5 employees or an average salary of less than 6,000.
2. Use HAVING for range filtering
SELECT department, SUM(salary) AS total_salary FROM employees GROUP BY department HAVING SUM(salary) BETWEEN 10000 AND 50000;
📌Analysis:
HAVING SUM(salary) BETWEEN 10000 AND 50000
Filters: Departments with total salary ranging from 10,000 to 50,000.
3. Sort with ORDER BY
SELECT department, COUNT(*) AS emp_count FROM employees GROUP BY department HAVING COUNT(*) > 3 ORDER BY COUNT(*) DESC;
📌Analysis:
ORDER BY COUNT(*) DESC
Arrange in descending order of employees to quickly view the largest department.
Optimization strategy for HAVING clauses
Try to use WHERE for preliminary screening, reduce data scale, and increase
GROUP BY
Computational efficiency.Avoid complex calculations in HAVING statements, and can store the calculation results in a temporary table to improve query performance.
Use index optimization grouping fields if
GROUP BY
When it comes to fields in large tables, you can consider creating indexes to improve query speed.
Summarize
HAVING
Mainly used to screen the aggregation results, andWHERE
Used for filtering single-line data.When optimizing SQL query, it is recommended to use it first
WHERE
Filter the original data, and thenHAVING
Perform aggregated data filtering.HAVING
Applicable to filtering of aggregation functions such as COUNT, SUM, AVG, MAX, MIN, etc., in conjunction withORDER BY
It can more conveniently analyze data.
Through reasonable useHAVING
, can effectively optimize SQL queries and improve the efficiency of database operations.
This is the end of this article about detailed explanations of the HAVING clauses in SQL that cannot be underestimated. For more related SQL HAVING clauses, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!