In SQL, HAVING and WHERE are both used to filter data, but their difference is that WHERE filters individual rows, while HAVING filters the results of aggregate functions. WHERE is used after the FROM clause and HAVING is used after the GROUP BY clause. WHERE filters based on the values in the row, while HAVING filters based on the aggregated results.
The difference between HAVING and WHERE in SQL
In SQL, HAVING and WHERE are both used to filter data keywords, but there are obvious differences in their uses:
WHERE filter rows
The WHERE clause is used to filter individual rows in the table. It is used in the SELECT statement, after the FROM clause. WHERE considers only the values in a single row and keeps or deletes them based on specified conditions.
For example:
SELECT * FROM users WHERE age > 18;
The above query will select all users older than 18.
HAVING filter group
The HAVING clause is used to filter the results of aggregate functions such as SUM, COUNT, AVG. It is used after GROUP BY clause to filter groups based on aggregate results.
For example:
SELECT department, COUNT(*) AS employee_count FROM users GROUP BY department HAVING employee_count > 10;
The above query will select departments with more than 10 employees.
Summary
The above is the detailed content of The difference between having and where in sql. For more information, please follow other related articles on the PHP Chinese website!