| Subqyery with group by / case when / having [message #645463] |
Mon, 07 December 2015 04:58  |
 |
Kruemel
Messages: 2 Registered: December 2015
|
Junior Member |
|
|
Hello everybody,
I am studying for the Oracle SQL Export exam (1Z0-047) with the following book:
OCA Oracle Database SQL Certified Expert Exam Guide (Exam 1Z0-047) (Oracle Press).
In the chapter on subqueries it is stated that scalar subqueries are not allowed in the following places:
1) GROUP BY clause
2) HAVING clause
3) CASE WHEN
4) CONNECT BY
5) (+ others)
Having worked with Oracle for quite some time, I knew about 1) and 4), however, I was surprised about 2) and 3). So I did a few test queries
and it seems that subqueries in these places work.
The following two examples work:
reg. 2) select dep, max(r) from (
select 1 as dep, 1 as r from dual UNION
select 1 as dep, 2 as r from dual UNION
select 2 as dep, 3 as r from dual
) having max(r) > (select 2 from dual)
group by dep;
reg. 3) select case when (select 2 from dual) > 1 then 1 else 0 end from dual;
Do I misinterprete the statement in the book? Or was it maybe not allowed in an Oracle version prior to 10g?
Thanks!
|
|
|
|
| Re: Subqyery with group by / case when / having [message #645464 is a reply to message #645463] |
Mon, 07 December 2015 05:08   |
John Watson
Messages: 8995 Registered: January 2010 Location: Global Village
|
Senior Member |
|
|
When you come across an error such as this, the best option is to contact the author through the publisher so that it can be included in the published errata. Include your demonstration, of course.
All authors appreciate this (trust me - as an author myself, I know). We all make mistakes, and no matter how good your technical editor is, some get through.
Incidentally, I am not going to say "good luck with the exam". With your approach to study, you won't need any luck.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Re: Subqyery with group by / case when / having [message #645500 is a reply to message #645481] |
Mon, 07 December 2015 09:43  |
Solomon Yakobson
Messages: 3305 Registered: January 2010 Location: Connecticut, USA
|
Senior Member |
|
|
You are confusing things.
GROUP BY CASE
WHEN row_id IN (
SELECT row_id
FROM test
WHERE row_id = '1-2BNEAX'
)
THEN 1
ELSE 2
END;
doesn't group by subquery. It groups by CASE result. Compare:
SQL> SELECT COUNT (*) AS cnt
2 FROM test
3 GROUP BY CASE
4 WHEN row_id IN (
5 SELECT row_id
6 FROM test
7 WHERE row_id = '1-2BNEAX'
8 )
9 THEN 1
10 ELSE 2
11 END;
CNT
----------
1
SQL> SELECT COUNT (*) AS cnt
2 FROM test
3 GROUP BY (
4 SELECT row_id
5 FROM test
6 WHERE row_id = '1-2BNEAX'
7 )
8 /
SELECT row_id
*
ERROR at line 4:
ORA-22818: subquery expressions not allowed here
SQL>
SY.
|
|
|
|