Home > Database > Mysql Tutorial > Understand the difference between where and having in sql statements

Understand the difference between where and having in sql statements

怪我咯
Release: 2017-03-31 10:07:14
Original
2213 people have browsed it

HAVING first groups and then filters the records, WHERE first filters the records before aggregating. That is to say, it acts before the GROUP BY clause and the HAVING clause; and the HAVING clause filters the group records after aggregation.
The objects used are different. The WHERE clause acts on tables and views, and the HAVING clause acts on groups. WHERE selects the input rows before grouping and aggregation calculations (therefore, it controls which rows enter the aggregation calculation), while HAVING selects the grouped rows after grouping and aggregation. Therefore, the WHERE clause cannot contain an aggregate function ; because it makes no sense to try to use an aggregate function to determine which rows are input to the aggregation operation. In contrast, the HAVING clause always contains aggregate functions. (Strictly speaking, you could write the HAVING clause without using aggregation, but doing so would be a waste of time. The same condition could be used more efficiently in the WHERE stage.) For example:
select * from tablename where id > 1; and
select * from tablename having id > 1
There is no difference between the query results. It is not recommended to use having
To summarize in two sentences:
The WHERE statement comes before the GROUPBY statement; SQL will calculate the WHERE statement before grouping.
HAVING statement follows the GROUPBY statement; SQL will calculate the HAVING statement after grouping.

The above is the detailed content of Understand the difference between where and having in sql statements. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template