4

I am new to SQL, have read many sources and it just tells me to use HAVING instead. Is there a more in-debth solution or reason to the alternate?

Also, is it not an an error to use an aggregate function in a HAVING clause? How is this different than using a one in a where clause?

tshepang
  • 12,111
  • 21
  • 91
  • 136
user2948897
  • 169
  • 3
  • 9
  • 2
    Can you provide an example of what you want to achieve using SQL? – Andrei Nicusan Nov 15 '13 at 22:36
  • The following should help clarify: http://stackoverflow.com/questions/9253244/sql-having-vs-where – Seymour Nov 15 '13 at 22:42
  • 1
    Where is a filter on a data column, having is a filter on an aggergate. – Twelfth Nov 15 '13 at 22:43
  • This more of general question, I found some relavence here: http://stackoverflow.com/questions/12600819/getting-errors-when-using-having-clause-with-aggregate-functions. If this post gets makred down then can i delete it? – user2948897 Nov 15 '13 at 22:43

1 Answers1

5

Conditions applied in the WHERE clause refer to the values in the rows of the table(s) prior to the application of the GROUP BY clause, and conditions in the HAVING clause apply to the result set post-GROUP-BY.

Hence you can reference GROUP BY columns or aggregations in the HAVING clause, but not columns for which the values are not guaranteed to be unique post-GROUP BY. In the WHERE clause, the result set of the GROUP BY is not available, so any row vaue can be referenced but no aggregation results can be.

David Aldridge
  • 51,479
  • 8
  • 68
  • 96