Having clause and Where clause
- Both are used for filtering of records based on filtered criteria.
- Having is used in a ‘group by’ clause in a query.
- ‘Where clause’ has preference over ‘having clause’ in a query.
Having clause and Where clause
Having Clause: This clause is used for specifying a search condition for a group or an aggregate. It can only be used with a SELECT statement. It’s often used with GROUP BY clause without which its synonymous to a WHERE clause.
E.g.: SELECT Id, Name, Age FROM Customers
GROUP BY Age
HAVING Age>10
ORDER BYAge;
Where Clause: This clause is used to narrow down the dataset being dealt with following a condition.
SELECT Id, Name, Age FROM Customers
WHERE Age>10
It is strongly recommended to use a Where clause with every Select Statement to avoid a table scan and reduce the number of rows to be returned. It can be used with Select, Update, Delete etc statements.