my-server
← Wiki

Having (SQL)

A <code>HAVING</code> clause in SQL specifies that an SQL <code>SELECT</code> statement must only return rows where aggregate values meet the specified conditions.

Use

<code>HAVING</code> and <code>WHERE</code> are often confused by beginners, but they serve different purposes. <code>WHERE</code> is taken into account at an earlier stage of a query execution, filtering the rows read from the tables. If a query contains <code>GROUP BY</code>, rows from the tables are grouped and aggregated. After the aggregating operation, <code>HAVING</code> is applied, filtering out the rows that don't match the specified conditions. Therefore, <code>WHERE</code> applies to data read from tables, and <code>HAVING</code> should only apply to aggregated data, which isn't known in the initial stage of a query.

To view the present condition formed by the <code>GROUP BY</code> clause, the <code>HAVING</code> clause is used.

Examples

To return a list of department IDs whose total sales exceeded $1000 on the date of January 1, 2000, along with the sum of their sales on that date:

Referring to the sample tables in the Join example, the following query will return the list of departments which have more than 1 employee:

<code>HAVING</code> is convenient, but not necessary. Code equivalent to the example above, but without using <code>HAVING</code>, might look like:

References

External links