Differences between database statements where, on, and having

the difference between where on having

Where on having is a query condition, which can filter out qualified data. The main difference between the three is that the timing of the restriction is different.

Execution sequence: ON------>WHERE------>HAVING

where和having

①The filtering unit of where is the data row, and the data rows that meet the conditions will be filtered out. whereThe clause filters the data rows beforeGROUP BY the grouping and aggregation functions ; so the aggregation function cannot be used in where. where works before having.

②having cannot be used alone, it can only appear after the GROUP BY clause, and havingthe clause filters the data rows afterGROUP BY the grouping and aggregation functions . Therefore, aggregate functions can be used in having to filter groups.

③Conditions that can appear in having: aggregate functions and the column names of the data that can be obtained after grouping (that is, only grouping fields or aggregate functions can be used.)

From a performance point of view, HAVINGif a grouping field is used as a filter condition in a clause, it should be replaced with WHEREa clause; because WHEREunnecessary data can be filtered out before performing grouping operations and calculating aggregate functions, the performance will be better. The condition of having is usually an aggregate function.

The summary is: where is used to filter the data before the grouping and aggregation functions, and having is used to filter the results after the calculation results of the aggregation functions are calculated, and the groupings that meet the conditions will be returned.

on sum where

①on is the condition used to limit the connection between tables and tables.

②In the left outer join, ON will return all the records in the left table; in the right outer join, ON will return all the records in the right table. If it is an inner connection, where and on have the same effect

③The data rows that do not meet the on condition will not appear in the temporary table (filter data), and where will filter out the data rows that meet the where condition according to the results obtained after the on condition.

In general, ON filters the data row records according to the restriction conditions, and then generates a temporary table; while WHERE filters the results from the temporary table according to the restriction conditions after the temporary table is produced.

Because the ON constraint occurs earlier, the data set of the temporary table is smaller, so the performance of ON is better than WHERE.

Guess you like

Origin blog.csdn.net/m0_48895748/article/details/126708856