Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oracle sql select syntax with GROUP BY and HAVING clause

I been going thru some of the sql syntax to study for the oracle sql exam, I found something rather confusing

based on the official references, the select syntax is as follow :

SELECT
    [ hint ]
    [ { { DISTINCT | UNIQUE } | ALL } ]
   select_list
     FROM { table_reference | join_clause | ( join_clause ) }
            [ , { table_reference | join_clause | (join_clause) } ] ...
     [ where_clause ]
     [ hierarchical_query_clause ]
     [ group_by_clause ]
     [ HAVING condition ]
     [ model_clause ]

based on this you cannot have the HAVING clause before the GROUP BY clause . However if i were to execute the following sql in the test server :

select 
   department_id , count (*)      
from 
    employees 
having 
    count(*) > 6 
group by 
    department_id ; 

it does not produce a syntax error , can some one help explain this ? I don't like to think that the reference docs is wrong , but if so I need some confirmation.

like image 629
user2081775 Avatar asked Nov 25 '13 09:11

user2081775


People also ask

Can we use GROUP BY and HAVING clause together?

You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function.

Can we use SELECT * with GROUP BY?

You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row.

Can we use SELECT in HAVING clause?

Having clause is only used with the SELECT clause. The expression in the syntax can only have constants. In the query, ORDER BY is to be placed after the HAVING clause, if any. HAVING Clause implements in column operation.

Can you use combination of GROUP BY clause HAVING clause and WHERE clause?

Yes, an SQL query can contain a WHERE and HAVING clause. You will use these together when you want to extract (or filter) rows for a group of data using a WHERE clause and apply a condition on the aggregate using the HAVING clause.


1 Answers

As stated here:

Use the HAVING clause to restrict the groups of returned rows to those groups for which the specified condition is TRUE. If you omit this clause, then the database returns summary rows for all groups.

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.

like image 51
Armunin Avatar answered Oct 12 '22 11:10

Armunin