Home > Database > SQL > The difference between having and where in sql

The difference between having and where in sql

下次还敢
Release: 2024-05-07 05:00:22
Original
1213 people have browsed it

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

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:

<code class="sql">SELECT * FROM users WHERE age > 18;</code>
Copy after login

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:

<code class="sql">SELECT department, COUNT(*) AS employee_count
FROM users
GROUP BY department
HAVING employee_count > 10;</code>
Copy after login

The above query will select departments with more than 10 employees.

Summary

  • 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 is based on the values ​​in the row, while HAVING is based on the aggregated results.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template