Join in update statement

can we use join in update statement?
here is the query which is giving me error
UPDATE      pol_int_name_multiple_v
SET      PMV.client_seq_nbr_i = 1
FROM     pol_int_name_multiple_v PMV
JOIN      pol_int_name PIV
ON      piv.int_name_id = pmv.int_name_id
WHERE      piv.client_id = 5
SQL> /
FROM pol_int_name_multiple_v PMV
ERROR at line 3:
ORA-00933: SQL command not properly ended
Message was edited by:
aadi

Yes, you can. The table with updateble columns must be a key preserved table. See http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adg03sch.htm#1044
Example:
SQL> CREATE TABLE A(A INTEGER PRIMARY KEY);
Table created.
SQL> INSERT INTO A VALUES(1);
1 row created.
SQL> INSERT INTO A VALUES(2);
1 row created.
SQL> COMMIT;
Commit complete.
SQL> CREATE TABLE B(
  2    A INTEGER,
  3    B INTEGER,
  4    FOREIGN KEY(A) REFERENCES A);
Table created.
SQL> INSERT INTO B(A, B) VALUES(1, 5);
1 row created.
SQL> INSERT INTO B(A, B) VALUES(2, 5);
1 row created.
SQL> INSERT INTO B(A, B) VALUES(2, 10);
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM B;
         A          B
         1          5
         2          5
         2         10
SQL> UPDATE
  2    (
  3      SELECT B.*
  4      FROM A JOIN B ON A.A = B.A
  5      WHERE B.A = 2
  6    )
  7    SET B = 333;
2 rows updated.
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM B;
         A          B
         1          5
         2        333
         2        333Regards,
Dima

Similar Messages

  • Using Case and Joins in update statement

    Hi all,
    I need to update one column in my table...but need to use case and joins...I wrote the query and it is not working
    I am getting an error msg saying...the SQL command not ended properly...
    I am not that good at SQL...Please help...
    update t1 a
    set a.name2=
    (case
    when b.msg2 in ('bingo') then '1'
    when b.msg2 in ('andrew') then '2'
    when b.msg2 in ('sam') then '3'
    else '4'
    end )
    from t1 a left outer join t2 b
    on a.name1 = b.msg1 ;
    Waiting for help on this...!
    Thanks in Advance... :)

    Another approach is to update an inline view defining the join:
    update
    ( select a.name2, b.msg2
      from   t1 a
      join   t2 b on b.msg1 = a.name1 ) q
    set q.name2 =
        case
          when q.msg2 = 'bingo' then '1'
          when q.msg2 = 'andrew' then '2'
          when q.msg2 = 'sam' then '3'
          else '4'
        end;which could also be rewritten as
    update
    ( select a.name2
           , case q.msg2
                when 'bingo'  then '1'
                when 'andrew' then '2'
                when 'sam'    then '3'
                else '4'
             end as new_name
      from   t1 a
      join   t2 b on b.msg1 = a.name1 ) q
    set name2 = new_name;The restriction is that the lookup (in this case, t2.msg1) has to be declared unique, via either a primary or unique key or unique index.
    (You don't strictly need to give the view an alias, but I used 'q' in case you tried 'a' or 'b' and wondered why they weren't recognised outside the view.)

  • Need help to write a query for Update statement with  join

    Hi there,
    The following update statement gives me error as the given table in set statement is invalid. But its the right table .
    Is the statement correct? Please help .
    update (
           select distinct(vpproadside.VEHICLE_CRED_OVERRIDE.vin)            
             from vpproadside.VEHICLE_CRED_OVERRIDE
             join vpproadside.vpp_vehicle
               on vpproadside.vpp_vehicle.vin = vpproadside.VEHICLE_CRED_OVERRIDE.vin
            where VPP_CARRIER_SEQ_NUMBER = 90
              and EXPIRY_DATE = '17-MAR-10'
       set vpproadside.VEHICLE_CRED_OVERRIDE.EXPIRY_DATE = '15-SEP-10';Edited by: Indhu Ram on Mar 12, 2010 1:00 PM
    Edited by: Indhu Ram on Mar 12, 2010 1:22 PM
    Edited by: Indhu Ram on Mar 12, 2010 2:35 PM
    Edited by: Indhu Ram on Mar 15, 2010 8:04 AM
    Edited by: Indhu Ram on Mar 15, 2010 8:06 AM
    Edited by: Indhu Ram on Mar 15, 2010 8:28 AM

    Ask Tom has very good discussion about this, if UPDATE does not work for PK issue, you can use MERGE
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:760068400346785797

  • Update statement with joining other tables

    Hi ,
    I have two table one is containing xml file , basically i need to read from those xml file then update to another table based on some condition.
    UPDATE TRCB_XBRL_STG_2 STG
    SET PROFIT =
      case when xbrl.isconsolidatedacc='Y' and EXTRACTVALUE(XBRL.XBRLFILE,'//PROFIT ', 'xmlns:acra="..."') is not null
      THEN EXTRACTVALUE(XBRL.XBRLFILE,'//PROFIT ', 'xmlns:acra="..."')
      WHEN XBRL.ISCONSOLIDATEDACC='N' AND EXTRACTVALUE(XBRL.XBRLFILE,'//PROFIT ', 'xmlns:acra="..') IS NOT NULL
      THEN extractValue(XBRL.xbrlfile,'//PROFIT ', 'xmlns:acra=".."')
      ELSE STG.PROFIT
      END,
      SET REVENUE=
      case when xbrl.isconsolidatedacc='Y' and EXTRACTVALUE(XBRL.XBRLFILE,'//REVENUE', 'xmlns:acra="..."') is not null
      THEN EXTRACTVALUE(XBRL.XBRLFILE,'//REVENUE.', 'xmlns:acra="..."')
      WHEN XBRL.ISCONSOLIDATEDACC='N' AND EXTRACTVALUE(XBRL.XBRLFILE,'//REVENUE', 'xmlns:acra="..') IS NOT NULL
      THEN extractValue(XBRL.xbrlfile,'//REVENUE', 'xmlns:acra="REVENUE"')
      ELSE STG.REVENUE
      END,
      ... (around 100 columns)
    FROM  TRCB_XBRL xbrl ,TRCB_XBRL_STG_2 STG
    WHERE STG.XBRL_ID = XBRL.XBRL_ID Number of columns are around 100 , please anyone suggest how to use update statement with joining two tables.

    Hi,
    If all the values needed to update a given row of table_x are coming from the same row of table_y (or from the same row of a result set of a query involving any number of tables), then you can do something like this:
    UPDATE  table_x  x
    SET     (col1, col2, col3, ...)
    =     (
             SELECT  NVL (y.col1, x.col1)
             ,         NVL (y.col2, x.col2)
             ,         NVL (y.col3, x.col3)
             FROM    table_y  y
             WHERE   x.pkey   = y.expr
             AND         ...
    WHERE   ...
    ;If the WHERE clause depends on the same row of table_y, then it will probably be simpler and more efficient to use MERGE instead of UPDATE.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Update statement with joins

    Hi all, consider the tables and data below
    CREATE TABLE table1 (id NUMBER, a NUMBER, b NUMBER) ;
    CREATE TABLE table2 (id NUMBER, c NUMBER, d NUMBER);
    INSERT INTO table1 VALUES(111,2,0);
    INSERT INTO table1 VALUES(111,1,2);
    INSERT INTO table1 VALUES(111,1,3);
    INSERT INTO table1 VALUES(222,1,3);
    INSERT INTO table2 VALUES(111,5,8);
    INSERT INTO table2 VALUES(222,6,7);
    what i want to do is write a UPDATE STATEMENT that joins the two tables BY id
    and update table1 rows. i want to include the following CASE statement
    UPDATE COLUMN a intable1 according to this logic
    case
    WHEN b >0
    THEN nvl(c,b)
    ELSE
    d
    END
    so table1 after the update should look like this
    id    a   b
    111   8   0
    111   5   2
    111   5   3
    222   6   3can somebody help write a update statement that update table1 according to case statement and joins both tables to get the values necessary? thanks

    Hooray for sample tables!
    SQL> alter table table2 add constraint table2_pk primary key (id);
    Table altered.
    SQL> update
      2     (select t1.a
      3            ,case when t1.b > 0 then nvl(t2.c, t1.b)
      4                  else t2.d
      5             end new_value
      6      from   table1 t1
      7      join   table2 t2
      8             on t1.id = t2.id
      9     )
    10  set a = new_value;
    4 rows updated.
    SQL> select * from table1;
                      ID                    A                    B
                     111                    8                    0
                     111                    5                    2
                     111                    5                    3
                     222                    6                    3

  • Update statement with inner join

    Hello everyone. I am am trying to do an update statement with an inner join. I have found several examples of SQL statements that work with Sql server and mysql but they don't work in Oracle. Does anyone know the proper way in Oracle 10G? I am trying to update all fields in one table from fields in another table.
    for example:
    UPDATE table3
    SET
    TL3.name = TL2.name,
    TL3.status = TL2.status,
    TL3.date = TL2.date
    FROM table3 TL3 JOIN table2 TL2
    ON (TL3.unique_id = TL2.unique_id);
    any help will be appreciated.

    Hi,
    You can also use MERGE, like this:
    MERGE INTO  table3     dst
    USING   (
             SELECT  unique_id
             ,         name
             ,         status
             ,         dt          -- DATE is not a good column name
             FROM    table2
         )          src
    ON     (dst.unique_id     = src.unique_id)
    WHEN MATCHED THEN UPDATE
    SET     dst.name     = src.name
    ,     dst.status     = src.status
    ,     dst.dt          = src.dt
    ;Unlike UPDATE, this lets you avoid essentially doing the same sub-query twice: once in the SET clause and then again in the WHERE clause.
    Like UPDATE, you don't acutally join the table being changed (table3 in this case) to the other table(s); that is, the FROM clause of the suib-query does not include table3.
    Riedelme is right; you'll get better response to SQL questions like this in the SQL and PL/SQL forum:
    PL/SQL

  • Update statement getting ORA-00904 invalid identifier

    I am getting this ORA error when I try to conduct an update statement from a column value in one table to a like-named column in another table.
    For instance, in my select, shown below, this query runs like a champ, returning all of my records
    SELECT
    b.ID,
    b.ZIP, a.ZIP,
    a.NAME,
    a.LOCATION
    FROM TBL_ARCHIVE a
    INNER JOIN TBL_UAT b ON
    a.ID = b.ID
    WHERE
    b.ID > 470000  And b.ID <470100;However, if I try to run an update statement with any of the following, I get this error. It seems so strange to me that I'd get an error using the same columns in the update statement, but would return the desired results effectively from the select statement!
    one version of UPDATE
    UPDATE TBL_ARCHIVE a
    SET a.ZIP = TBL_UAT.ZIP
    WHERE TBL_UAT.ID = a.ID;and another
    UPDATE TBL_ARCHIVE
    SET a.ZIP  =
    (SELECT b.ZIP
    FROM TBL_UAT b
    WHERE b.ID <472500 And b.ID >471000)
    FROM TBL_ARCHIVE a
    WHERE a.ID = b.ID)
    WHERE ID IN
    (SELECT ID
    FROM TBL_UAT b
    WHERE b.ID  <472500 And b.ID >471000
    );^ - this one produces a SQL not properly ended. Error ORA-00933: SQL command not properly ended.
    I'm really unsure though, how what I thought was a fairly basic update statement wouldn't work. I'm using Oracle 11g but through either Toad or SQL Plus. I've gotten these same errors in both.
    Though MS Access runs slow as snails, I can manage to run the update statement successfully with it, a thousand records or so at a time. Problem is, I've got about 300K records needing updating.
    I've looked around for similar problems but haven't found one where someone wasn't either using a reserved word for a column, which I'm not, I don't believe, or a problem that really dealt with this error in the context of an update statement.
    But I'd welcome any enlightenment on this.

    rp0428 wrote:
    UPDATE TBL_ARCHIVE a
    SET a.ZIP = TBL_UAT.ZIP
    WHERE TBL_UAT.ID = a.ID;That isn't a valid query and neither is the other one.
    Please post the actual query you are using and the actual complete error message you are getting (everything about the error that is displayed).^^
    That is NOT a valid query?
    How else would you have an UPDATE statement created to set the value of a column in table A to the value of a (in this case, same named) column in table B?
    And keep them in order to update the records appropriately?
    I'll append the create statements momentarily.
    Thanks!
    CREATE TABLE TBL_UAT
    ( ID NUMBER(6),
    ZIP VARCHAR2(10 BYTE) ) and
    CREATE TABLE TBL_ARCHIVE
    ( ID NUMBER(6) NOT NULL, NAME VARCHAR2(50 BYTE),
    EMAIL VARCHAR2(50 BYTE),
    LOCATION VARCHAR2(50 BYTE),
    DEPARTMENT VARCHAR2(50 BYTE),
    PRIORITY VARCHAR2(50 BYTE),
    APPROVING_MGR_NAME VARCHAR2(50 BYTE),
    TYPE1 VARCHAR2(50 BYTE),
    TYPE2 VARCHAR2(50 BYTE),
    CONTACT_NAME VARCHAR2(50 BYTE),
    CONTACT_PHN_NO VARCHAR2(50 BYTE),
    LOAN_NUM VARCHAR2(50 BYTE),
    REF_ID VARCHAR2(50 BYTE),
    BORROWER_NAME VARCHAR2(50 BYTE),
    ADDRESS VARCHAR2(50 BYTE),
    CITY VARCHAR2(50 BYTE),
    ST VARCHAR2(50 BYTE),
    ZIP VARCHAR2(10 BYTE),
    SALE_DATE DATE,
    COMMENTS VARCHAR2(800 BYTE),
    TIME_REQ DATE,
    ACCTLOC VARCHAR2(50 BYTE),
    OTHER_ACCTLOC VARCHAR2(50 BYTE)) Hope this can be of assistance.
    Thanks, folks!
    Edited by: user515689 on Feb 7, 2012 11:59 AM

  • How to convert the following FORALL Update to direct SQL UPDATE statement

    I have a FORALL loop to update a table. It is taking too long. I want to rewrite the code to a direct UPDATE sql. Also, any other tips or hints which can help run this proc faster?
    CURSOR cur_bst_tm IS
    SELECT listagg(tm, ' ') WITHIN GROUP(ORDER BY con_addr_id) best_time,
           con_addr_id
       FROM   (select Trim(Upper(con_addr_id)) con_addr_id,
                      ||decode(Initcap(start_day),
                                      'Monday', 'm',
                                    'Tuesday', 'tu',
                                    'Wednesday', 'w',
                                    'Thursday', 'th',
                                    'Friday', 'f',
                                     Initcap(start_day))
                      ||'='
                      ||trunc(( ( TO_DATE(start_tm,'HH12:MI:SS PM') - trunc(TO_DATE(start_tm,'HH12:MI:SS PM')) ) * 24 * 60 ))
                      ||','
                      ||trunc(( ( TO_DATE(end_tm,'HH12:MI:SS PM') - trunc(TO_DATE(end_tm,'HH12:MI:SS PM')) ) * 24 * 60 )) tm
               FROM   (SELECT DISTINCT * FROM ODS_IDL_EDGE_OFFC_BST_TM)
                 WHERE con_addr_id is not null)
      GROUP  BY con_addr_id
      ORDER BY con_addr_id;
    TYPE ARRAY IS TABLE OF cur_bst_tm%ROWTYPE;
    l_data ARRAY;
    BEGIN
    OPEN cur_bst_tm;
         LOOP
        FETCH cur_bst_tm BULK COLLECT INTO l_data LIMIT 1000;
        FORALL i IN 1..l_data.COUNT
          UPDATE ODS_CONTACTS_ADDR tgt
          SET best_times = l_data(i).best_time,
          ODW_UPD_BY = 'IDL - MASS MARKET',
           ODW_UPD_DT = SYSDATE,
          ODW_UPD_BATCH_ID = '0'
          WHERE Upper(edge_id) = l_data(i).con_addr_id
           AND EXISTS (SELECT 1 FROM ods_idl_edge_cont_xref src
                       WHERE tgt.contacts_odw_id = src.contacts_odw_id
                          AND src.pc_flg='Y')  
        EXIT WHEN cur_bst_tm%NOTFOUND;
        END LOOP;
      CLOSE cur_bst_tm;Record count:-
    select count(*) from
    ODS_IDL_EDGE_OFFC_BST_TM;
    140,000
    SELECT count(*)
    FROM ods_idl_edge_cont_xref src
    WHERE src.pc_flg='Y';
    118,000
    SELECT count(*)
    FROM ODS_CONTACTS_ADDR;
    671,925
    Database version 11g.
    Execution Plan for the update:
    Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
    UPDATE STATEMENT Optimizer Mode=ALL_ROWS          6 K          8120                     
    UPDATE     ODW_OWN2.ODS_CONTACTS_ADDR                                   
    HASH JOIN SEMI          6 K     256 K     8120                     
    TABLE ACCESS FULL     ODW_OWN2.ODS_CONTACTS_ADDR     6 K     203 K     7181                     
    TABLE ACCESS FULL     ODW_OWN2.ODS_IDL_EDGE_CONT_XREF     118 K     922 K     938
    Edited by: user10566312 on May 14, 2012 1:07 AM

    The code tag should be in lower case like this {noformat}{noformat}. Otherwise your code format will be lost.
    Here is a update statementupdate ods_contacts_addr tgt
    set (
              best_times, odw_upd_by, odw_upd_dt, odw_upd_batch_id
         ) =
              select best_time, odw_upd_by, odw_upd_dt, odw_upd_batch_id
              from (
                   select listagg(tm, ' ') within group(order by con_addr_id) best_time,
                        'IDL - MASS MARKET' odw_upd_by,
                        sysdate odw_upd_dt,
                        '0' odw_upd_batch_id,
                        con_addr_id
                   from (
                             select Trim(Upper(con_addr_id)) con_addr_id,
                                  ||decode(Initcap(start_day), 'Monday', 'm', 'Tuesday', 'tu', 'Wednesday', 'w', 'Thursday', 'th', 'Friday', 'f', Initcap(start_day))
                                  ||'='
                                  ||trunc(((TO_DATE(start_tm,'HH12:MI:SS PM')-trunc(TO_DATE(start_tm,'HH12:MI:SS PM')))*24*60 ))
                                  ||','
                                  ||trunc(((TO_DATE(end_tm,'HH12:MI:SS PM')-trunc(TO_DATE(end_tm,'HH12:MI:SS PM')))*24*60)) tm
                             FROM (
                                  select distinct * from ods_idl_edge_offc_bst_tm
                             WHERE con_addr_id is not null
                   group
                   by con_addr_id
              where upper(tgt.edge_id) = con_addr_id
    where exists
              SELECT 1
              FROM ods_idl_edge_cont_xref src
              WHERE tgt.contacts_odw_id = src.contacts_odw_id
              AND src.pc_flg='Y'
    and exists
              select null
              from (
                   SELECT listagg(tm, ' ') WITHIN GROUP(ORDER BY con_addr_id) best_time,
                        'IDL - MASS MARKET' odw_upd_by,
                        SYSDATE odw_upd_dt,
                        '0' odw_upd_batch_id,
                        con_addr_id
                   FROM (
                             select Trim(Upper(con_addr_id)) con_addr_id,
                                  ||decode(Initcap(start_day), 'Monday', 'm', 'Tuesday', 'tu', 'Wednesday', 'w', 'Thursday', 'th', 'Friday', 'f', Initcap(start_day))
                                  ||'='
                                  ||trunc(((TO_DATE(start_tm,'HH12:MI:SS PM')-trunc(TO_DATE(start_tm,'HH12:MI:SS PM')))*24*60 ))
                                  ||','
                                  ||trunc(((TO_DATE(end_tm,'HH12:MI:SS PM')-trunc(TO_DATE(end_tm,'HH12:MI:SS PM')))*24*60)) tm
                             FROM (
                                  SELECT DISTINCT * FROM ODS_IDL_EDGE_OFFC_BST_TM
                             WHERE con_addr_id is not null
                   GROUP
                   BY con_addr_id
              where upper(tgt.edge_id) = con_addr_id
    This is an untested code. If there is any syntax error then please fix it and try.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem in doing an update statement

    Hello all
    i should write an update statement,
    these tables : country: name,code,population,nextyearr_population ...
    nextyear_population is empty,at first i should get population_growth from population table then calculate the next year population according to corrent population and population_growth
    population: country(actually is code not name of country) ,population_growth,....
    i wrote so and i got this error
    Error starting at line 1 in command:
    update country c
    set c.nextyear_population=(c.population+ ((c.population*(select pop.population_growth from population pop join country co on co.code=pop.code))/100)
    where country.code=population.country
    Error at Command Line:4 Column:20
    Error report:
    SQL Error: ORA-00904: "POPULATION"."COUNTRY": invalid identifier
    00904. 00000 -  "%s: invalid identifier"
    *Cause:   
    *Action:
    --  File created - Wednesday-May-15-2013  
    --  DDL for Table COUNTRY
      CREATE TABLE "intern"."COUNTRY" ("NAME" VARCHAR2(40), "CODE" CHAR(2), "CAPITAL" VARCHAR2(40), "PROVINCE" VARCHAR2(40), "POPULATION" NUMBER, "AREA" NUMBER, "NEXTYEAR_POPULATION" NUMBER)
       COMMENT ON COLUMN "intern"."COUNTRY"."NAME" IS 'the country name'
       COMMENT ON COLUMN "intern"."COUNTRY"."CODE" IS 'the internet country code (two letters)'
       COMMENT ON COLUMN "intern"."COUNTRY"."CAPITAL" IS 'the name of the capital'
       COMMENT ON COLUMN "intern"."COUNTRY"."PROVINCE" IS 'the province where the capital belongs to'
       COMMENT ON COLUMN "intern"."COUNTRY"."POPULATION" IS 'the population number'
       COMMENT ON COLUMN "intern"."COUNTRY"."AREA" IS 'the total area'
       COMMENT ON TABLE "intern"."COUNTRY"  IS 'the countries of the world with some data'
    REM INSERTING into intern.COUNTRY
    SET DEFINE OFF;
    Insert into intern.COUNTRY (NAME,CODE,CAPITAL,PROVINCE,POPULATION,AREA,NEXTYEAR_POPULATION) values ('Andorra','ad','Andorra la Vella','Andorra la Vella',69865,468,null);
    Insert into intern.COUNTRY (NAME,CODE,CAPITAL,PROVINCE,POPULATION,AREA,NEXTYEAR_POPULATION) values ('United Arab Emirates','ae','Abu Dhabi','Abu Dhabi',2523915,82880,null);
    Insert into intern.COUNTRY (NAME,CODE,CAPITAL,PROVINCE,POPULATION,AREA,NEXTYEAR_POPULATION) values ('Afghanistan','af','Kabul','Kabul',28513677,647500,null);
    --  File created - Wednesday-May-15-2013  
    --  DDL for Table POPULATION
      CREATE TABLE "intern"."POPULATION" ("COUNTRY" CHAR(2), "POPULATION_GROWTH" NUMBER, "INFANT_MORTALITY" NUMBER)
       COMMENT ON COLUMN "intern"."POPULATION"."COUNTRY" IS 'the country code'
       COMMENT ON COLUMN "intern"."POPULATION"."POPULATION_GROWTH" IS 'population growth rate (percentage, per annum)'
       COMMENT ON COLUMN "intern"."POPULATION"."INFANT_MORTALITY" IS 'infant mortality (per thousand)'
       COMMENT ON TABLE "intern"."POPULATION"  IS 'information about the population of the countries'
    REM INSERTING into intern.POPULATION
    SET DEFINE OFF;
    Insert into intern.POPULATION (COUNTRY,POPULATION_GROWTH,INFANT_MORTALITY) values ('ad',0.95,4.05);
    Insert into intern.POPULATION (COUNTRY,POPULATION_GROWTH,INFANT_MORTALITY) values ('ae',1.54,14.51);
    Insert into intern.POPULATION (COUNTRY,POPULATION_GROWTH,INFANT_MORTALITY) values ('af',4.77,163.07);thank you in advance
    im using oracle11g and ubuntu 12
    best,david

    Hi, David,
    Thanks for posting the CREATE TABLE and INSERT statements.
    Don't forget to post the results you want from thatsample data (that is, the contents of country after everything is finished).
    1003209 wrote:
    ... i wrote so and i got this error
    Error starting at line 1 in command:
    update country c
    set c.nextyear_population=(c.population+ ((c.population*(select pop.population_growth from population pop join country co on co.code=pop.code))/100)
    where country.code=population.country
    Error at Command Line:4 Column:20
    Error report:
    SQL Error: ORA-00904: "POPULATION"."COUNTRY": invalid identifier
    00904. 00000 -  "%s: invalid identifier"
    In the UPDATE statement itself (outside of sub-queries) you can only reference the table being UPDATEd, but in the WHERE clause:
    where country.code=population.countryyou're trying to reference another table, population. That's what caused the error.
    You either need another sub-query, or MERGE, which will probably be simpler and more efficient than UPDATE.

  • SQL Update statement taking too long..

    Hi All,
    I have a simple update statement that goes through a table of 95000 rows that is taking too long to update; here are the details:
    Oracle Version: 11.2.0.1 64bit
    OS: Windows 2008 64bit
    desc temp_person;
    Name                                                                                Null?    Type
    PERSON_ID                                                                           NOT NULL NUMBER(10)
    DISTRICT_ID                                                                     NOT NULL NUMBER(10)
    FIRST_NAME                                                                                   VARCHAR2(60)
    MIDDLE_NAME                                                                                  VARCHAR2(60)
    LAST_NAME                                                                                    VARCHAR2(60)
    BIRTH_DATE                                                                                   DATE
    SIN                                                                                          VARCHAR2(11)
    PARTY_ID                                                                                     NUMBER(10)
    ACTIVE_STATUS                                                                       NOT NULL VARCHAR2(1)
    TAXABLE_FLAG                                                                                 VARCHAR2(1)
    CPP_EXEMPT                                                                                   VARCHAR2(1)
    EVENT_ID                                                                            NOT NULL NUMBER(10)
    USER_INFO_ID                                                                                 NUMBER(10)
    TIMESTAMP                                                                           NOT NULL DATE
    CREATE INDEX tmp_rs_PERSON_ED ON temp_person (PERSON_ID,DISTRICT_ID) TABLESPACE D_INDEX;
    Index created.
    ANALYZE INDEX tmp_PERSON_ED COMPUTE STATISTICS;
    Index analyzed.
    explain plan for update temp_person
      2  set first_name = (select trim(f_name)
      3                    from ext_names_csv
      4                               where temp_person.PERSON_ID=ext_names_csv.p_id
      5                               and   temp_person.DISTRICT_ID=ext_names_csv.ed_id);
    Explained.
    @?/rdbms/admin/utlxpls.sql
    PLAN_TABLE_OUTPUT
    Plan hash value: 3786226716
    | Id  | Operation                   | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | UPDATE STATEMENT            |                | 82095 |  4649K|  2052K  (4)| 06:50:31 |
    |   1 |  UPDATE                     | TEMP_PERSON    |       |       |            |          |
    |   2 |   TABLE ACCESS FULL         | TEMP_PERSON    | 82095 |  4649K|   191   (1)| 00:00:03 |
    |*  3 |   EXTERNAL TABLE ACCESS FULL| EXT_NAMES_CSV  |     1 |   178 |    24   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - filter("EXT_NAMES_CSV"."P_ID"=:B1 AND "EXT_NAMES_CSV"."ED_ID"=:B2)
    Note
       - dynamic sampling used for this statement (level=2)
    19 rows selected.By the looks of it the update is going to take 6 hrs!!!
    ext_names_csv is an external table that have the same number of rows as the PERSON table.
    ROHO@rohof> desc ext_names_csv
    Name                                                                                Null?    Type
    P_ID                                                                                         NUMBER
    ED_ID                                                                                        NUMBER
    F_NAME                                                                                       VARCHAR2(300)
    L_NAME                                                                                       VARCHAR2(300)Anyone can help diagnose this please.
    Thanks
    Edited by: rsar001 on Feb 11, 2011 9:10 PM

    Thank you all for the great ideas, you have been extremely helpful. Here is what we did and were able to resolve the query.
    We started with Etbin's idea to create a table from the ext table so that we can index and reference easier than an external table, so we did the following:
    SQL> create table ext_person as select P_ID,ED_ID,trim(F_NAME) fst_name,trim(L_NAME) lst_name from EXT_NAMES_CSV;
    Table created.
    SQL> desc ext_person
    Name                                                                                Null?    Type
    P_ID                                                                                         NUMBER
    ED_ID                                                                                        NUMBER
    FST_NAME                                                                                     VARCHAR2(300)
    LST_NAME                                                                                     VARCHAR2(300)
    SQL> select count(*) from ext_person;
      COUNT(*)
         93383
    SQL> CREATE INDEX EXT_PERSON_ED ON ext_person (P_ID,ED_ID) TABLESPACE D_INDEX;
    Index created.
    SQL> exec dbms_stats.gather_index_stats(ownname=>'APPD', indname=>'EXT_PERSON_ED',partname=> NULL , estimate_percent=> 30 );
    PL/SQL procedure successfully completed.We had a look at the plan with the original SQL query that we had:
    SQL> explain plan for update temp_person
      2  set first_name = (select fst_name
      3                    from ext_person
      4                               where temp_person.PERSON_ID=ext_person.p_id
      5                               and   temp_person.DISTRICT_ID=ext_person.ed_id);
    Explained.
    SQL> @?/rdbms/admin/utlxpls.sql
    PLAN_TABLE_OUTPUT
    Plan hash value: 1236196514
    | Id  | Operation                    | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | UPDATE STATEMENT             |                | 93383 |  1550K|   186K (50)| 00:37:24 |
    |   1 |  UPDATE                      | TEMP_PERSON    |       |       |            |          |
    |   2 |   TABLE ACCESS FULL          | TEMP_PERSON    | 93383 |  1550K|   191   (1)| 00:00:03 |
    |   3 |   TABLE ACCESS BY INDEX ROWID| EXTT_PERSON    |     9 |  1602 |     1   (0)| 00:00:01 |
    |*  4 |    INDEX RANGE SCAN          | EXT_PERSON_ED  |     1 |       |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       4 - access("EXT_PERSON"."P_ID"=:B1 AND "RS_PERSON"."ED_ID"=:B2)
    Note
       - dynamic sampling used for this statement (level=2)
    20 rows selected.As you can see the time has dropped to 37min (from 6 hrs). Then we decided to change the SQL query and use donisback's suggestion (using MERGE); we explained the plan for teh new query and here is the results:
    SQL> explain plan for MERGE INTO temp_person t
      2  USING (SELECT fst_name ,p_id,ed_id
      3  FROM  ext_person) ext
      4  ON (ext.p_id=t.person_id AND ext.ed_id=t.district_id)
      5  WHEN MATCHED THEN
      6  UPDATE set t.first_name=ext.fst_name;
    Explained.
    SQL> @?/rdbms/admin/utlxpls.sql
    PLAN_TABLE_OUTPUT
    Plan hash value: 2192307910
    | Id  | Operation            | Name         | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | MERGE STATEMENT      |              | 92307 |    14M|       |  1417   (1)| 00:00:17 |
    |   1 |  MERGE               | TEMP_PERSON  |       |       |       |            |          |
    |   2 |   VIEW               |              |       |       |       |            |          |
    |*  3 |    HASH JOIN         |              | 92307 |    20M|  6384K|  1417   (1)| 00:00:17 |
    |   4 |     TABLE ACCESS FULL| TEMP_PERSON  | 93383 |  5289K|       |   192   (2)| 00:00:03 |
    |   5 |     TABLE ACCESS FULL| EXT_PERSON   | 92307 |    15M|       |    85   (2)| 00:00:02 |
    Predicate Information (identified by operation id):
       3 - access("P_ID"="T"."PERSON_ID" AND "ED_ID"="T"."DISTRICT_ID")
    Note
       - dynamic sampling used for this statement (level=2)
    21 rows selected.As you can see, the update now takes 00:00:17 to run (need to say more?) :)
    Thank you all for your ideas that helped us get to the solution.
    Much appreciated.
    Thanks

  • Help on update statement in Apply DML Handler

    I followed the example given in Streams document.
    The document has the code for converting DELETE on the source to INSERT on the target. I added the dml handler code INSERT and UPDATE statements also.
    In DELETE, INSERT, UPDATE dml handler code, I am setting the command type to 'INSERT' so that I can insert the data in the target table.
    It is working fine for DELETE and INSERT statements.
    When I do update on the source table,
    I see only the value for the column I updated and all other columns are showing blank. May be this is the normal behaviour. How do I see the values for entire record. Do I need to join the source table based on the key column to get the data for the columns that were not updated.
    Also, I thought I should at least see the values for key column and updated column in the target table. It only shows the value for updated column but not for key column. But, When I choosed the old values (I know we need new values, but I just did it for test purpose) in the UPDATE DML handler, it shows the values for key column and the updated column.
    When I read the data in the LCR record using get_value('old', 'EMPLOYEE_ID') and get_value('NEW', 'FIRST_NAME')
    for key column, it shows the value in both old and new. I do not understand why it is not inserting the key column value in the target table.
    Thanks for your help in advance.
    Best regards,

    I forgot to mention these things.
    We added supplmental logging using alter database add supplemental log data (primary key, unique index) columns;
    I also added the supplemental logging on the source key column (employee_id) using ALTER TABLE emp ADD SUPPLEMENTAL LOG GROUP log_group_emp_pk (employee_id) ALWAYS;
    I also set the key column on the target table using DBMS_APPLY_ADM.SET_KEY_COLUMNS.
    Thanks for your help in advance.
    Best regards,

  • Update Statement Help Please

    I'm coming from the MS SQL world LOL
    and Im trying to write an update statement but in Oracle there is no INNER JOIN.
    Can you give me some advice on how to do this please?
    UPDATE employee
    SET employee.name = tmpuser.name
    FROM employee
    INNER JOIN tmpuser
    on tmpuser.emp_id = employtee.emp_id
    Thank you for you help.
    P

    Hi,
    AJR wrote:
    Frank,
    But when we are using the where condition it should update records with the matching ids. right?What your query should do is entirely up to you; I can't answer any questions about that, only you can.
    I have faced this issue earlier.
    WHERE       tmpuser.emp_id = employee.emp_idCan you explain?Not out of context. Post a complete statement.
    If this isn't directly related to user9170886's problem, then it's better to start your own thread.
    I can say a few things about UPDATE statements in general:
    The WHERE clause governs which rows will be UPDATEd. If there is no WHERE clause, all rows in the table will be UPDATEd.
    So
    UPDATE     employee
    SET     employee_name = ( <subquery> )
    ;UPDATEs every row in employee, because the UPDATE statement does not have a WHERE clause. Nothing in the sub-query can change that.
    A sub-query can reference values from its immediate parent, but a parent can't reference values from a sub-query (other than the values actually returned by the sub-query, of course).
    So
    UPDATE     employee
    SET     employee_name = ( <subquery> )
    WHERE     tmpuser.emp_id     = employee.emp_id
    ;causes an error, because there is no table called tmpuser in the main UPDATE statement. Nothing in the sub-query can change that.

  • Update statement help

    Hello folks,
    I need some help/advise on an UPDATE statement.
    I have two tables. I need to join these tables and update a field in table1 with a field from table2.
    Please see the attached jpg file.
    The first 3 coloumns are from table1 and last 2 columns in the picture are from table2.
    I want to update NEXT_RATE_RESET_ADJ_P field (from table1) with NEXT_RESET_DATE_ADJUSTED field (from table2). I want to join them between table1.DEAL_LEG_ID_P and table2.DEAL_LEG_ID.
    I have never written update statement with a join in it.
    Any help is greatly appreciated.

    UPDATE EMP1
    SET EMP1.SAL =
    (SELECT EMP2.SAL
    FROM EMP2
    WHERE EMP1.EMPNO = EMP2.EMPNO
    AND EMP1.DEPTNO = EMP2.DEPTNO)
    WHERE EMP1.JOB = 'SALESMAN';
    To avoid setting EMP1.SAL to NULL if there is no matching EMP2 record
    UPDATE EMP1
    SET EMP1.SAL =
    (SELECT EMP2.SAL
    FROM EMP2
    WHERE EMP1.EMPNO = EMP2.EMPNO
    AND EMP1.DEPTNO = EMP2.DEPTNO)
    WHERE EMP1.JOB = 'SALESMAN'
    AND EXISTS (SELECT NULL
    FROM EMP2
    WHERE EMP1.EMPNO = EMP2.EMPNO
    AND EMP1.DEPTNO = EMP2.DEPTNO);

  • Update statement issue

    Whenever I join two tables in update statement
    following error occures ,However all columns exist
    update bio1
    set appl_uid = demdata.appl_uid
    where bio1.cnic = demdata.cnic
    ora-00904 demdataid.cnic invalid indentifier

    no dear i am at the SQLPLUS prompt and i had the access the of of both of these tables and demdata is the table and appl_uid id is the column, i am just trying to update first_table.appl_uid column with the join of 2nd tables's appl_uid column on the basis of the common field CNIC in between both of these tables, the most simplest update is not working, i am getting late from lunch, plz help
    Regards,

  • Update statement not working PL/SQL block

    Hi friends,
    My code is written the following way:
    declare
    var1 number;
    var2....
    Cursor c1 <select something>;
    Cursor c2 <select something>
    Begin
    Insert into table1 <different values>;
    Commit;
    /* first update statement */
    Update table1 set table1.col3 = (select col3 from table2 where table2.col1 = table1.col1 and table2.col2 = table1.col2);
    commit ;
    /* 2nd update statement */
    update table1 set table1.col4 = (select col4 from table3 where table3.col1 = table1.col1 and table3.col2 = table1.col2);
    commit ;
    for r2 in c2 loop
    update table1
    end loop;
    end;
    This code works till 1st update statement. But after that, even if I let my code run overnight, nothing happens. There are appropriate indexes on tables where join is done. All tables are in one schema.
    What could be the reason?

    darshilm wrote:
    /* first update statement */
    Update table1 set table1.col3 = (select col3 from table2 where table2.col1 = table1.col1 and table2.col2 = table1.col2);This is an unconstrained updated - meaning that it instructs the database that every single row in TABLE1 needs to be updated.
    For every single row, the "update" SQL has to be executed and a SELECT performed on TABLE2.
    Let's say there are a 100,000 rows in TABLE1. This means that the SELECT to find the updated value has to be executed a 100,000 times.
    Let's say that there are a 200,000 rows in TABLE2. This means that each time that SELECT runs, it potentially hits 200,000 rows. Does it do it via a full table scan? Index range scan?
    At what cost? Hitting the very same data set again and again and again, 100,000 times in a row.
    And that is only the start of your code... and you wonder why it does not seem to finish?
    Data processing in a RDBMS is about how to do the minimal amount of I/O to achieve the desired result. For example, instead of hitting TABLE2 100,000 times, you can write code to hit it once by joining it with TABLE1 and creating an "updateable view" of TABLE1 that can be updated with the join values of TABLE2.
    You also seem to use PL/SQL cursors to perform row-row (and slow-by-slow) processing. This typically pulls data from the SQL engine into the PL engine and then push that very same data from the PL engine to the SQL engine.. It is a lot faster and more efficient (and scalable) to rather stay inside the SQL engine and do data set processing there (as oppose to row-by-row on the client side).
    Performance in a RDBMS is primarily determined by the designer and the developer... are functions of how well designed the data model is, and how well designed and written the code is.

Maybe you are looking for