The HAVING Clause

In its most common use, the HAVING clause is a WHERE clause for groups. Just as WHERE limits rows, HAVING limits groups. Most of the time, you use HAVING with GROUP BY.


SELECT select_list
FROM table_list
[WHERE conditions]
[GROUP BY group_by_list]
[HAVING conditions]
[ORDER BY order_by_list]

When there are aggregates in the SELECT list of a query, WHERE clause conditions apply to the rows that are used to calculate the aggregates, while HAVING conditions apply to the final results after you've calculated the aggregates and set up the groups. One way to keep this difference in mind is to recall the order of the clauses in the SELECT statement. Remember that WHERE comes after FROM, and HAVING comes after GROUP BY. An example at the end of this section explores WHERE and HAVING interactions in some detail.

Here are the steps when a query includes WHERE, GROUP BY, aggregates, and HAVING:

1.
The WHERE clause acts first to find the rows you want.

2.
The GROUP BY clause divides these rows into groups.

3.
After the groups are formed, SQL calculates the aggregate values (SUM, MIN, etc.) for each group.

4.
HAVING checks the resulting group rows to see which ones qualify for the final display.

Any rows you can remove with WHERE, rather than HAVING, make your query more efficient because you have fewer rows to group and fewer to aggregate. Use HAVING to qualify groups, not rows.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.54.108