By jamesmhaley

2010-02-25 14:36:53 8 Comments

In SQL Server, it's possible to insert into a table using a SELECT statement:

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

Is it also possible to update via a 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'


@Abdul Azeez 2018-01-31 15:42:41

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.


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


    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 =
    where = 2

2. Update with a common table expression

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

3. Merge

    Merge into product P1
    using Product_Bak P2 on =

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

In this Merge statement, we can do inset 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 =;

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

    insert (name, description)
    values(, P2.description);

@Rokonz Zaz 2019-03-14 07:00:19

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

@Santhana 2018-11-07 07:34:07

Option 1: Using Inner Join:

    A.col1 = B.col1,
    A.col2 = B.col2
    Some_Table AS A
    INNER JOIN Other_Table AS B
        ON =
    A.col3 = 'cool'

Option 2: Co related Sub query

UPDATE table 
SET Col1 = B.Col1, 
    Col2 = B.Col2 
    SELECT ID, Col1, Col2 
    FROM other_table) B
    B.ID = table.ID

@Jason Clark 2015-11-30 05:48:56

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.

@rishi jain 2018-11-22 06:09:06

The same solution can be written in a slightly different way as I would like to set the columns only once I have written about both the tables. Working in mysql.      

UPDATE Table t, 
(SELECT col1, col2 FROM other_table WHERE sql = 'cool' ) o
SET t.col1 = o.col1, t.col2=o.col2

@CAGDAS AYDIN 2018-11-22 06:54:34

like this; but you must sure update table and table after from have be same.

UPDATE Table SET col1, col2
FROM table
inner join other_table =
WHERE sql = 'cool'

@Bartosz X 2017-01-26 13:28:32

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

Sample data set:


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');


SET #DEST.[Desc] = #SOURCE.[Desc]

@Bartosz X 2017-01-26 13:30:28

YES - there is no JOIN on purpose and NO - this can't be applied on table variables.

@Jenna Leaf 2017-02-03 15:53:31

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 [email protected]_id". Have you tried? I am using a phone to reply this, no computer to try.

@Martin Smith 2017-02-05 18:10:07

What does this have to do with updating from a SELECT?

@Bartosz X 2017-02-05 18:19:13

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

@Saikh Rakif 2018-10-08 12:22:18

declare @tblStudent table (id int,name varchar(300))
declare @tblMarks table (std_id int,std_name varchar(300),subject varchar(50),marks int)

insert into @tblStudent Values (1,'Abdul')
insert into @tblStudent Values(2,'Rahim')

insert into @tblMarks Values(1,'','Math',50)
insert into @tblMarks Values(1,'','History',40)
insert into @tblMarks Values(2,'','Math',30)
insert into @tblMarks Values(2,'','history',80)

select * from @tblMarks

update m
 from @tblMarks as m
left join @tblStudent as s on

select * from @tblMarks

@Erfan Mohammadi 2018-08-31 16:48:35

You can use from this for update in sql server

   T1.col1 = T2.col1,
   T1.col2 = T2.col2
   Table1 AS T1
    ON =
    T1.col3 = 'cool'

@Jakub 2014-06-27 21:14:53

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

@Mark Hurd 2014-06-30 02:05:36

+1 but you should have used relevant alias names like targett1 and sourcet1 rather than (or as well as) comments.

@Richard 2017-02-20 16:34:56

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:

SET Table1.col1 = Table2.col1,
    Table1.col2 = Table2.col2

@Govind Tupkar 2016-09-08 12:02:24

The other way to update from a select statement:

SET A.col = A.col,B.col1 = B.col1
FROM  first_Table AS A
INNER JOIN second_Table AS B  ON = WHERE A.col2 = 'cool'

@B001ᛦ 2016-09-08 12:29:58

The other way to update from select statement What is the difference to other answers? Please elaborate your answer. Keep in mind: A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.

@lmo 2016-09-08 22:09:31

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.

@Pரதீப் 2015-12-12 16:32:39

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

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

@Mateen 2014-10-01 06:24:34

The below solution works for a MySQL database:

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

@Eugene Evdokimov 2016-06-17 07:04:37

Not working in MS SQL Server

@russ 2014-06-18 11:40:19


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


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')


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')

@Martin Smith 2011-11-06 00:18:38

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

     AS (SELECT T1.Col1,
                T2.Col1 AS _Col1,
                T2.Col2 AS _Col2
         FROM   T1
                JOIN T2
                  ON =
         /*Where clause added to exclude rows that are the same in both tables
           Handles NULL values correctly*/
                       SELECT T2.Col1,
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).

@Raptor 2012-10-08 12:48:00

is there any meaning of the name CTE ?

@Martin Smith 2012-10-08 13:05:15

@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.

@VeeTheSecond 2013-08-29 20:09:10

This also works well with multiple CTEs: ;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...

@quillbreaker 2011-09-08 21:20:00

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

SET Table.col1 = other_table.col1,
 Table.col2 = other_table.col2
INNER JOIN other_table ON =
    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.

@Martin Smith 2011-11-06 00:03:32

This assumes none of the columns are nullable though.

@quillbreaker 2011-11-11 20:27:23

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.

@Martin Smith 2012-05-27 09:44:34

WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2)) is more concise.

@quillbreaker 2013-04-03 04:53:44

Martin - it took me a while to get the knack of what that statement does. "It's a select in a where clause but it's not a table subquery?" was a proposition I was having difficulty wrapping my brain around. Now that I've got it, I've come to learn how valuable a technique it is, especially for some kinds of Data Warehousing operations.

@Barka 2013-05-15 04:03:29

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)

@quillbreaker 2013-05-16 16:35:50

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.

@Johannes Wentu 2017-04-27 07:54:50

In the accepted answer, after the:

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)

@rageit 2012-05-23 13:06:56

Using alias:

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

@Yaman 2016-11-30 21:06:38

SET TQ.IsProcessed = 1, TQ.TextName = 'bla bla bla'
FROM TableQueue TQ
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
WHERE TQ.IsProcessed = 0

@Hentold 2013-10-03 13:16:44

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

ON =
SET Table1.col1 = Table2.col1,
    Table1.col2 = Table2.col2

@Patrick Frenette 2012-11-14 13:17:40

The simple way to do it is:

    table_to_update.col1 = table_info.col1,
    table_to_update.col2 = table_info.col2

    table_to_update.ID = table_info.ID

@Ben West 2013-02-14 22:11:45

Yours is formatted better; Also, when using a subselect, yours (and Adrian's) work more reliably than the other format. Thanks for posting your answer.

@HLGEM 2013-04-24 18:32:10

This is not SQl Server syntax and it will not work in SQL server

@Aleksandr Fedorenko 2013-09-25 06:18:13

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

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

@sqluser 2016-02-24 23:35:12

The other way is to use a derived table:

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

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'

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


@Robin Day 2010-02-25 14:39:55

    Table_A.col1 = Table_B.col1,
    Table_A.col2 = Table_B.col2
    Some_Table AS Table_A
    INNER JOIN Other_Table AS Table_B
        ON =
    Table_A.col3 = 'cool'

@Trisped 2012-10-24 18:41:05

If you are editing the the link between tables (SET Table.other_table_id = @NewValue) then change the ON statement to something like ON = @IdToEdit AND = @NewValue

@Charles Wood 2013-11-26 17:12:20

@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.

@Roger Ray 2013-11-27 03:34:35

@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

@ThinkCode 2014-01-20 23:08:49

How do I use an alias in set? update table set a.col1 = b.col2 from table a inner join table2 b on =; Instead I have to use update table set table.col1 = b.col2 from table a inner join table2 b on =;

@dennislloydjr 2015-08-21 19:48:36

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:

@Cornezuelo del Centeno 2015-07-31 08:04:59

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

@travis 2016-03-18 14:31:32

This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here:

@SQLMenace 2010-02-25 14:41:40

One way

SET t.col1 = o.col1, 
    t.col2 = o.col2
    other_table o 
    t ON =
    o.sql = 'cool'

@Jamal 2012-01-22 17:47:09

UPDATE table 
SET Col1 = i.Col1, 
    Col2 = i.Col2 
    SELECT ID, Col1, Col2 
    FROM other_table) i
    i.ID = table.ID

@John Doherty 2014-10-31 18:03:20

By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work

@Alan Macdonald 2016-02-01 14:46:33

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.

@Kiquenet 2017-11-29 14:45:35

@dotnetN00b is not good for you ?

@Yuri 2019-03-13 12:26:22

Works in MS SQL.

@efirat 2013-05-02 09:48:30

Here is another useful syntax:

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

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

@onedaywhen 2011-09-09 09:40:21

In SQL Server 2008 (or better), use MERGE

   USING other_table S 
      ON =
         AND S.tsql = 'cool'
      SET col1 = S.col1, 
          col2 = S.col2;


   USING (
          SELECT id, col1, col2 
            FROM other_table 
           WHERE tsql = 'cool'
         ) S
      ON =
      SET col1 = S.col1, 
          col2 = S.col2;

@brichins 2012-05-15 19:51:44

MERGE can also be used for "Upserting" records; that is, UPDATE if matching record exists, INSERT new record if no match found

@Paul Suart 2013-04-03 02:49:54

This was around 10x quicker than the equivalent update...join statement for me.

@Möoz 2013-08-08 03:58:09

MERGE can also be used to DELETE. But be careful with MERGE as the TARGET table cannot be a remote table.

@Tracker1 2014-02-20 16:48:06

Thanks for this, hadn't seen MERGE definitely like the syntax, and that you can use aliases (which don't work in the update/set/from) much better... I've been using WITH statements for the query part.

@HLGEM 2014-06-02 13:34:20

If I can't guarantee teh results of a merge, and I can guarnatee the results of doing separate insert and update statments, then it is a bad idea to use merge.

@onedaywhen 2014-06-19 10:59:05

@HLGEM: ...I assume you are aware of the case where the result of an UPDATE..FROM is not guaranteed? (hint: many side of a one-to-many join where the result is arbitrary) Is that the kind of 'bug' you are alluding to?

@Simon D 2014-08-27 09:38:01

@onedaywhen 2014-10-03 15:29:09

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

@Endrju 2014-11-26 11:36:43

@SimonD I'm sure you would be able to find problems similar to these MERGE "bugs" (well...) in separate INSERT/UPDATE/DELETE combo. One thing - always use MERGE in SERIALIZABLE transaction (or use HOLDLOCK hint) if you want to avoid most common race conditions. Same for manual merge using INSERT/UPDATE/DELETE...

@unbob 2017-10-10 14:22:25

Portability note: MERGE is ANSI SQL; UPDATE...FROM is not. Having used both, I find MERGE semantics more intelligible - I'm less likely to mess up doing a MERGE than an UPDATE...FROM. YMMV.

Related Questions

Sponsored Content

28 Answered Questions

[SOLVED] How can I prevent SQL injection in PHP?

25 Answered Questions

[SOLVED] How do I perform an IF...THEN in an SQL SELECT?

27 Answered Questions

24 Answered Questions

[SOLVED] Check if table exists in SQL Server

43 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

45 Answered Questions

16 Answered Questions

[SOLVED] How can I do an UPDATE statement with JOIN in SQL?

23 Answered Questions

[SOLVED] Insert into ... values ( SELECT ... FROM ... )

4 Answered Questions

[SOLVED] Inserting multiple rows in a single SQL query?

37 Answered Questions

Sponsored Content