Update with correlated subquery
Hi,
I have the following SQL update statement:
update temp_input_sms b
set (b.provider_id,b.region_id)=
(select provider_id,region_id
from
select a.PROVIDER_ID,a.REGION_ID,row_number() over (order by fraud) rn
from icdm.smsc_lookup a
where sysdate>=a.VALID_FROM and sysdate<a.VALID_TO
and b.user_summarisation like a.SMSC_CODE_LIKE
) where rn=1)
The problem is that there are two nested subqueries on the right side of the set clause, and in the inner subquery the 'b.user_summarisation' column is not available.
Could anyone suggest a workaround for this problem?
Thanks.
Viktor
possible workaround:
update temp_input_sms c
set (c.provider_id, c.region_id) =
(select d.provider_id, d.region_id
from (select a.provider_id, a.region_id, smsc_code_like,
row_number () over
(partition by a.smsc_code_like
order by a.fraud) rn
from smsc_lookup a, temp_input_sms b
where sysdate >= a.VALID_FROM
and sysdate < a.VALID_TO
and b.user_summarisation like a.SMSC_CODE_LIKE) d
where rn=1
and c.user_summarisation like d.smsc_code_like)
[pre]
Similar Messages
-
I have 2 tables
tblA(aID, aSeq, aname, aLname)
tblB(bSeq, bname, bLname)
I need to update table tblA to set aSeq where the name and Lname match with tblB. Something like
update zA A
set A.aSeq =
select B.bSeq
from zB B
where UPPER(B.bname) = UPPER(A.aname)
and UPPER(B.blname) = UPPER(A.alname)
What am I doing wrong? Why do I get the error - ORA-01427: single-row subquery returns more than one rowbased on above scenario (tblA => proposal tblB => personnel)
select rp.prop_id || '| ' || UPPER(rp.prodir_fn) || '| ' || UPPER(rp.prodir_ln)
from proposal rp
where exists(
select p.piid ---------------------------------------------------get matching names from personnel
from personnel p
where UPPER(rp.prodir_fn) = UPPER(p.fname)
and UPPER(rp.prodir_ln) = UPPER(p.lname)
and EXISTS
( select UPPER(q.fname), UPPER(q.lname) ------------ get matching names of single person that is drop
from personnel q--------------------------------------------- peron names who have same first and last name different id
where UPPER(q.fname) = UPPER(p.fname)
and UPPER(q.lname) = UPPER(p.lname)
group by UPPER(q.fname), UPPER(q.lname)
having count(*) = 1
gives me 3535 matching records
but
my update still fails, Please guide
UPDATE proposal rp
set rp.pi = (
select p.piid
from personnel p
where UPPER(rp.prodir_fn) = UPPER(p.fname)
and UPPER(rp.prodir_ln) = UPPER(p.lname)
and EXISTS
( select UPPER(q.fname), UPPER(q.lname)
from personnel q
where UPPER(q.fname) = UPPER(p.fname)
and UPPER(q.lname) = UPPER(p.lname)
group by UPPER(q.fname), UPPER(q.lname)
having count(*) = 1
; -
I am trying to write a script to set all products in the Confections category that have more than 50 units in stock to a price of $10, and disable them. But I have to include a subquery to identify the category ID from the Category name Confetions. I am
also suppose to show before and after that's why I have to select statements. I am lost, here is what I have and I don't know what I am doing wrong. I am using sql 2012. Do I need to add a inner join to convert the category name to the id?
SELECT
FROM
Products
WHERE
UnitsInstock > 50
AND CategoryID
= 3
UPDATE
Products
SET
UnitPrice = 10.00
WHERE
Unitsinstock > 50
AND CategoryID
= 3
SELECT
FROM
Products
WHERE
UnitsInstock > 50
AND CategoryID
= 3
kinneyleaWell, if you're using SQL Server 2012, I suggest MERGE command and OUTPUT clause, e.g.
;with cteNeedChanges as (select P.* from dbo.Products P
inner join dbo.Categories C ON P.CategoryID = C.CategoryID
where C.CategoryName = 'Confections' and P.UnitsInStock > 50 and P.UnitPrice <> 10)
MERGE Products as Target USING cteNeedChanges as Source ON Target.ProductID = Source.ProductID
WHEN Matched THEN UPDATE SET UnitPrice = 10
OUTPUT Deleted.ProductID, Deleted.UnitPrice, Inserted.UnitPrice
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Performance of using a Select For Update vs a correlated subquery
I was wondering wether or not it is more effecient to use the
Select ... For Update (with a cursor etc.) versus a correlated
subquery.
I can accomplish the same thing with either however performance
at our site is an issue.Use select for update cursor as that is faster as it updates
based on the rowid. One thing to keep in mind is that rowid is
session specific and the rows to be updated get locked so that
nobody else can update them till the lock is released. I have
had very good performance results with these cursors.
Good luck !
Sudha -
Update with exists and subquery
Hi how to pass index to this sql
Table pap ( eqid,seq,histseq,docno,status,value1,value2)
PK(eqid,seq,histseq) and indx (docno)
table pa ( eqid,seq,docno,status,value1,value2)
PK(eqid,seq) and indx (docno)
update pa
set (value1,value2) = (select pap.value1,pap.value2 from pap
where pap.eqid = pa.eqid
and pap.seq = pa.seq
and pap.histseq =1
and pap.docno <> pa.docno
and pap.status = 4 )
where pa.status=1
and exists ( select 1 from pap
where pap.eqid = pa.eqid
and pap.seq = pa.seq
and pap.histseq =1
and pap.docno <> pa.docno
and pap.status =4 )
It is doing fulltable scan on pa and using hash join .
How to write update with subquery method also ?There's nothing wrong with a full scan.
Please read this explanation/example: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9422487749968
If you want more explanation then please follow these guidelines below, so we have sufficient inputs:
[When your query takes too long...|http://forums.oracle.com/forums/thread.jspa?messageID=1812597#1812597]
[How to post a SQL statement tuning request|http://forums.oracle.com/forums/thread.jspa?threadID=863295&tstart=0]
Remember to put the tag befor and after the examples you post.
See http://forums.oracle.com/forums/help.jspa regarding tags. -
What is the main difference between Merge Statment(only update) with simple Update statement based on Select query ?
Which one is faster ?There are no vanilla answers to such a question especially when asked by someone who doesn't have time to post version number or DML.
The only honest answer ... build a test environment and test it using EXPLAIN PLAN and SET TIMING ON.
That said: A merge statement should only be used where it is appropriate. -
Oracle 11g: update with group by
DB. 11.2.0.2.0
Hello
This feels as though it should be simple. The below code tries to update the Activities table with the sum of staff hours (worked out from two other tables).
The select works fine:
select a.activities_id, sum((t.st_proportion*s.staff_time)*7*(t.st_enddate-t.st_startdate)/100)
from aa_wl_activities3 a
join aa_wl_stafftime2 t
on a.activities_id=t.st_activity_id
join aa_wl_staff s
on t.st_staff_id=s.staff_id
group by a.activities_idand produces data like this:
7 700
6 700
44 700
41 700
update aa_wl_activities3 a
set a.activities_stafftime = sum((t.st_proportion*s.staff_time)*7*(t.st_enddate-t.st_startdate)/100)
join aa_wl_stafftime2 t
on a.activities_id=t.st_activity_id
join aa_wl_staff s
and t.st_staff_id=s.staff_id
group by a.activities_idI get this error:
ORA-00934: group function is not allowed hereFrom various bits of googling, it is possible to update using an aggregate function - I want to check it's possible in Oracle SQL and if anyone can spot anything wrong with my code
Thanks
Emmaemma-apex wrote:
From various bits of googling, it is possible to update using an aggregate function - I want to check it's possible in Oracle SQL and if anyone can spot anything wrong with my codeYes, it's possible but you have to do it with a correlated subquery that computes the sum for each row of the target table :
update aa_wl_activities3 a
set a.activities_stafftime =
select sum(
(t.st_proportion * s.staff_time)
* 7
* (t.st_enddate - t.st_startdate)
/ 100
from aa_wl_stafftime2 t
join aa_wl_staff s on s.staff_id = t.st_staff_id
where t.st_activity_id = a.activities_id
;(Or MERGE as suggested) -
Update with Select from a non-existant column
Hello,
If I have two tables in Oracle database:
Table_1 has column id, c1, c2
Table_2 has column id, c1, c2
If I run the following select statement, it will give error, because column c3 does not exist:
select c3 from table_2;
However, if I run the following update statement, it run successfully with error. It shows, for example, 10 rows updated:
update table_1 t1 set t1.c2 =
(select t2.c3 from table_2 t2
where t2.id = t1.id);
Could someone explain to me what happens?
Regards!rp0428 wrote:
>
It's called a Correlated Sub-Query . It's documented, with examples, in the SQL Language manual
>
I'm familiar with correlated sub-queries. That link has NO examples using a column in the FROM list of a sub-query that is NOT in a table in the FROM list of that sub-query.
You can certainly use constants, or functions in a select list without needing a table reference but I haven't seen any documentation showing an example of selecting a column in a sub-query that doesn't exist in one of the FROM tables.There are no examples of selecting a column from the outer query in a sub-query because in 99.999% of the cases it would be the wrong thing to do, however it is possible. Clearly the sub-query can "see" columns in the outer query otherwise how would it see the values for a correlated sub-query. As Frank said, there is nothing in the documenation that precludes using an outer column in the sub-query, and this paragraph from Frank's link certainly seems to pretty generally refer to the entire sub-query:
If columns in a subquery have the same name as columns in the containing statement, then you must prefix any reference to the column of the table from the containing statement with the table name or alias. To make your statements easier to read, always qualify the columns in a subquery with the name or alias of the table, view, or materialized view.John -
Performance Issues with Correlated Subqueries
Hi,
We have a problem with the performance of correlated subquery. Please see below the query we use;
select &ebenecolval, &attribalias
from freq2 as tab1
where cnt_rank = (select min(cnt_rank)
from freq2_&attribcolval as tab2
where tab1.&ebenecolval = tab2.&ebenecolval);
(We need to get the minimum of the cnt_rnk from the table freq2 for each ebenecolval attribute)
The table freq2 has around 12 million records and so the subquery executes for each of the record and there by reduces the performance.
Can you please suggest any other option to otimize the performance.
Thanks.create a index on (cnt_rank , .&ebenecolval) for the table freq2_&attribcolval and check its performance.
I am not sure about the improvement but you can give a try. -
Top n Analysis using correlated subquery
Please explain this query. It is doing top n analysis using correlated subquery. I need explaination of execution of this query.
Select distinct a.sal
From emp a
where 1=(select count ( distinct b.sal) from emp b
where a.sal <=b.sal)
Thanks in advanceTry breaking the query down and rewriting it in order to follow the logic;
SQL> --
SQL> -- Start by getting each salary from emp along with a count of all salaries in emp
SQL> --
SQL> select a.sal,
(select count (distinct b.sal) from scott.emp b ) count_sal
from scott.emp a
order by 1 desc
SAL COUNT_SAL
5000 12
3000 12
3000 12
2975 12
2850 12
2450 12
1600 12
1500 12
1300 12
1250 12
1250 12
1100 12
950 12
800 12
14 rows selected.
SQL> --
SQL> --Add a condition to the count for only salaries below or equal to the current salarySQL> --
SQL> select a.sal,
(select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) rank_sal
from scott.emp a
order by 1 desc
SAL RANK_SAL
5000 1
3000 2
3000 2
2975 3
2850 4
2450 5
1600 6
1500 7
1300 8
1250 9
1250 9
1100 10
950 11
800 12
14 rows selected.
SQL> --
SQL> -- Add a condition to only pick the nth highest salary
SQL> --
SQL> select a.sal,
(select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) rank_sal
from scott.emp a
where (select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) = 4
SAL RANK_SAL
2850 4
1 row selected.Hope this helps. -
SQL Bug in "Minus" in correlated subquery presence of index
(Oracle Database 11g Release 11.2.0.1.0)
Below, there is a small example that shows the bug. Further below,
there are some more comments.
drop table Country;
create table Country
(code VARCHAR2(4) constraint countrykey PRIMARY KEY,
name VARCHAR2(35));
-- if the key constraint is not given, the bug does not occur
drop table City;
create table City
(name VARCHAR2(35),
country VARCHAR2(4),
population number);
drop table Locatedon;
create table Locatedon
(city VARCHAR2(35),
country VARCHAR2(4),
island VARCHAR2(35));
insert into country values('E','Spain');
insert into country values('F','France');
insert into country values('S','Sweden');
insert into country values('GB','Sweden');
insert into city values('Ajaccio','F',53500);
insert into city values('Paris','F',2152423);
insert into city values('Palma','E',322008);
insert into city values('Madrid','E',3041101);
insert into city values('Stockholm','S',711119);
insert into city values('London','GB',6967500);
insert into locatedon values('Ajaccio','F','Corse');
insert into locatedon values('Palma','E','Mallorca');
insert into locatedon values('London','GB','Great Britain');
-- all countries that have a city that is not located on
-- some island: should be E, F, S.
Select c.name
From country c
Where exists
((Select name
From city
Where city.country=c.code)
minus
(Select city
From locatedon
Where locatedon.country=c.code)
-- wrong answer: only Sweden; Spain and France not in the answer!
select distinct country from
((Select name, country
From city)
minus
(Select city, country
From locatedon)
-- correct answer: E, F, S
Comments:
The bug has been found by students in our SQL course.
Using a larger database from that course, the bug can be reproduced
(same queries as above) at
http://www.semwebtech.org/sqlfrontend/
(wrong: 142 answers, correct: 154 answers)
During reducing it to a simple sample, there were some interesting
observations: trying with smaller and simpler tables (without the keys)
and synthetic data, the bug did not occur immediately. When
restating the query after about one day, the bug occurred. Obviously,
Oracle creates some index on its own in course of its internal
optimization that (or more exactly, its usage) exhibits the bug. The
query plan (showed in SQL Developer) was the same before and after.
WolfgangThere's a typo in the test data - GB should presumably not be in Sweden. However....
the bug did not occur immediatelyIt's possible. But what would have almost certainly happened is that the execution plan DID change at some point. There are various reasons why it might not be immediate.
Obviously, Oracle creates some index on its own in course of its internal optimizationFar from obvious, what are you on about?
The query plan was the same before and afterBet you it wasn't.
A clear illustration of the issue and indication that it must be a bug is below.
Simply by hinting a different access method, we can change the result. Therefore, bug.
See [url http://support.oracle.com]Oracle Support and search for "wrong results".
Please raise with Oracle Support to get confirmation of bug.
There have been so many wrong results bugs recently, it's getting ridiculous.
It's a real issue, IMHO.
If you can't trust the DB to get your data right....
Note that the query plan is very much NOT the same and it is the difference in query plan which s that is the root cause of the bug.
SQL> select * from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
CORE 11.2.0.2.0 Production
TNS for Linux: Version 11.2.0.2.0 - Production
NLSRTL Version 11.2.0.2.0 - Production
SQL> SELECT c.name
2 FROM country1 c
3 WHERE exists ((SELECT name
4 FROM city1
5 WHERE city1.country=c.code)
6 MINUS
7 (SELECT city
8 FROM locatedon1
9 WHERE locatedon1.country=c.code));
NAME
Sweden
SQL> SELECT /*+ full(c) */
2 c.name
3 FROM country1 c
4 WHERE exists ((SELECT name
5 FROM city1
6 WHERE city1.country=c.code)
7 MINUS
8 (SELECT city
9 FROM locatedon1
10 WHERE locatedon1.country=c.code));
NAME
Spain
France
Sweden
SQL> explain plan for
2 SELECT c.name
3 FROM country1 c
4 WHERE exists ((SELECT name
5 FROM city1
6 WHERE city1.country=c.code)
7 MINUS
8 (SELECT city
9 FROM locatedon1
10 WHERE locatedon1.country=c.code));
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 156929629
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 27 | 12 (25)| 00:00:01 |
| 1 | NESTED LOOPS | | | | | |
| 2 | NESTED LOOPS | | 1 | 27 | 12 (25)| 00:00:01 |
| 3 | VIEW | VW_SQ_1 | 6 | 24 | 10 (20)| 00:00:01 |
| 4 | MINUS | | | | | |
| 5 | SORT UNIQUE | | 6 | 138 | | |
| 6 | TABLE ACCESS FULL | CITY1 | 6 | 138 | 4 (0)| 00:00:01 |
| 7 | SORT UNIQUE | | 3 | 69 | | |
| 8 | TABLE ACCESS FULL | LOCATEDON1 | 3 | 69 | 4 (0)| 00:00:01 |
|* 9 | INDEX UNIQUE SCAN | COUNTRYKEY | 1 | | 0 (0)| 00:00:01 |
| 10 | TABLE ACCESS BY INDEX ROWID| COUNTRY1 | 1 | 23 | 1 (0)| 00:00:01 |
Predicate Information (identified by operation id):
9 - access("VW_COL_1"="C"."CODE")
Note
- dynamic sampling used for this statement (level=4)
26 rows selected.
SQL> explain plan for
2 SELECT /*+ full(c) */
3 c.name
4 FROM country1 c
5 WHERE exists ((SELECT name
6 FROM city1
7 WHERE city1.country=c.code)
8 MINUS
9 (SELECT city
10 FROM locatedon1
11 WHERE locatedon1.country=c.code));
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 1378726376
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 23 | 14 (15)| 00:00:01 |
|* 1 | FILTER | | | | | |
| 2 | TABLE ACCESS FULL | COUNTRY1 | 4 | 92 | 4 (0)| 00:00:01 |
| 3 | MINUS | | | | | |
| 4 | SORT UNIQUE | | 1 | 23 | 5 (20)| 00:00:01 |
|* 5 | TABLE ACCESS FULL| CITY1 | 1 | 23 | 4 (0)| 00:00:01 |
| 6 | SORT UNIQUE | | 1 | 23 | 5 (20)| 00:00:01 |
|* 7 | TABLE ACCESS FULL| LOCATEDON1 | 1 | 23 | 4 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - filter( EXISTS ( (SELECT "NAME" FROM "CITY1" "CITY1" WHERE
"CITY1"."COUNTRY"=:B1)MINUS (SELECT "CITY" FROM "LOCATEDON1" "LOCATEDON1"
WHERE "LOCATEDON1"."COUNTRY"=:B2)))
5 - filter("CITY1"."COUNTRY"=:B1)
7 - filter("LOCATEDON1"."COUNTRY"=:B1)
Note
- dynamic sampling used for this statement (level=4)
27 rows selected.Just to show that it's related to query transformation:
SQL> SELECT /*+
2 no_query_transformation
3 */
4 c.name
5 FROM country1 c
6 WHERE exists ((SELECT name
7 FROM city1
8 WHERE city1.country=c.code)
9 MINUS
10 (SELECT city
11 FROM locatedon1
12 WHERE locatedon1.country=c.code));
NAME
Spain
France
Sweden
SQL> Edited by: Dom Brooks on Jun 30, 2011 2:50 PM -
Is it possible to do an update that involves an outer join on the table being updated?
Here's what I mean - currently, I have something like:
UPDATE table_1 t1
SET col_1 =
SELECT t2.col_2
FROM table_2 t2
WHERE t2.t1_key = t1.t1_key
WHERE EXISTS
SELECT t2.*
FROM table_2 t2
WHERE t2.t1_key = t1.t1_key
UPDATE table_1 t1
SET col_1 = 0
WHERE NOT EXISTS
SELECT t2.*
FROM table_2 t2
WHERE t2.t1_key = t1.t1_key
Yes, I could do set all of the table_1.col_1 values = 0 first, and then do the first update, but it is inefficient given the number of records in the table that would be updated twice.
Is there a way of combining these two updates into a single update statement?You could simply use your first update and omit the WHERE EXISTS clause since you want to update all the rows in table_1 anyway.
If the subquery finds a match, it will update with the selected value. Normally, a non-match would set the column to a null but you can solve that with NVL:
SQL> select * from table_1;
T1_KEY COL_1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
9 rows selected.
SQL> select * from table_2;
T2_KEY COL_2
1 9
3 9
5 9
SQL> UPDATE table_1 t1
2 SET col_1 = nvl (
3 (SELECT t2.col_2
4 FROM table_2 t2
5 WHERE t2.t2_key = t1.t1_key
6 ),0
7 )
8 ;
9 rows updated.
SQL> select * from table_1;
T1_KEY COL_1
1 9
2 0
3 9
4 0
5 9
6 0
7 0
8 0
9 0
9 rows selected. -
JDOQL Correlated Subquery - Bad SQL
Hi,
When I execute a JDOQL correlated subquery, the generated SQL is either
invalid or incorrect. Exactly what happens depends on the exact query, and
on the target database type, but I believe it all stems from the same
problem, which has to do with table aliasing.
If you need further details to reproduce this, please let me know. I'll be
glad to help in any way I can to get this situation remedied quickly, as I
am depending on this functionality. I have a test application to
demonstrate the problem.
I'm using Kodo 3.3.3 and application identity.
Paul Mogren
CommerceHubFor the record, this is in part due to a bug in Kodo's SQL92 joining.
See http://bugzilla.solarmetric.com/show_bug.cgi?id=1156
-Patrick
Paul Mogren wrote:
Certainly... Here's a simple example using Microsoft's JDBC Driver for SQL
Server 2000, and kodo.jdbc.sql.SQLServerDictionary, which produces invalid
SQL.
The query:
pm.newQuery(Container.class,
"(select from Entry entry where entries.contains(entry) &&
entry.containedId != 1).isEmpty()");
The classes:
class Contained {
private int id; //pk
class Container {
private int id; //pk
private Set entries = new HashSet(); //<Entry>
class Entry {
private int containerId; //pk
private int containedId; //pk
private Container container; //persistent-redundant
private Contained contained; //persistent-redundant
The result:
Incorrect syntax near the keyword 'WHERE'. {prepstmnt 31598780 SELECT
t0.container_id, t0.lock FROM WHERE (NOT EXISTS (SELECT DISTINCT
t2.contained_id, t2.container_id FROM dbo.entry t2 WHERE (t1.contained_id
= t2.contained_id AND t1.container_id = t2.container_id AND
t2.contained_id <> ?) AND t0.container_id = t1.container_id))
[params=(int) 1]} [code=156, state=HY000]
Patrick Linskey wrote:
Hi Paul,
Kodo's correlated subquery support does have some known limitations. Can
you post a sample JDOQL statement + corresponding SQL statement?
-Patrick
Paul Mogren wrote:
Hi,
When I execute a JDOQL correlated subquery, the generated SQL is either
invalid or incorrect. Exactly what happens depends on the exact query, and
on the target database type, but I believe it all stems from the same
problem, which has to do with table aliasing.
If you need further details to reproduce this, please let me know. I'll be
glad to help in any way I can to get this situation remedied quickly, as I
am depending on this functionality. I have a test application to
demonstrate the problem.
I'm using Kodo 3.3.3 and application identity.
Paul Mogren
CommerceHub -
Why update with subqueries does not have cost and cardinality?
There is update.
update test t1 set dummy = (select dummy from test2 t2 where t1.id = t2.id);Both tables which have actual statistics. Each has 1000 rows. And column ID have values from 1 to 1000 in each table.
This is explain plan
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | UPDATE STATEMENT | | 1000 | 13000 | 426 (9)| 00:00:01 |
| 1 | UPDATE | TEST | | | | |
| 2 | TABLE ACCESS FULL| TEST | 1000 | 13000 | 426 (9)| 00:00:01 |
|* 3 | TABLE ACCESS FULL| TEST2 | 1 | 13 | 426 (9)| 00:00:01 |
Predicate Information (identified by operation id):
3 - filter("T2"."ID"=:B1)We can see here, that Oracle consider subquery within update as once-executed subquery.
This is runtime plan
| Id | Operation | Name | Starts | E-Rows | A-Rows |
| 1 | UPDATE | TEST | 1 | | 0 |
| 2 | TABLE ACCESS FULL| TEST | 1 | 1000 | 1000 |
|* 3 | TABLE ACCESS FULL| TEST2 | 1000 | 1 | 1000 |
Predicate Information (identified by operation id):
3 - filter("T2"."ID"=:B1)Why first plan does not have cost in step 1?
Does Oracle always not understand that update with subqueries will performed as NL or filter? In other words that step 3 will executed many times.
Or it is my bug (or what?)?793769 wrote:
Does Oracle always not understand that update with subqueries will performed as NL or filter? In other words that step 3 will executed many times.
Or it is my bug (or what?)?It's not possible to say whether this is a bug or a deliberate choice.
Because of "subquery caching" (see http://jonathanlewis.wordpress.com/2006/11/06/filter-subqueries/ ) the optimizer cannot predict how often the subquery will have to run. So possibly it shows nothing rather than showing the best or worst cases or a pure guess.
Regards
Jonathan Lewis -
How does oracle execute a correlated subquery .... some confusion
How does oracle 10g execute a correlated subquery?
I read some articles online & i am a little confused.
example:
select * from emp e
where e.deptno in (select d.deptno from dept d
where e.deptno = d.deptno);
My questions .......
1.In the above example, does oracle read the entire outer table first and then run the inner query using the rows returned by the outer query?
I read in some articles that they execute simultaneously.
How does this work?
2.Should the inner query have lesser amount of rows compared to the outer query for a good performance?
3.Can every correlated subquery be converted to a join and if so which one to use?
Truly appreciate any inputs on how oracle executes it at the backend.
Thanks in advance.user10541890 wrote:
How does oracle 10g execute a correlated subquery?
I read some articles online & i am a little confused.
example:
select * from emp e
where e.deptno in (select d.deptno from dept d
where e.deptno = d.deptno);
My questions .......
1.In the above example, does oracle read the entire outer table first and then run the inner query using the rows returned by the outer query?
I read in some articles that they execute simultaneously.
How does this work?SQL is not a procedural language. SQL code specifies what the system sill do, not how the system wlll do it; that's entirely up to the system.
What does it matter to you whether the two are done together, or if one is completed before the other begins?
The system will probably choose to run ucorellated subqueiris only once, and correlated queries multiple times as needed.
2.Should the inner query have lesser amount of rows compared to the outer query for a good performance?That usually doesn't matter.
It some cases, you may want to consider whether the subquery is correlated or not. If the subquery is very costly, and produces, say, 1 million rows, but you know the main query will only produce about 5 rows, then you may want to do a correlated subquery rather than an uncorrelated one.
3.Can every correlated subquery be converted to a join and if so which one to use?I believe so.
Use whichever is easier to code and debug. That will change depnding on the data and the requirements.
If performance is an issue, try different ways. Usually, where I've noticed a big difference, join was fastest.
By the way, it's unusual to have a correlated IN-subquery.
Usually IN-subqueris are uncorrelated, like this:
select *
from emp e
where e.deptno in ( select d.deptno
from dept d
);(This and the queries below produce the same resutls as your original query.)
Correlated subqueries are usually used for scalar subqueries or EXISTS subqueries, like this:
select *
from emp e
where EXISTS ( select d.deptno
from dept d
where e.deptno = d.deptno
);To do the same thing with a join:
select e.*
from emp e
join dept d on e.deptno = d.deptno
;assuming dept.deptno is unique.
Maybe you are looking for
-
Can anyone tell me why I can no longer download CAD from iTunes onto my Mac pro ?
Can anyone tell me why I can no longer download CAD from iTunes onto my MacBook Pro ?
-
Using Adobe My Sketch, I can no longer upload pictures from my Library. Why?
Using Adobe My Sketch, I can no longer upload pictures from my Library. Why?
-
How do I get audio back on single clip that loses audio when imported into Premiere Pro CC?
I've got one clip out of many that for some reason won't play any audio when imported into Premiere Pro. I am new to Premiere Pro so am hoping it's something stupid I've done, but this is a problem with just a single clip exported the same way as al
-
System Info reports the wrong OS and CPU. I'm on Windows7 using a dual core I3 CPU, but it reports Windows 2000 and a slow single core CPU. Might it be because one of my HDD has remnants of a W2000 system? In any event how do I fix Photoshop Elemen
-
PE11 issues with video playback.
I have a few issues I am trying to work through and need some help. First, I am trying to edit an old homemade DVD that used VOB files. First, all of the VOB files play correctly in Organizer andmy problems are with the editor. On one of the VOB