This Oracle tutorial explains how to use the Oracle HAVING clause with syntax and examples.
The Oracle HAVING clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE.
The syntax for the HAVING clause in Oracle/PLSQL is:
The expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY clause.
It can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.
This is the column or expression that the aggregate_function will be used against.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. These are the conditions for the records to be selected.
This is a further condition applied only to the aggregated results to restrict the groups of returned rows. Only those groups whose condition evaluates to TRUE will be included in the result set.
Let's look at an Oracle HAVING clause example that uses the SUM function.
You could also use the SUM function to return the name of the department and the total sales (in the associated department). The Oracle HAVING clause will filter the results so that only departments with sales greater than $25,000 will be returned.
Let's look at how we could use the HAVING clause with the COUNT function.
You could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make under $49,500 / year. The Oracle HAVING clause will filter the results so that only departments with more than 10 employees will be returned.
Let's next look at how we could use the HAVING clause with the MIN function.
You could also use the MIN function to return the name of each department and the minimum salary in the department. The Oracle HAVING clause will return only those departments where the minimum salary is less than $42,000.
For example, you could also use the MAX function to return the name of each department and the maximum salary in the department. The Oracle HAVING clause will return only those departments whose maximum salary is greater than $45,000.