2

Can someone tell me the difference between the HAVING and WHERE clause in the below context when i am getting the same results using both the statements

SELECT Table1.DEPT, Sum(Table1.SALARY) AS Comp
FROM Table1
GROUP BY Table1.DEPT
HAVING DEPT="HR"

This goes with WHERE clause.

SELECT Table1.DEPT, Sum(Table1.SALARY) AS Comp
FROM Table1
WHERE DEPT="HR"
GROUP BY Table1.DEPT
santhosha
  • 351
  • 2
  • 8
  • 20

1 Answers1

2

Functionally, the two are equivalent.

The WHERE clause is saying:

Filter the data and then aggregate the results.

The HAVING clause is saying:

Aggregate the data and then filter the results.

Both return the same result, because the filtering is on the columns used for aggregation. Usually, HAVING uses aggregation functions; these are not allowed in the WHERE.

In general, the WHERE clause is going to be faster, because less data is being aggregated. You should use WHERE in this case.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786