Update with use of subquery

I'd like to update all the rows with values getting from subquery from the same table.
For example, the subquery of
select id, some_manipulation as value from table_a
id value
1 12
2 14
3 16
4 21
I'd like to use above info update the values of a column (column2 of table_a) according to the same id. Something like this
update table_a a
set a.column2 = b.value
where a.id =
(select b.id from table_a b);
I know above sql sytax is invalid, but I just want to give you an idea what I'm tryig to accomplish. Any idea?
Thanks in advance,
Ittichai

A slightly modified version of Sri's solution will work for all cases. Assuming proper indexing, this should be relatively fast.
SQL>SELECT * FROM table_a;
              ID             COL1             COL2
               1                2                0
               2                3                0
               3                1               15
SQL>SELECT * FROM table_b;
              ID             COLA
               1                6
               2               12
SQL>UPDATE table_a a
  2  SET col2 = nvl((SELECT a.col1*b.cola
  3              FROM table_b b
  4              WHERE a.id = b.id),a.col2);
3 rows updated.
SQL>commit;
Commit complete.
SQL>SELECT * FROM table_a;
              ID             COL1             COL2
               1                2               12
               2                3               36
               3                1               15In the case of table_b not having the id, the current value of col2 will be retained. If you want some other value, then substitute it in the NVL. You can even use a different select statement as the return from nvl.
SQL>UPDATE table_a a
  2  SET col2 = nvl((SELECT a.col1*b.cola
  3              FROM table_b b
  4              WHERE a.id = b.id),(SELECT col2 from table_a where id = 2));
3 rows updated.
SQL>commit;
Commit complete.
SQL>SELECT * FROM table_a;
              ID             COL1             COL2
               1                2               12
               2                3               36
               3                1               36

Similar Messages

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to make system update with "use automatic configuration script" and an URL

    Hello,
    all our laptop using "use automatic configuration script" with an "accelerated_pac_base.pac" prxy setting.
    How can we make system update work with that ?
    And no way for us to by pass this proxy settings with
    Thanks

    I mean there is no general method which is capable of correcting all possible errors found by schema validation.
    For example if the validation says it expected to find an <organization> element or a <company> element but it found a <banana> element, there is no way to determine what repair is necessary.
    Anyway the requirement is fighting against the way things work in the real world. The purpose of validation is just to find out whether a document matches a schema. If it doesn't, then too bad. Send it back to be fixed or replaced. If you are having a problem because you repeatedly get documents which don't quite match your schema, then you need to train the users to produce valid documents or to give them tools which help them do that.

  • 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

  • How do i uninstall iphoto? it was preinstalled on my macbook pro when I bought it used and I can only update with the previous owners password.

    how do i uninstall iphoto? it was preinstalled on my macbook pro when I bought it used and I can only update with the previous owners password.

    Do you have the current MacOS X version 10.10.2?
    Then you can simply move iPhoto from the Applications folder to the Trash,
    sign into the App Store with your own AppleID
    reload the "Featured" main page of the AppStore with ⌘R,
    then download iPhoto with your own AppleID.
    Make a backup of your iPhoto Library, before your launch the new iPhoto the first time,
    If your current system is not Yosemite, you can only buy a boxed iLife 11 version of iPhoto to install it independent of the previous owner.

  • HT4623 I have an IPhone4 and is updated with version 6.1.3 and I am not able to connect with face time calls. I have checked the date ant time. I used to be able to use face time with no problem. since the late os upgrace I have not been able to connect w

    I have an IPhone4 and is updated with version 6.1.3 and I am not able to connect with face time calls. I have checked the date ant time. I used to be able to use face time with no problem. Since the late os upgrace I have not been able to connect with face time.

    Read http://support.apple.com/kb/ts3367

  • Exception calling "Update" with "0" argument(s): "To add an item to a document library, use SPFileCollection.Add()"

    Hi i am trying to add a new item and update existing field value in a document library with powershell 
    but i receive below error message.
    PS C:\Users\spfarm> C:\Scripts\add.ps1
    Exception calling "Update" with "0" argument(s): "To add an item to a document
    library, use SPFileCollection.Add()"
    At C:\Scripts\add.ps1:24 char:16
    + $newItem.Update <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException
    #Add SharePoint PowerShell Snapin which adds SharePoint specific cmdlets
    Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
    #Variables that we are going to use for list editing
    $webURL = "http://tspmcwfe:89"
    $listName = "test"
    #Get the SPWeb object and save it to a variable
    $web = Get-SPWeb $webURL
    #Get the SPList object to retrieve the "Demo List"
    $list = $web.Lists[$listName]
    #Create a new item
    $newItem = $list.Items.Add()
    #Add properties to this list item
    $newItem["Title"] = "My second item!"
    $newItem["Info"] = "s15"
    #Update the object so it gets saved to the list
    $newItem.Update()
    $web.Dispose()
    adil

    Hi Adil,
    Document Library is different from a normal list. The document library contains files inside it. You need to update the code to add a document to the library. Then you can get hold of the List Item represented by that file and update its properties. Here
    is an example:
    $WebURL = "http://aissp2013/sites/TestSite"
    $DocLibName = "Docs" 
    $FilePath = "c:\blogs.txt" 
    # Get a variable that points to the folder 
    $Web = Get-SPWeb $WebURL 
    $List = $Web.GetFolder($DocLibName) 
    $Files = $List.Files
    # Get just the name of the file from the whole path 
    $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
    # Load the file into a variable 
    $File= Get-ChildItem $FilePath
    # Upload it to SharePoint 
    $spFile = $Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$false) 
    $item = $spFile.Item
    $item["Title"] = "New Title"
    $item.Update()
    $web.Dispose()
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • After updating with ios7, I cannot proceed because I cannot enter my password since it uses Greek letters but the keyboard available is Latin. How can I change the keyboard to Greek?

    After updating with ios7, I cannot proceed because I cannot enter my password since it uses Greek letters but the keyboard available is Latin. How can I change the keyboard to Greek?

    try tapping holding on the key that would be most similar to the letter you want to enter, that will bring up a menu of other characters similar to that character and maybe the greek letter will be included in that menu

  • 'Missing select' error for update statement using WITH clause

    Hi,
    I am getting the below error for update statement using WITH clause
    SQL Error: ORA-00928: missing SELECT keyword
      UPDATE A
      set A.col1 = 'val1'
         where
      A.col2 IN (
      WITH D AS
      SELECT col2 FROM
      (SELECT col2, MIN(datecol) col3 FROM DS
      WHERE <conditions>
        GROUP BY PATIENT) D2
      WHERE
      <conditions on A.col4 and D2.col3>

    Hi,
    The format of a query using WITH is:
    WITH  d  AS
        SELECT  ...  -- sub_query
    SELECT  ...   -- main query
    You don't have a main query.  The keyword FROM has to come immediately after the right ')' that ends the last WITH clause sub-query.
    That explains the problem based on what you posted.  I can't tell if the real problem is in the conditions that you didn't post.
    I hope this answers your question.
    If not, post a complete test script that people can run to re-create the problem and test their ideas.  Include 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: https://forums.oracle.com/message/9362002

  • I have bought a iphone 4s from uk. but i face problem in using sim on it. this is updated with 6.0.1 version. this phone also hve a chip in sim plate. now how could i use it?

    i have bought a iphone 4s from uk. but i face problem in using sim on it. this is updated with 6.0.1 version. this phone also have a chip in sim plate. now how could i use it?

    Where did you purchase in UK and is the iPhone carrier locked ??

  • [Bug] July 15th update ruined using the PS4 with XBR-55X850C...

    So the new July 15th update for Sony's 2015 Android TVs came with Dualshock 4 integration on the Home Screen and the new Playstation Now app. The bad part is that now it conflicts with using the Dualshock 4 for ONLY Playstation 4, not Playstation Now. Before this update, when there wasn't a new Dualshock 4 bluetooth pairing option for the TV there was no problems. So if I turn on my PS4. Switch to HDMI 1 which is the PS4 input. Then grab my Dualshock 4 controller and turn it on, a few seconds later I am brought to the Home Menu of the TV on the new Dualshock 4 Pairing settings page. I am asked to pair the controller with my TV (the TV not the PS4). If I say no I don't want to pair the DS4 with the TV as a secondary remote, then my DS4 will not turn on. I have to say yes for it to power on. When I pair it as a secondary remote for the TV and go back to my PS4 then there are a bunch of problems. With it paired, back on the PS4 HDMI 1 input the DS4 controller will register a few button presses on the DS4 controller as buttons/functions for the TV and PSNow app. So if I hold the Playstation button (on the PS4 HDMI 1 input) then instead of bringing me back to the Playstation 4 settings menu to (like power options to turn it off etc), I am instead now taken to the PSNow app on my TV home screen. So it changes input from HDMI 1 to the Home Screen and opens up the PSNow app...... If I press options while on my DS4 while on PS4's HDMI 1 input, instead of giving me the normal PS4 options menu, it instead opens up the TV's action menu. If I press on my DS4's touchpad it takes me to the TV Home Screen and also functions as a Back button for the TV..... This makes navigating the PS4 (opening games, using the options menu, closing games, turning off the PS4) impossible/confusing.  It's dissapointing to see this bug especially from Sony who makes this TV and the PS4 console. You would think they would check for compatibility conflicts before pushing updates to users. So I'm screwed out of using my PS4 until a new update comes out to fix this. Knowing the update schedule for the past few updates, that will probably take a few weeks.  Hopefully a community manager can forward this to the Sony TV team so they can patch this soon.  

  • SQL 2008, Update using multiple SubQuery

    Hello Experts , 
    I WANT TO DO THIS UPDATE WITHOUT USING CTE
    I have Two Table  REGION and AREA 
    REGION TABLE HAVE VALUE LIKE 
    Create Table REGIONtbl (REGION varchar(20),SomeArea varchar(20))
    Insert into REGIONtbl
    select 'REGION1','' union all
    select 'REGION2','' union all
    select 'REGION3','' 
    select *  from REGION
    OTHER table is AREA
    Create Table AREAtbl(AREAS  varchar(20))
    Insert into Areatbl
    select 'area1','' union all
    select 'area2','' union all
    select 'area3','' 
    I want to upadte AREAs in SomeArea column of Region Table ,
    I Need to first create autoincrement column in both Table using Row_Number function  and Upadte "SOMEAREA" column with "Areas" column 
    where ever ROW_Number ID of both the Table match 
    I tried below but did not work..
    UPDATE MASTER 
    SET MASTER.somearea =ar.areas
    FROM 
    SELECT Row_number() over (order by REGION) RN,
    REGION, somearea FROM REGIONtbl
    ) AS MASTER
    SELECT areas, ROW_NUMBER() OVER (ORDER BY areas)RNa
    FROM areatbl
    )AR
    where MASTER.rn=ar.rna
    HELP ?

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You have no idea.
    Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I want to do this update without using CTE <<
    Why? Is that part of a homework assignment? 
    >> I have Two Tables REGION [sic] and AREA [sic] <<
    No, tables are sets so their names plural or collective nouns. Putting “tbl” in a name is called “tibble”, a common design flaw that we laugh at. Look for Phil Factor’s humor column on this. 
    Here is my guess at what you should have posted in order to do this the way you want to do it.
    CREATE SEQUENCE Region_Garbage
    AS INTEGER 
    START WITH 1 
    INCREMENT BY 1;
    CREATE SEQUENCE Area_Garbage
    AS INTEGER 
    START WITH 1 
    INCREMENT BY 1;
    CREATE TABLE Regions
    (region_name VARCHAR(20) NOT NULL PRIMARY KEY, 
     region_seq INTEGER NOT NULL,
     area_name VARCHAR(20) DEFAULT '' NOT NULL);
    INSERT INTO Regions (region_name, region_seq) 
    VALUES ('region_name1', NEXT VALUE FOR Region_Garbage);
    INSERT INTO Regions (region_name, region_seq) 
    VALUES ('region_name2', NEXT VALUE FOR Region_Garbage);
    INSERT INTO Regions (region_name, region_seq) 
    VALUES ('region_name3', NEXT VALUE FOR Region_Garbage);
    CREATE TABLE Areas
    (area_name VARCHAR(20) NOT NULL PRIMARY KEY,
     area_seq INTEGER NOT NULL);
    INSERT INTO Areas (area_name, area_seq) 
    VALUES ('area_name1', NEXT VALUE FOR area_Garbage);
    INSERT INTO Areas (area_name, area_seq) 
    VALUES ('area_name2', NEXT VALUE FOR area_Garbage);
    INSERT INTO Areas (area_name, area_seq) 
    VALUES ('area_name3', NEXT VALUE FOR area_Garbage);
    CREATE TABLE Areas
    (area_name VARCHAR(20) NOT NULL PRIMARY KEY,
     area_seq NEXT VALUE FOR Area_Garbage);
    >> I want to update area_name column of Regions Table <<
    I would fire you for doing this, but here is a stinking kludge.
    The term “Master” is from magnetic tape files, not RDBMS! Then to make it worse, you have used the old Sybase UPDATE. FROM.. syntax! It is unpredictable. Use the MERGE: 
    MERGE INTO Regions AS R
    USING Areas AS X
    ON X.area_seq = R.region_seq 
    WHEN MATCHED
    THEN UPDATE
         SET area_name = X.area_name;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Oracle 9i Problem when using multicolumn bulk update with "save exceptions"

    I'm running into a problem with Oracle 9i when running a multicolumn update with "save exceptions". The problem occurs when updating 4 or more fileds. (The data being updated are 40 character text strings)
    I'm updating 1000 records at a time, in bulk.
    The problem goes away when I don't use "save exception" (i.e. catch the exception the normal "pre-Oracle 9i" way) or when I use "save exception" with 3 or fewer fields.
    (I don't get any exceptions when running without the "save exception")
    Thanks

    The problem is an ORA-14403 error detected during bulk updates only when "save exception" is used with more than 3 fields being updated.
    Remove the "save exception" I can update any number of fields.
    or
    Reduce the number of fields being updated to 3 or less and use save exceptions and the 14403 error goes away.
    (I'd like to use "save exception" without having to break the "update" into two separate 3 field updates.)
    Thanks,
    Len

  • Merge Vs Update with Subquery

    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.

  • HT4484 i used to have an app store and lost it and i created a new one and i can not update the iphoto app because it was updated with the old account, is there a solution for this problem?

    i used to have an app store and lost it and i created a new one and i can not update the iphoto app on my macbook pro because it was updated with the old account, is there a solution for this problem?

    Content and Apple IDs -
    Content is forever tied to the Apple ID that bought it. Apple does not transfer content from one Apple ID to another. Apple does not merge Apple IDs. You will never be able to access your content bought with one Apple ID with a new Apple ID.

Maybe you are looking for