Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SQL Having Clause

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I was just working on SQL Having clause. I wrote the following query using having clause:


Then I wrote the following query using where condition and not using the having clause:


Both are basically giving the same result. I am wondering now the usage of having clause because if it's usage is to filter the records that a GROUP BY returns, then it can be done using the where condition too right?

Thanks.
 
Shailesh Chandra
Ranch Hand
Posts: 1082
Java Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

A HAVING clause restricts the results of a 'GROUP BY'.
The HAVING clause is applied to each group,A WHERE clause is applied to a select list.
Having clause can also filter your data on aggregate functions like, sum, avg, min etc.



Just try filter your query on aggregate function, then you will come to know about difference. for example try to filter on SUM(PRICE) >0

Shailesh
[ November 11, 2008: Message edited by: Shailesh Chandra ]
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shailesh Chandra:



Just try filter your query on aggregate function, then you will come to know about difference. for example try to filter on SUM(PRICE) >0

Shailesh

[ November 11, 2008: Message edited by: Shailesh Chandra ]


Yes Shailesh, where clause does not seem to work on aggregate functions. Where as Having clause works perfectly fine.

Thanks.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic