Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "HAVING ... GROUP BY" and "GROUP BY ... HAVING"

I have got the table MYTABLE with 2 columns: A and B

I have got the following pieces of the code:

SELECT MYTABLE.A FROM MYTABLE 
    HAVING SUM(MYTABLE.B) > 100
    GROUP BY MYTABLE.A

and

SELECT MYTABLE.A FROM MYTABLE 
    GROUP BY MYTABLE.A
    HAVING SUM(MYTABLE.B) > 100

Is it the same? Is it possible that these 2 codes will return diffrent sets of results?

Thank you in advance

like image 670
user3006279 Avatar asked Dec 09 '13 13:12

user3006279


People also ask

What is the difference between HAVING vs WHERE?

A HAVING clause is like a WHERE clause, but applies only to groups as a whole (that is, to the rows in the result set representing groups), whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause.

Should I use or HAVING?

Well, the main distinction between the two clauses is that HAVING can be applied for subsets of aggregated groups, while in the WHERE block, this is forbidden. In simpler words, after HAVING, we can have a condition with an aggregate function, while WHERE cannot use aggregate functions within its conditions.

What is the difference between GROUP BY and HAVING?

The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The having clause is always used after the group By clause.

Which comes first HAVING or GROUP BY?

The Having Clause should be placed after the Group By clause, but before the Order By clause.


2 Answers

As documented, there is no difference. People are just used to seeing HAVING after GROUP BY.

http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#SQLRF20040

Specify GROUP BY and HAVING after the where_clause and hierarchical_query_clause. If you specify both GROUP BY and HAVING, then they can appear in either order.

http://sqlfiddle.com/#!4/66e33/1

like image 172
David Aldridge Avatar answered Sep 19 '22 00:09

David Aldridge


I originally wrote:

I am not sure your 1st query is valid. As far as I know, HAVING should always come after GROUP BY.

I was corrected by David Aldridge, the Oracle docs state that the order does not matter. Although I don't recommend using HAVING before GROUP for readability reasons (and to prevent confusion with a WHERE clause), it is technically correct. So that makes the answer to your question 'yes, it's the same'.

like image 20
M-Peror Avatar answered Sep 19 '22 00:09

M-Peror