With clause vs sub-queries
db and dev 10g rel2 , hi all,
i am trying to learn the "WITH CLAUSE" , and i do not see any difference between using it and using sub-queries .
when i searched for this , i found that the with clause is used when You need to reference the subquery block multiple places in the query by specifying the query name , but i can not imagine an example for doing so .
if you could provide me with an example please ? and telling me about another situations in which i could need using the "with clause" if any ?
thanks
>
db and dev 10g rel2 , hi all,
i am trying to learn the "WITH CLAUSE" , and i do not see any difference between using it and using sub-queries .
when i searched for this , i found that the with clause is used when You need to reference the subquery block multiple places in the query by specifying the query name , but i can not imagine an example for doing so .
if you could provide me with an example please ? and telling me about another situations in which i could need using the "with clause" if any ?
>
It isn't just about referencing a subquery multiple times. There are other advantages to using 'common table expressions'/'subquery factoring' also.
Take a look at the example below. It first defines 'dept_costs' as a query block, then defines 'avg_cost' as a new query block and it references the first query block.
Then the actual query references both query blocks just as if they are tables. And, in fact, in some circumstances Oracle will actually materialize them AS temporary tables.
Look at how easy it is to understand the entire statement. You can focus first on the 'dept_costs' query block WITHOUT having to look at anything else. That is because the query block is self-contained; you are defining a result set. There is no 'join' or connection to any other part of the statement.
It is easy for a developer, and for Oracle, to understand what is needed for that one piece.
Next you can focus entirely on the 'avg_cost' query block. Since it uses the first query block just as if it were a table you can treat it as a table. That means you do NOT even need to look at the first query block to understand what the second query block is doing.
Same with the actual query. You can analyze it by treating the two query blocks just as if they were other tables.
Even better you can test the first query block by itself in sql*plus or other tool to confirm that it works and you can create an execution plan for it to make sure it will use an appropriate index. You can also then test the first and second query blocks together to make sure THEY have a proper execution plan.
Then when you test then entire statement you already know that the query blocks work correctly.
Try to do THAT with a query that uses nested sub-queries.
Sure - you could write a set of nested sub-queries to accomplish the same thing (Oracle will sometimes rewrite your query that way itself) but it becomes one big query and the individual pieces are not nearly as easy to see, analyze or understand.
It can be difficult if not impossible to extract a nested query in order to test it even to just try to get the syntax working. And when you do extract it you will often be testing something that isn't quite exactly the same as when i t was nested.
So: easier to understand, easier to write and test (especially for new developers) as well as easier to use multiple times without having to duplicate it.
>
subquery_factoring_clause
The WITH query_name clause lets you assign a name to a subquery block. You can then reference the subquery block multiple places in the query by specifying the query name. Oracle Database optimizes the query by treating the query name as either an inline view or as a temporary table.
>
The SQL Language doc has an example.
http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#i2129904
>
Subquery Factoring: Example The following statement creates the query names dept_costs and avg_cost for the initial query block containing a join, and then uses the query names in the body of the main query.
WITH
dept_costs AS (
SELECT department_name, SUM(salary) dept_total
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY department_name),
avg_cost AS (
SELECT SUM(dept_total)/COUNT(*) avg
FROM dept_costs)
SELECT * FROM dept_costs
WHERE dept_total >
(SELECT avg FROM avg_cost)
ORDER BY department_name;
DEPARTMENT_NAME DEPT_TOTAL
Sales 313800
Shipping 156400
Similar Messages
-
IN clause with ORDER BY clause in sub-queries
Hello,
We generate dynamic queries with the following statement pattern (could be many union/intersect sub-queries):
select my_col
from my_table
where my_col IN
select table_2.my_col , x_col from table_2 where x_col > 10
UNION
select table_3.my_col , y_col from table_3 where y_col > 20
INTERSECT
select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
I know that I can do just the sub-queries w/ an ORDER BY clause as follows (as long as the 2nd parameter in the select stmts are of the same type):
select table_2.my_col , x_col from table_2 where x_col > 10
UNION
select table_3.my_col , y_col from table_3 where y_col > 20
INTERSECT
select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
order by 2 desc
But my questions are:
1. What is (if there is) the syntax that will ensure that the result set order will be that of the ordering of the sub-queries?
Or does my SQL stmt have to have syntactically (but not semantically) change to achieve this?
Thanks,
JimRandolf Geist wrote:
just a minor doubt - I think it is not officially supported to have separate ORDER BYs in a compound query with set operators (e.g. UNION / UNION ALL subsets). Of course one could use inline views with NO_MERGE + NO_ELIMINATE_OBY hints, but I think the only officially supported approach is to use a single, final ORDER BY (that needs to use positional notation as far as I remember).
Randolf,
You're right, of course, about the separate "order by" clauses.
Interestingly the following type of thing does work though (in 10.2.0.3, at least):
with v1 as (
select * from t1 where col1 = 'ABC' order by col2
v2 as (
select * from t1 where col1 = 'DEF' order by col2
select * from v1
union all
select * from v2
;A quick check the execution plan suggsts that Oracle appears to be convering this to the following - even though its technically not acceptable in normal circumstances:
select * from t1 where col1 = 'ABC' order by col2
union all
select * from t1 where col1 = 'DEF' order by col2
;Regards
Jonathan Lewis
http://jonathanlewis.wordpress.com
http://www.jlcomp.demon.co.uk
To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
"Science is more than a body of knowledge; it is a way of thinking"
Carl Sagan -
Tricky query with multiple hierarchial sub queries
Here's a pussle that I cannot solve. Who can help me?
Given table F (records form a binary tree with levels 0, 1, and
2):
Id IdParent
F1 null
F2 F1
F3 F2
F4 F2
F5 F1
F6 F5
F7 F5
and given table D (records form a similar binary tree with
levels 0, 1, and 2):
Id IdParent
D1 null
D2 D1
D3 D2
D4 D2
D5 D1
D6 D5
D7 D5
and given table P (cross referencing tables F and D):
IdF IdD
F2 D6
F3 D2
F5 D7
and given table S (which holds the seed to the query):
IdF
F3
and given table I (just any collection of records that reference
table D which we want to select records from):
Id IdD
I1 D1
I2 D2
I3 D3
I4 D4
I5 D5
I6 D6
I7 D7
I8 D1
I9 D5
all together being related like in figure 1:
S.IdF =>> F.Id
F.Id <- P.IdF
P.IdD -> D.Id
D.Id <<= I.IdD
where =>> denotes 'is or is a descenden of'
and -> denotes 'is'
I want to build a query that lets me select all records from
table I, which reference table D, such that the referenced
records in table D are hierarchial descendents of any record
that is referenced by records in table P, for which they
reference records in table F, which are ancestors to records
referenced by records in table S.
If it wasn't for the hierarchial approach on both sides of the
cross referencing table, matters would have been easy. Then the
releational map would have been like in figure 2:
S.IdF <- P.IdF
P.IdD -> I.IdD
and the query would have been:
SELECT I.Id
FROM I, P, S
WHERE I.IdD = P.IdD
AND P.IdF = S.IdF
So in what I am looking for, you may say that the '='-signs in
this select statement should denote 'is or is a descenden of'
going towards the side of table P.
Given the tables listed above and given the query I am seeking,
I expect to retrieve the following result set:
I.Id
I2
I3
I4
I6
Tricky, eh? I belive the figures are the best angles to
understand this problem.You do this with subqueries and hierarchical queries...
First the hierarchal subquery on F...
SQL> SELECT f.id
2 FROM f
3 CONNECT BY PRIOR f.idp = f.id
4 START WITH f.id IN ( SELECT idf FROM s )
5 ;
ID
F3
F2
F1
Then join with the cross reference table...
SQL> SELECT p.idd
2 FROM p
3 , ( SELECT f.id
4 FROM f
5 START WITH f.id IN ( SELECT idf FROM s )
6 CONNECT BY PRIOR f.idp = f.id
7 ) s
8 WHERE s.id = p.idf
9 ;
ID
D6
D2
Use this as a subquery in a hierarchial query for the
descendents in D...
SQL> SELECT d.id
2 FROM d
3 START WITH d.idd IN ( SELECT p.idd
4 FROM p
5 , ( SELECT f.id
6 FROM f
7 START WITH f.id IN ( SELECT
idf FROM s )
8 CONNECT BY PRIOR f.idp = f.id
9 ) s
10 WHERE s.id = p.idf
11 )
12 CONNECT BY PRIOR d.id = d.idp
13 ;
ID
D2
D3
D4
D6
Then use that as a subquery to return the I result set...
SQL> SELECT i.id
2 FROM i
3 WHERE i.idd IN ( SELECT d.id
4 FROM d
5 START WITH d.id IN ( SELECT p.idd
6 FROM p
7 , ( SELECT
f.id
8 FROM f
9 START
WITH f.id IN ( SELECT idf FROM s )
10 CONNECT
BY PRIOR f.idp = f.id
11 ) s
12 WHERE s.id = p.idf
13 )
14 CONNECT BY PRIOR d.id = d.idp
15 )
16 ;
ID
I2
I3
I4
I6Good Luck... -
A Single query with out the sub-queries
I am using My-SQL as my back-end and it doesnot support the
Sub-Queries. i have my table given below
UserID..UserName..ParentUserID
1........Admin...........0
2........Sales...........1
3........Sourcing........1
4........SalesHead.......2
5........SourcingHead....3
6........SalesExec.......4
7........SourExec........5
The table contains heirarchy of users. The top most users
has the ParentUserID as 0. and the remaining has their own ParentUserID
I want to get the complete heirarchy of a given user in single ResultSet.
It should be done without using sub-queries. but all joins can be used.
e.g.
if i say userid is 2 i should get following output:
Sales - > SalesHead -> SalesExec->......
Can any body please help me out!
Sridhar.Hi Sridhar,
You can use recursive method. Make a method as follows :
public String getChildren(int UserID)
String temp = "";
Connection con = DriverManager.getConnection("","","");
Statement st = con.createStatement();
ResultSet rs = statement.executeQuery("select UserID from MyUsers where ParentUserID = " + UserID);
while(rs.next())
temp += " [ ";
if(temp.equals(""))
temp += getChildren(rs(0));
else
temp += " -> " + getChildren(rs(0));
temp += " ] ";
return temp;
then call his method by providing any UserID to it and it will return you a string containing complete hierarchy in the following format :
AAA -> BBB -> CCC -> DDD
I hope it will help you.
regards,
Humayun -
Parallel Execution of Sub Queries using WITH clause ?
Hi ,
For the below query is it that Oracle Optimizer executes "sum_data" and "avg_data" queries parallely ?
WITH sum_data AS
SELECT deptno, sum(sal) AS S FROM emp GROUP BY deptno ),
avg_data AS
SELECT deptno, avg(sal) AS A FROM emp GROUP BY deptno )
SELECT sum_data.deptno, s, a, s / a FROM sum_data , avg_data
WHERE sum_data.deptno = avg_data.deptno
ORDER BY sum_data.deptno
THANKSNo, it doesn't.
You can add the parallel hint to each query itsel to speed up the exuction of a given query. But the WITH clause has nothing to do with parallel, it only uses temp or memory to keep the data being processed and thus speeds up the performance.
Edited by: DimaK on Feb 25, 2011 10:42 AM -
Can you pass parameters with sub queries
I have created a Custom folder within a Business Area using a sql query that has multi sub queries. I need to be able to pass date parameters at the top level and at each sub query levels. Is this possible, or how can it be done in Discoverer?
I have attached an example of the query below.
select T.title_type_code, T.title_number
from title_trans T
where T.title_type_code in ( 'A', 'AC', 'AN','AS','EL', 'ERL','SEL', 'MC', 'MCN', 'MCC', 'MCS', 'ML', 'MLN', 'MLC', 'MLS')
and T.trans_type_code = 'APPL'
and trunc(T.effective_date) between to_date('&start_date','DD/MM/YYYY') and to_date('&end_date','DD/MM/YYYY')
and exists
(select *
from title_land_status L
where T.title_type_code = L.title_type_code
and T.title_number = L.title_number
and L.trans_type_code in ('APPL', 'FLS', 'AVAR')
--FREEHOLD LAND
and L.land_status_id in ('15')
and L.date_completed = (select MAX(L.date_completed)
from title_land_status L
where T.title_type_code = L.title_type_code
and T.title_number = L.title_number
and trunc(L.date_completed) <= to_date('&end_date','DD/MM/YYYY')
and L.trans_type_code in ('APPL', 'FLS', 'AVAR')))
and not exists
(select *
from title_land_status L
where T.title_type_code = L.title_type_code
and T.title_number = L.title_number
and L.trans_type_code in ('APPL', 'FLS', 'AVAR')
--AB fREEHOLD LAND - NLC, CLC, TLC, ALC
and L.land_status_id in ('3', '4', '5', '6')
and L.date_completed = (select MAX(L.date_completed)
from title_land_status L
where T.title_type_code = L.title_type_code
and T.title_number = L.title_number
and trunc(L.date_completed) <= to_date('&end_date','DD/MM/YYYY')
and L.trans_type_code in ('APPL', 'FLS', 'AVAR')))
and not exists
(select * from title TIT
where T.title_type_code = TIT.title_type_code
and T.title_number = TIT.title_number
and TIT.purpose = 'EMPC')
order by T.title_type_code;Ok,
I just tried that and it still doesn't pass anything to the prompt.
I changed the prompt to an edit field and I made the following weblink but when i click the link from an account it doesn't put anything in the prompt and all data for all accounts is shown.
This is the URL maybe I messed something up...
https://secure-ausomx###.crmondemand.com/OnDemand/user/Dashboard?OMTHD=ShowDashboard&OMTGT=ReportIFrame&SelDashboardFrm.Dashboard Type=%2fshared%2fCompany_########_Shared_Folder%2f_portal%2f360+Report&Option=rfd&Action=Navigate&P0=1&P1=eq&P2=Account."Account Name"&P3=%%%Name%%%
thanks -
Sub Queries in Hyperion Interactive Reporting
Hi All,
I am new to Hyperion.
How to create Sub Queries in Hyperion IR?????
Please provide steps to createI Assume that you have done creating required OCE, and familiar with the single table query process. You can create sub queries using the Custom SQL feature, which is located under view menu->custom SQL. Please note that the query data model must have at least one table to use this feature.
Here are the steps to create sub query.
1. select the main table from table catalog list
2. select the required columns from table and right click " add selected items" to request section.
3. go to View menu - > custom SQL
4. you will see a section which is editable enter all your where clause and sub query section and then process.
Let me know if you need any detail information. -
Post Author: pranathi20
CA Forum: Data Connectivity and SQL
Hi All,
Can someone help me with the below SQL query? I am not sure how to have the sub query in CR
SELECT x.created_on, x.ssn, x.age , max(DECODE(x.rn,1,x.nlsi_answer)) BIO001 , max(DECODE(x.rn,4,x.nlsi_answer)) BIO116 , x.nlsipvsc
FROM (SELECT nlsiview.created_on created_on , nlsiview.ssn ssn , nlsiview.age age , nlsiview.answer nlsi_answer , ROW_NUMBER() OVER (PARTITION BY nlsiview.created_on, nlsiview.ssn ORDER BY NULL) rn FROM nlsiview ) x GROUP BY x.created_on, x.ssn, x.age ORDER BY x.created_on, x.ssn /I Assume that you have done creating required OCE, and familiar with the single table query process. You can create sub queries using the Custom SQL feature, which is located under view menu->custom SQL. Please note that the query data model must have at least one table to use this feature.
Here are the steps to create sub query.
1. select the main table from table catalog list
2. select the required columns from table and right click " add selected items" to request section.
3. go to View menu - > custom SQL
4. you will see a section which is editable enter all your where clause and sub query section and then process.
Let me know if you need any detail information. -
Difference between WITH CLAUSE and INLINNE VIEW.
Hi experts.
Can anyone explain me the diff. between WITH CLAUSE and INLINNE VIEW with some example.
Thanks in advance.user10314274 wrote:
Hi experts.
Can anyone explain me the diff. between WITH CLAUSE and INLINNE VIEW with some example.Generally, they are the same thing with a few minor differences.
The WITH clause gives you a little more control on how the sub-queries are to be set up and used and allows the same subquery to be used multiple times without re-reading the data. Both simulate the functionality of views.
I feel the WITH clause provides better strucure and maintainablility.
The WITH clause aslo offesr two hints, INLINE and MATERIALIZE that can affect performance - both are used with the query in the IN clause. INLINE causes the subquery to be used as a subquery (inline view) while MATERIALIZE requests that the data be copied to a temporary table first. These hints are undocumented but are recognized by the user community.
Edited by: riedelme on Jan 20, 2010 6:32 AM -
ORA-32034: unsupported use of WITH clause-issue
hello all,
i am facing some issue when i use with clause and union all operator.
i have created a dummy code to solve this problem..
my code is ----------
with dept_1 as
(select deptno d1 from detp9 where deptno = 20)
select empno from emp9 e,dept_d1 where e.empno = dept_1.d1
UNION ALL
with dept_1 as
(select deptno d2 from detp9 where deptno = 30)
select empno from emp9 e,dept_d2 where e.empno = dept_2.d2.
when i ran this i gort a message-
ORA-32034: unsupported use of WITH clause.
please help me to solve this iisue..
when i ran it separatly without using union/union all it ran sucessfully..
thanks in advance..923315 wrote:
hello all,
i am facing some issue when i use with clause and union all operator.
i have created a dummy code to solve this problem..
my code is ----------
with dept_1 as
(select deptno d1 from detp9 where deptno = 20)
select empno from emp9 e,dept_d1 where e.empno = dept_1.d1
UNION ALL
with dept_1 as
(select deptno d2 from detp9 where deptno = 30)
select empno from emp9 e,dept_d2 where e.empno = dept_2.d2.
when i ran this i gort a message-
ORA-32034: unsupported use of WITH clause.
please help me to solve this iisue..
when i ran it separatly without using union/union all it ran sucessfully..
thanks in advance..Well, i don't see anything about these queries that makes sense.
You are essentially joining emp and dept on EMPNO to DEPTNO ... that doesn't usually make any sense.
How about you step back from the query which is almost certainly incorrect, and explain your tables, their data and what you need as output?
Cheers, -
In a previous post I asked a question in regards to showing all the days between now and sysdate +14. I got an answer back an was able to manipulate the code in sql and get it to run returning the necessary results. Now when I try to copy and paste the code into and LOV the LOV saves fine but when I run the form I get an ERR-1000 Unable to Determine LOV along with ORA-06559 an INTO clause is expected with this select statemt. Can you not put With clause in an LOV lookup?
My SQL statement is below. Thanks! Amber
with t as (
select
trunc(sysdate) + 1 + (rownum - 1) / 2 d
from
dual
connect
by rownum <= 28)
, call_info as (
select
c.schedule_id, c.call_date, c.call_identifier
from uid_csr_schedule c
union select
c2.schedule_id, c2.call_date, c2.call_identifier
from uid_csr_schedule c2
select
to_char(d, 'fmDy DD/MM/YYYY AM') l
, d v
from
t
where
100 > (select
count(call_identifier)
from
call_info ci
where
ci.call_date = t.d);mtuser,
Since the LOV queries are executed dynamically, I guess I'm not totally surprised there was a problem?
Since that's the case, I would think your LOV query might run more efficiently by defining the entire query as a view, not use the WITH clause. I didn't see anything in your LOV query that would make this require dynamic input from the Apex form, though maybe you simplified it.
Good luck,
Stew -
Hi,
I was going through some docs on using WITH clause in curosr...but coulcn't understand.
I was going through existing code for customization, that has 'WITH' clause.
I'm trying to understand below piece of code.
could you let me know what the below code is about..
CURSOR CUR_CRK
IS
WITH PTLPM_WITH AS
(SELECT
/*+ INDEX(P_TR_LOAN_PAST_MONTHLY PK_P_TR_LOAN_PAST_MONTHLY) */
FROM INF.P_TR_LOAN_PAST_MONTHLY
WHERE POST_DATE =P_POST_DATE
AND TREND_GROUP_ID = 'M'
AND APPL_ID IN ('FL','LN')
UIGL_INF_WITH AS
(SELECT * FROM INF.U_IM_GALL_LOAN
XHCC_INF_WITH as
(SELECT * FROM DWC.XREF_HIER_COST_CENTER_11SEP12 --INF.XREF_HIER_COST_CENTER
)Thanks.Perhaps a simple example will make it clear...
SQL> ed
Wrote file afiedt.buf
1 select e.empno, e.ename, d.dname
2 from (select * from emp) e
3 join (select * from dept) d
4* on (e.deptno = d.deptno)
SQL> /
EMPNO ENAME DNAME
7369 SMITH RESEARCH
7499 ALLEN SALES
7521 WARD SALES
7566 JONES RESEARCH
7654 MARTIN SALES
7698 BLAKE SALES
7782 CLARK ACCOUNTING
7788 SCOTT RESEARCH
7839 KING ACCOUNTING
7844 TURNER SALES
7876 ADAMS RESEARCH
7900 JAMES SALES
7902 FORD RESEARCH
7934 MILLER ACCOUNTING
14 rows selected.Ok, a bit of a nonsense query in itself, but it's demonstrating that we have two subqueries that we are getting our data from.
Now, writing the same query using a WITH clause...
SQL> ed
Wrote file afiedt.buf
1 with e as (select * from emp)
2 ,d as (select * from dept)
3 select e.empno, e.ename, d.dname
4* from e join d on (e.deptno = d.deptno)
SQL> /
EMPNO ENAME DNAME
7369 SMITH RESEARCH
7499 ALLEN SALES
7521 WARD SALES
7566 JONES RESEARCH
7654 MARTIN SALES
7698 BLAKE SALES
7782 CLARK ACCOUNTING
7788 SCOTT RESEARCH
7839 KING ACCOUNTING
7844 TURNER SALES
7876 ADAMS RESEARCH
7900 JAMES SALES
7902 FORD RESEARCH
7934 MILLER ACCOUNTING
14 rows selected.As you can see, the subqueries have been moved out of the main query and put into the WITH clause, and then the main query just references those subqueries aliases.
In the above example, there's not much point in doing this, but in more complex queries, you may have a subquery that is used several times, in which case having it in the WITH clause means that that subquery is processed just once and used many times, (you can also look at the MATERIALIZE hint to help improve performance with such subqueries if necessary)
The difficulty with finding this in the documentation is because you will no doubt be trying to search for "WITH", which isn't a very good search term to be using as it's used in the english language too much for an accurate hit... so... when you learn it's called "Subquery Factoring" (because you are factoring out the subqueries from the main query), it then becomes easier to find...
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#i2161315
... and you see it's included as part of the documentation for the SQL SELECT statement. -
Hi,
Can we use order by clause in Sub query?
While using the order by clause, I am getting the "missing expression error" . If I remove order by clause query executing fine.
Here is my query:
select *
from emp_mstr
where emp_no in(select
emp_no
from emp_mstr
order by branch_no);
Thanks & Regards,
MahiMay be you miss some required spaces also, other than wrong use of ORDER BY
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr e2
-- order by e2.branch_no
);Why do you want to ORDER BY in the subquery, which you use with IN clause? That will not make any difference in the result..Means the result you get with ORDER BY will be same as without that.. And in this case, ORDER by is a unncessary overhead.. And Ordering is very costly..
And why do you want to have the IN clause at all in your query? You are referring the same tables in the main query and sub query..
The below will give the same result
select *
from emp_mstr
where emp_no is not nullIf you want to use another table in the subquery, always use aliasess...
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr2 e2
-- order by e2.branch_no
); -
Bug in WITH clause (subquery factoring clause) in Oracle 11?
I'm using WITH to perform a set comparison in order to qualify a given query as correct or incorrect regarding an existing solution. However, the query does not give the expected result - an empty set - when comparing the solution to itself in Oracle 11 whereas it does in Oracle 10. A minimal example os posted below as script. There are also some observations about changes to the tables or the query that make Oracle 11 returning correct results but in my opinion these changes must not change the semantics of the queries.
Is this a bug or am I getting something wrong? The Oracle versions are mentioned in the script.
-- Bug in WITH clause (subquery factoring clause)
-- in Oracle Database 11g Enterprise Edition 11.2.0.1.0?
DROP TABLE B PURGE;
DROP TABLE K PURGE;
DROP TABLE S PURGE;
CREATE TABLE S (
m number NOT NULL,
x varchar2(30) NOT NULL
CREATE TABLE K (
k char(2) NOT NULL,
x varchar2(50) NOT NULL
CREATE TABLE B (
m number NOT NULL ,
k char(2) NOT NULL ,
n number
INSERT INTO S VALUES(1, 'h');
INSERT INTO S VALUES(2, 'l');
INSERT INTO S VALUES(3, 'm');
INSERT INTO K VALUES('k1', 'd');
INSERT INTO K VALUES('k2', 'i');
INSERT INTO K VALUES('k3', 'm');
INSERT INTO K VALUES('k4', 't');
INSERT INTO K VALUES('k5', 't');
INSERT INTO K VALUES('k6', 's');
INSERT INTO B VALUES(1, 'k1', 40);
INSERT INTO B VALUES(1, 'k2', 30);
INSERT INTO B VALUES(1, 'k4', 50);
INSERT INTO B VALUES(3, 'k1', 10);
INSERT INTO B VALUES(3, 'k2', 20);
INSERT INTO B VALUES(3, 'k1', 30);
INSERT INTO B VALUES(3, 'k6', 90);
COMMIT;
ALTER TABLE S ADD CONSTRAINT S_pk PRIMARY KEY (m);
ALTER TABLE K ADD CONSTRAINT K_pk PRIMARY KEY (k);
ALTER TABLE B ADD CONSTRAINT B_S_fk
FOREIGN KEY (m) REFERENCES S(m) ON DELETE CASCADE;
CREATE OR REPLACE VIEW v AS
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC;
-- Query 1: Result should be 0
WITH q AS
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC
SELECT COUNT(*)
FROM
SELECT * FROM q
MINUS
SELECT * FROM v
UNION ALL
SELECT * FROM v
MINUS
SELECT * FROM q
-- COUNT(*)
-- 6
-- 1 rows selected
-- Query 2: Result set should be empty (Query 1 without counting)
WITH q AS
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC
SELECT *
FROM
SELECT * FROM q
MINUS
SELECT * FROM v
UNION ALL
SELECT * FROM v
MINUS
SELECT * FROM q
-- M N
-- null 10
-- null 30
-- null 40
-- 1 40
-- 3 10
-- 3 30
-- 6 rows selected
-- Observations:
-- Incorrect results in Oracle Database 11g Enterprise Edition 11.2.0.1.0:
-- Query 1 returns 6, Query 2 returns six rows.
-- Correct in Oracle Database 10g Enterprise Edition 10.2.0.1.0.
-- Correct without the foreign key.
-- Correct if attribute x is renamed in S or K.
-- Correct if attribute x is left out in S.
-- Correct without the ORDER BY clause in the definition of q.
-- Only two results if the primary key on K is left out.
-- Correct without any change if not using WITH but subqueries (see below).
-- Fixed queries
-- Query 1b: Result should be 0
SELECT COUNT(*)
FROM
SELECT * FROM
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC
MINUS
SELECT * FROM v
UNION ALL
SELECT * FROM v
MINUS
SELECT * FROM
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC
-- COUNT(*)
-- 0
-- 1 rows selected
-- Query 2b: Result set shoud be empty (Query 1b without counting)
SELECT *
FROM
SELECT * FROM
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC
MINUS
SELECT * FROM v
UNION ALL
SELECT * FROM v
MINUS
SELECT * FROM
SELECT S.m, B.n
FROM S JOIN B ON S.m=B.m JOIN K ON B.k=K.k
WHERE K.x='d'
ORDER BY B.n DESC
-- M N
-- 0 rows selectedYou're all gonna love this one.....
The WITH clause works. But not easily.
Go ahead, build the query, (as noted in a recent thread, I, too, always use views), set the grants and make sure DISCOVERER and EULOWNER have SELECT privs.
1. Log into Disco Admin as EULOWNER. Trust me.
2. Add the view as a folder to the business area.
3. Log into Disco Desktop as EULOWNER. Don't laugh. It gets better.
4. Build the workbook and the worksheet (or just the worksheet if apropos)
5. Set the appropriate "sharing" roles and such
6. Save the workbook to the database.
7. Save the workbook to your computer.
8. Log out of Desktop.
9. Log back into Desktop as whatever, whoever you usually are to work.
10. elect "open existing workbook"
11. Select icon for "open from my computer". See? I told you it would get better!
12. Open the save .dis file from your computer.
13. Save it to the database.
14. Open a web browser and from there, you're on your own.
Fortran in VMS. Much easier and faster. I'm convinced the proliferation of the web is a detriment to the world at large...On the other hand, I'm also waiting for the Dodgers to return to Brooklyn. -
Just a quick question about Reports 10g, does it support queries using the WITH clause? i.e.
WITH alias as (subquery)
SELECT col1, col2...
FROM aliasI can't find anything on the documentation on the OTN site. Reports 9iR2 croaks with this unfortunately.
Regards,
Steve RooneyThat is what I have had to do. I wanted to use the WITH clause because subquery has to be done twice so that I can perform some arithmetic on the result sets. Using the WITH construct I only need to define subquery once and re-use the result set; as a result the version using the WITH clause runs twice as fast in SQL*Plus as the way I have implemented the inline views.
Thanks anyway.
Regards,
Steve Rooney
Maybe you are looking for
-
Backup Assistant not compatible with Droid Razr M
I'm trying to backup my photos, etc. and went to the apps section on Verizon's website to get the Backup Assistant Plus. It says "not compatible your device, choose another to send to." I tried the regular Backup Assistant with the same result. Wh
-
Work Manager 6.0 - Order & Notification assignment type Z
Hi Agentry experts, for WM 6.0 we have the idea to get a more flexible assignment for notifications and work orders, as our business process requires more flexibility than the standard available assignment types e.g. Work Center User A should only se
-
PO workflow - escalator at plant level
Hi SAP people, do you know if it is possible to set the time for workflow escalator at plant level? I have implemented the PO approval flow but i want to define 2 different escalator... Thanks in advance Michela
-
Hi,everyone, I had installed R Enterprise in my Oracle 11.2.0.1 base on win7,using the R 2.13.2, ORE 1.1, I can using the part function: like library(ORE) options(STERM='iESS', str.dendrogram.last="'", editor='emacsclient.exe', show.err
-
Where best to store encryption key for dbms_crypto?
We want to use dbms_crypto to encrypt pwds. Thing is with the encryption key. We now store the encryption key in the package itself. When we deploy the pkg we wrap it. That gives some security, but if we loose the source code we loose the key and als