4265

In SQL Server, it is possible to insert rows into a table with an INSERT.. SELECT statement:

INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3 
FROM other_table 
WHERE sql = 'cool'

Is it also possible to update a table with SELECT? I have a temporary table containing the values and would like to update another table using those values. Perhaps something like this:

UPDATE Table SET col1, col2
SELECT col1, col2 
FROM other_table 
WHERE sql = 'cool'
WHERE Table.id = other_table.id
0

40 Answers 40

6014
UPDATE
    Table_A
SET
    Table_A.col1 = Table_B.col1,
    Table_A.col2 = Table_B.col2
FROM
    Some_Table AS Table_A
    INNER JOIN Other_Table AS Table_B
        ON Table_A.id = Table_B.id
WHERE
    Table_A.col3 = 'cool'
7
  • 27
    If you are editing the the link between tables (SET Table.other_table_id = @NewValue) then change the ON statement to something like ON Table.id = @IdToEdit AND other_table.id = @NewValue
    – Trisped
    Oct 24, 2012 at 18:41
  • 2
    @CharlesWood yeah. I have the same question in MySQL. It would be great if someone knows how to implement it to MySQL and share with everyone. I'm sure lots of people are looking for a MySQL version solution
    – Roger Ray
    Nov 27, 2013 at 3:34
  • 1
    How do I use an alias in set? update table set a.col1 = b.col2 from table a inner join table2 b on a.id = b.id; Instead I have to use update table set table.col1 = b.col2 from table a inner join table2 b on a.id = b.id;
    – ThinkCode
    Jan 20, 2014 at 23:08
  • 18
    Somewhat related, I often like to write my UPDATE queries as SELECT statements first so that I can see the data that will be updated before I execute. Sebastian covers a technique for this in a recent blog post: sqlity.net/en/2867/update-from-select Aug 21, 2015 at 19:48
  • 3
    For MySQL db: UPDATE Table_A, Table_B SET Table_A.col1 = Table_B.col1 WHERE Table_A.id = Table_B.table_a_id
    – bladekp
    Nov 15, 2019 at 21:33
881

In SQL Server 2008 (or newer), use MERGE

MERGE INTO YourTable T
   USING other_table S 
      ON T.id = S.id
         AND S.tsql = 'cool'
WHEN MATCHED THEN
   UPDATE 
      SET col1 = S.col1, 
          col2 = S.col2;

Alternatively:

MERGE INTO YourTable T
   USING (
          SELECT id, col1, col2 
            FROM other_table 
           WHERE tsql = 'cool'
         ) S
      ON T.id = S.id
WHEN MATCHED THEN
   UPDATE 
      SET col1 = S.col1, 
          col2 = S.col2;
14
  • 144
    MERGE can also be used for "Upserting" records; that is, UPDATE if matching record exists, INSERT new record if no match found
    – brichins
    May 15, 2012 at 19:51
  • 20
    This was around 10x quicker than the equivalent update...join statement for me.
    – Paul Suart
    Apr 3, 2013 at 2:49
  • 19
    MERGE can also be used to DELETE. But be careful with MERGE as the TARGET table cannot be a remote table.
    – Möoz
    Aug 8, 2013 at 3:58
  • 26
    Merge bugs: mssqltips.com/sqlservertip/3074/…
    – Simon D
    Aug 27, 2014 at 9:38
  • 19
    @SimonD: pick any SQL Server keyword and you will find bugs. Your point? I wager there are more bugs (and more fundamental ones too) associated with UPDATE than MERGE, folks have just learned to live with them and they become part of the landscape ('features'). Consider that blogs didn't exist when UPDATE was the new kid on the block.
    – onedaywhen
    Oct 3, 2014 at 15:29
857
UPDATE YourTable 
SET Col1 = OtherTable.Col1, 
    Col2 = OtherTable.Col2 
FROM (
    SELECT ID, Col1, Col2 
    FROM other_table) AS OtherTable
WHERE 
    OtherTable.ID = YourTable.ID
4
  • 23
    This will tend to work across almost all DBMS which means learn once, execute everywhere. If that is more important to you than performance you might prefer this answer, especially if your update is a one off to correct some data. Feb 1, 2016 at 14:46
  • 3
    If you need to set the first table with aggregates from the second, you can put the aggregates in the select subquery, as you cannot do SET Table_A.col1 = SUM(Table_B.col1) (or any other aggregate function). So better than Robin Day's answer for this purpose.
    – Jason S
    Jul 14, 2019 at 22:38
  • I really like this solution as it feels like a natural compliment to the way INSERT ... SELECT works. Thanks for sharing! Jun 6, 2021 at 17:50
  • Thank you. this's the easiest and most understandable way. Feb 14, 2023 at 5:29
310

I'd modify Robin's excellent answer to the following:

UPDATE Table
SET Table.col1 = other_table.col1,
 Table.col2 = other_table.col2
FROM
    Table
INNER JOIN other_table ON Table.id = other_table.id
WHERE
    Table.col1 != other_table.col1
OR Table.col2 != other_table.col2
OR (
    other_table.col1 IS NOT NULL
    AND Table.col1 IS NULL
)
OR (
    other_table.col2 IS NOT NULL
    AND Table.col2 IS NULL
)

Without a WHERE clause, you'll affect even rows that don't need to be affected, which could (possibly) cause index recalculation or fire triggers that really shouldn't have been fired.

6
  • 7
    This assumes none of the columns are nullable though. Nov 6, 2011 at 0:03
  • 4
    You're right, I was typing the example by hand. I've added a third and fourth clause to the where statement to deal with that. Nov 11, 2011 at 20:27
  • 50
    WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2)) is more concise. May 27, 2012 at 9:44
  • 5
    shouldn't the statement also contain these two in the where clause? (other_table.col1 is null and table.col1 is not null) or (other_table.col2 is null and table.col2 is not null)
    – Barka
    May 15, 2013 at 4:03
  • 4
    Depends on if you want to replace nulls in the destination with nulls from the source. Frequently, I don't. But if you do, Martin's construction of the where clause is the best thing to use. May 16, 2013 at 16:35
232

One way

UPDATE t 
SET t.col1 = o.col1, 
    t.col2 = o.col2
FROM 
    other_table o 
  JOIN 
    t ON t.id = o.id
WHERE 
    o.sql = 'cool'
1
  • SQL server 12. Seems like it is getting the t.id from JOIN t and not from UPDATE t. So it always update with the same value no matter of what row of t we are trying to update. Nov 26, 2022 at 12:34
195

Another possibility not mentioned yet is to just chuck the SELECT statement itself into a CTE and then update the CTE.

WITH CTE
     AS (SELECT T1.Col1,
                T2.Col1 AS _Col1,
                T1.Col2,
                T2.Col2 AS _Col2
         FROM   T1
                JOIN T2
                  ON T1.id = T2.id
         /*Where clause added to exclude rows that are the same in both tables
           Handles NULL values correctly*/
         WHERE EXISTS(SELECT T1.Col1,
                             T1.Col2
                       EXCEPT
                       SELECT T2.Col1,
                              T2.Col2))
UPDATE CTE
SET    Col1 = _Col1,
       Col2 = _Col2;

This has the benefit that it is easy to run the SELECT statement on its own first to sanity check the results, but it does requires you to alias the columns as above if they are named the same in source and target tables.

This also has the same limitation as the proprietary UPDATE ... FROM syntax shown in four of the other answers. If the source table is on the many side of a one-to-many join then it is undeterministic which of the possible matching joined records will be used in the Update (an issue that MERGE avoids by raising an error if there is an attempt to update the same row more than once).

3
  • 4
    is there any meaning of the name CTE ?
    – Raptor
    Oct 8, 2012 at 12:48
  • 21
    @ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case. Oct 8, 2012 at 13:05
  • 3
    This also works well with multiple CTEs: ;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ... Aug 29, 2013 at 20:09
143

For the record (and others searching like I was), you can do it in MySQL like this:

UPDATE first_table, second_table
SET first_table.color = second_table.color
WHERE first_table.id = second_table.foreign_id
0
114

Using alias:

UPDATE t
   SET t.col1 = o.col1
  FROM table1 AS t
         INNER JOIN 
       table2 AS o 
         ON t.id = o.id
85

The simple way to do it is:

UPDATE
    table_to_update,
    table_info
SET
    table_to_update.col1 = table_info.col1,
    table_to_update.col2 = table_info.col2

WHERE
    table_to_update.ID = table_info.ID
1
  • 25
    This is not SQl Server syntax and it will not work in SQL server
    – HLGEM
    Apr 24, 2013 at 18:32
76

This may be a niche reason to perform an update (for example, mainly used in a procedure), or may be obvious to others, but it should also be stated that you can perform an update-select statement without using join (in case the tables you're updating between have no common field).

update
    Table
set
    Table.example = a.value
from
    TableExample a
where
    Table.field = *key value* -- finds the row in Table 
    AND a.field = *key value* -- finds the row in TableExample a
1
  • 1
    I feel this should be the accepted answer, because it keeps things simple and to the point. Dec 7, 2021 at 22:56
69

Here is another useful syntax:

UPDATE suppliers
SET supplier_name = (SELECT customers.name
                     FROM customers
                     WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT customers.name
              FROM customers
              WHERE customers.customer_id = suppliers.supplier_id);

It checks if it is null or not by using "WHERE EXIST".

1
  • 1
    The only answer that worked for me. I'm using MariaDB, and my query is of the form: SELECT value FROM table_1 INNER JOIN ( SELECT * FROM table_2 WHERE ..... ) ON ( ...... )
    – Bludzee
    Mar 23, 2022 at 16:41
63

I add this only so you can see a quick way to write it so that you can check what will be updated before doing the update.

UPDATE Table 
SET  Table.col1 = other_table.col1,
     Table.col2 = other_table.col2 
--select Table.col1, other_table.col,Table.col2,other_table.col2, *   
FROM     Table 
INNER JOIN     other_table 
    ON     Table.id = other_table.id 
0
60

If you use MySQL instead of SQL Server, the syntax is:

UPDATE Table1
INNER JOIN Table2
ON Table1.id = Table2.id
SET Table1.col1 = Table2.col1,
    Table1.col2 = Table2.col2
1
  • What if we want to update Table2.col1? how will we do that. table two is extracted on the base of the query condition. Nov 26, 2020 at 21:03
59

UPDATE from SELECT with INNER JOIN in SQL Database

Since there are too many replies of this post, which are most heavily up-voted, I thought I would provide my suggestion here too. Although the question is very interesting, I have seen in many forum sites and made a solution using INNER JOIN with screenshots.

At first, I have created a table named with schoolold and inserted few records with respect to their column names and execute it.

Then I executed SELECT command to view inserted records.

Then I created a new table named with schoolnew and similarly executed above actions on it.

Then, to view inserted records in it, I execute SELECT command.

Now, Here I want to make some changes in third and fourth row, to complete this action, I execute UPDATE command with INNER JOIN.

To view the changes I execute the SELECT command.

You can see how Third and Fourth records of table schoolold easily replaced with table schoolnew by using INNER JOIN with UPDATE statement.

0
52

And if you wanted to join the table with itself (which won't happen too often):

update t1                    -- just reference table alias here
set t1.somevalue = t2.somevalue
from table1 t1               -- these rows will be the targets
inner join table1 t2         -- these rows will be used as source
on ..................        -- the join clause is whatever suits you
1
  • 8
    +1 but you should have used relevant alias names like targett1 and sourcet1 rather than (or as well as) comments.
    – Mark Hurd
    Jun 30, 2014 at 2:05
50

Updating through CTE is more readable than the other answers here:

;WITH cte
     AS (SELECT col1,col2,id
         FROM   other_table
         WHERE  sql = 'cool')
UPDATE A
SET    A.col1 = B.col1,
       A.col2 = B.col2
FROM   table A
       INNER JOIN cte B
               ON A.id = B.id
48

Consolidating all the different approaches here.

  1. Select update
  2. Update with a common table expression
  3. Merge

Sample table structure is below and will update from Product_BAK to Product table.

Table Product

CREATE TABLE [dbo].[Product](
    [Id] [int] IDENTITY(1, 1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [Description] [nvarchar](100) NULL
) ON [PRIMARY]

Table Product_BAK

    CREATE TABLE [dbo].[Product_BAK](
        [Id] [int] IDENTITY(1, 1) NOT NULL,
        [Name] [nvarchar](100) NOT NULL,
        [Description] [nvarchar](100) NULL
    ) ON [PRIMARY]

1. Select update

    update P1
    set Name = P2.Name
    from Product P1
    inner join Product_Bak P2 on p1.id = P2.id
    where p1.id = 2

2. Update with a common table expression

    ; With CTE as
    (
        select id, name from Product_Bak where id = 2
    )
    update P
    set Name = P2.name
    from  product P  inner join CTE P2 on P.id = P2.id
    where P2.id = 2

3. Merge

    Merge into product P1
    using Product_Bak P2 on P1.id = P2.id

    when matched then
    update set p1.[description] = p2.[description], p1.name = P2.Name;

In this Merge statement, we can do insert if not finding a matching record in the target, but exist in the source and please find syntax:

    Merge into product P1
    using Product_Bak P2 on P1.id = P2.id;

    when matched then
    update set p1.[description] = p2.[description], p1.name = P2.Name;

    WHEN NOT MATCHED THEN
    insert (name, description)
    values(p2.name, P2.description);
1
  • What do you mean by "and please find syntax"? Can you elaborate? Feb 2, 2022 at 18:51
45

The following example uses a derived table, a SELECT statement after the FROM clause, to return the old and new values for further updates:

UPDATE x
SET    x.col1 = x.newCol1,
       x.col2 = x.newCol2
FROM   (SELECT t.col1,
               t2.col1 AS newCol1,
               t.col2,
               t2.col2 AS newCol2
        FROM   [table] t
               JOIN other_table t2
                 ON t.ID = t2.ID) x
44

If you are using SQL Server you can update one table from another without specifying a join and simply link the two from the where clause. This makes a much simpler SQL query:

UPDATE Table1
SET Table1.col1 = Table2.col1,
    Table1.col2 = Table2.col2
FROM
    Table2
WHERE
    Table1.id = Table2.id
0
28

The other way is to use a derived table:

UPDATE t
SET t.col1 = a.col1
    ,t.col2 = a.col2
FROM (
SELECT id, col1, col2 FROM @tbl2) a
INNER JOIN @tbl1 t ON t.id = a.id

Sample data

DECLARE @tbl1 TABLE (id INT, col1 VARCHAR(10), col2 VARCHAR(10))
DECLARE @tbl2 TABLE (id INT, col1 VARCHAR(10), col2 VARCHAR(10))

INSERT @tbl1 SELECT 1, 'a', 'b' UNION SELECT 2, 'b', 'c'

INSERT @tbl2 SELECT 1, '1', '2' UNION SELECT 2, '3', '4'

UPDATE t
SET t.col1 = a.col1
    ,t.col2 = a.col2
FROM (
SELECT id, col1, col2 FROM @tbl2) a
INNER JOIN @tbl1 t ON t.id = a.id

SELECT * FROM @tbl1
SELECT * FROM @tbl2
26
UPDATE TQ
SET TQ.IsProcessed = 1, TQ.TextName = 'bla bla bla'
FROM TableQueue TQ
INNER JOIN TableComment TC ON TC.ID = TQ.TCID
WHERE TQ.IsProcessed = 0

To make sure you are updating what you want, select first

SELECT TQ.IsProcessed, 1 AS NewValue1, TQ.TextName, 'bla bla bla' AS NewValue2
FROM TableQueue TQ
INNER JOIN TableComment TC ON TC.ID = TQ.TCID
WHERE TQ.IsProcessed = 0
25

There is even a shorter method and it might be surprising for you:

Sample data set:

CREATE TABLE #SOURCE ([ID] INT, [Desc] VARCHAR(10));
CREATE TABLE #DEST   ([ID] INT, [Desc] VARCHAR(10));

INSERT INTO #SOURCE VALUES(1,'Desc_1'), (2, 'Desc_2'), (3, 'Desc_3');
INSERT INTO #DEST   VALUES(1,'Desc_4'), (2, 'Desc_5'), (3, 'Desc_6');

Code:

UPDATE #DEST
SET #DEST.[Desc] = #SOURCE.[Desc]
FROM #SOURCE
WHERE #DEST.[ID] = #SOURCE.[ID];
4
  • 1
    YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
    – Bartosz X
    Jan 26, 2017 at 13:30
  • 1
    I think if you use [_id] on your #SOURCE not [ID] the same as #DESTINATION's, they might let you do JOIN. "on #DESTINATION.ID=#SOURCE._id. Or even use table variable like @tbl, "on PermTable.ID=@memorytbl._id". Have you tried? I am using a phone to reply this, no computer to try.
    – Jenna Leaf
    Feb 3, 2017 at 15:53
  • 2
    What does this have to do with updating from a SELECT? Feb 5, 2017 at 18:10
  • 2
    This is the same idea but another method - you don't have to put "select" at all to achieve JOIN and WHERE in update statement - which is SELECT type of query without even writing SELECT
    – Bartosz X
    Feb 5, 2017 at 18:19
23

Use:

drop table uno
drop table dos

create table uno
(
    uid int,
    col1 char(1),
    col2 char(2)
)
create table dos
(
    did int,
    col1 char(1),
    col2 char(2),
    [sql] char(4)
)
insert into uno(uid) values (1)
insert into uno(uid) values (2)
insert into dos values (1,'a','b',null)
insert into dos values (2,'c','d','cool')

select * from uno 
select * from dos

EITHER:

update uno set col1 = (select col1 from dos where uid = did and [sql]='cool'), 
col2 = (select col2 from dos where uid = did and [sql]='cool')

OR:

update uno set col1=d.col1,col2=d.col2 from uno 
inner join dos d on uid=did where [sql]='cool'

select * from uno 
select * from dos

If the ID column name is the same in both tables then just put the table name before the table to be updated and use an alias for the selected table, i.e.:

update uno set col1 = (select col1 from dos d where uno.[id] = d.[id] and [sql]='cool'),
col2  = (select col2 from dos d where uno.[id] = d.[id] and [sql]='cool')
17

In the accepted answer, after the:

SET
Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2

I would add:

OUTPUT deleted.*, inserted.*

What I usually do is putting everything in a roll backed transaction and using the "OUTPUT": in this way I see everything that is about to happen. When I am happy with what I see, I change the ROLLBACK into COMMIT.

I usually need to document what I did, so I use the "results to Text" option when I run the roll-backed query and I save both the script and the result of the OUTPUT. (Of course this is not practical if I changed too many rows)

14
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
0
14

The below solution works for a MySQL database:

UPDATE table1 a , table2 b 
SET a.columname = 'some value' 
WHERE b.columnname IS NULL ;
0
13

The other way to update from a select statement:

UPDATE A
SET A.col = A.col,B.col1 = B.col1
FROM  first_Table AS A
INNER JOIN second_Table AS B  ON A.id = B.id WHERE A.col2 = 'cool'
1
  • 2
    This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
    – lmo
    Sep 8, 2016 at 22:09
10

Option 1: Using Inner Join:

UPDATE
    A
SET
    A.col1 = B.col1,
    A.col2 = B.col2
FROM
    Some_Table AS A
    INNER JOIN Other_Table AS B
        ON A.id = B.id
WHERE
    A.col3 = 'cool'

Option 2: Co related Sub query

UPDATE table 
SET Col1 = B.Col1, 
    Col2 = B.Col2 
FROM (
    SELECT ID, Col1, Col2 
    FROM other_table) B
WHERE 
    B.ID = table.ID
4
  • 1
    Did it work for you? I used exact same query but had errors when used inner join, alias coun't be resolved. However the co-related sub query worked perfectly. Nov 26, 2019 at 15:12
  • I don't have the exact error logs but the alias A was being referenced before the assignment, which caused the error. Jan 7, 2020 at 8:16
  • I used the correlated sub query Mar 19, 2020 at 18:14
  • What was this tested on? SQL Server? MySQL? Something else? What version? Feb 2, 2022 at 18:29
10
UPDATE table1
SET column1 = (SELECT expression1
               FROM table2
               WHERE conditions)
[WHERE conditions];

The syntax for the UPDATE statement when updating one table with data from another table in SQL Server.

7

It is important to point out, as others have, that MySQL or MariaDB use a different syntax. Also it supports a very convenient USING syntax (in contrast to T/SQL). Also INNER JOIN is synonymous with JOIN. Therefore the query in the original question would be best implemented in MySQL thusly:

UPDATE
    Some_Table AS Table_A

JOIN
    Other_Table AS Table_B USING(id)

SET
    Table_A.col1 = Table_B.col1,
    Table_A.col2 = Table_B.col2

WHERE
    Table_A.col3 = 'cool'

I've not seen the a solution to the asked question in the other answers, hence my two cents. (tested on PHP 7.4.0 MariaDB 10.4.10)

7
  • Re "the query in the original question": What? The very first revision was tagged with SQL Server (the Microsoft product). Jan 30, 2022 at 1:37
  • NATURAL joins with or without USING is an evil feature and can conducts to false answer and catatsrophic response times...
    – SQLpro
    Dec 19, 2023 at 9:02
  • @PeterMortensen hence my disclaimer right at the start.
    – theking2
    Dec 19, 2023 at 15:38
  • @SQLpro please elaborate
    – theking2
    Jan 1 at 19:55
  • 1
    @theking2 A little bit too complex to answer in few words, but I demonstrate why in my new book about SQL language (in French) that will be available for free in few month on developpez.com website
    – SQLpro
    Jan 2 at 22:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.