WHERE versus HAVING

Previous Next

Use a WHERE clause instead of a HAVING clause if possible.

Background

If you can, avoid HAVING clauses. With HAVING, all records are fetched and sorted before a selection is made of the records that are really required.

Example:

Rewrite an SQL statement like the following:

For all persons who have made reservations except the person with id 1, select the total price the person has paid.

SELECT    made_by

,         SUM(price)

FROM      reservation r

GROUP BY  made_by

HAVING    made_by != 1

 

to:

SELECT    made_by

,         SUM(price)

FROM      reservation r

WHERE     made_by != 1

GROUP BY  made_by