The HAVING clause restricts the rows returned by a query. It sets conditions for the GROUP BY clause similar to the way in which WHERE sets conditions for the SELECT clause.
The HAVING clause search conditions are identical to WHERE search conditions except that WHERE search conditions cannot include aggregates. For example, the following usage is allowed:
HAVING AVG( UnitPrice ) > 20 |
The following usage is not allowed:
WHERE AVG( UnitPrice ) > 20 |
The following statement is an example of simple use of the HAVING clause with an aggregate function.
To list those products available in more than one size or color, you need a query to group the rows in the Products table by name, but eliminate the groups that include only one distinct product:
SELECT Name FROM Products GROUP BY Name HAVING COUNT( * ) > 1; |
Name |
---|
Tee Shirt |
Baseball Cap |
Visor |
Sweatshirt |
For information about when you can use aggregate functions in HAVING clauses, see Where you can use aggregate functions.
The HAVING clause can also be used without aggregates.
The following query groups the products, and then restricts the result set to only those groups for which the name starts with B.
SELECT Name FROM Products GROUP BY Name HAVING Name LIKE 'B%'; |
Name |
---|
Baseball Cap |
More than one condition can be included in the HAVING clause. They are combined with the AND, OR, or NOT operators, as in the following example.
To list those products available in more than one size or color, for which one version costs more than $10, you need a query to group the rows in the Products table by name, but eliminate the groups that include only one distinct product, and eliminate those groups for which the maximum unit price is under $10.
SELECT Name FROM Products GROUP BY Name HAVING COUNT( * ) > 1 AND MAX( UnitPrice ) > 10; |
Name |
---|
Tee Shirt |
Sweatshirt |
Send feedback about this page via email or DocCommentXchange | Copyright © 2008, iAnywhere Solutions, Inc. - SQL Anywhere 11.0.0 |