Home How do I UPDATE from a SELECT in SQL Server?
Reply: 26

How do I UPDATE from a SELECT in SQL Server?

jamesmhaley
1#
jamesmhaley Published in 2010-02-25 14:36:53Z

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'
WHERE Table.id = other_table.id
Dai
2#
Dai Reply to 2016-04-30 01:26:35Z
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'
shA.t
3#
shA.t Reply to 2015-05-20 10:12:15Z

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'
Faisal
4#
Faisal Reply to 2017-07-28 05:00:52Z

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.

HLGEM
5#
HLGEM Reply to 2011-09-08 21:35:34Z

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 
onedaywhen
6#
onedaywhen Reply to 2014-04-03 08:06:16Z

In SQL Server 2008 (or better), 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;
Martin Smith
7#
Martin Smith Reply to 2012-01-31 13:50:23Z

Another possibility not mentioned yet is to just chuck the SELECT statement itself into a CTE 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).

shA.t
8#
shA.t Reply to 2015-05-20 10:11:11Z
UPDATE table 
SET Col1 = i.Col1, 
    Col2 = i.Col2 
FROM (
    SELECT ID, Col1, Col2 
    FROM other_table) i
WHERE 
    i.ID = table.ID
Faisal
9#
Faisal Reply to 2017-07-28 04:58:33Z

Using alias:

UPDATE t
SET t.col1 = o.col1
FROM
    table1 AS t
INNER JOIN table2 AS o ON t.id = o.id
Ryan
10#
Ryan Reply to 2012-06-11 16:58:24Z

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
Adrian Macneil
11#
Adrian Macneil Reply to 2012-10-05 14:20:32Z

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
Shiva
12#
Shiva Reply to 2016-07-25 19:39:19Z

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
Peter Mortensen
13#
Peter Mortensen Reply to 2014-04-14 19:44:46Z

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

Peter Mortensen
14#
Peter Mortensen Reply to 2016-06-25 21:28:13Z

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
Simon Hughes
15#
Simon Hughes Reply to 2016-08-11 08:16:44Z

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
russ
16#
russ Reply to 2014-06-18 12:44:36Z
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 ie:

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')
Jakub
17#
Jakub Reply to 2014-06-27 21:14:53Z

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
Peter Mortensen
18#
Peter Mortensen Reply to 2014-11-29 08:44:30Z

I finally got this simple solution:

UPDATE table1 a , table2 b 
SET a.columname = 'some value' 
WHERE b.columnname IS NULL ;
Cornezuelo del Centeno
19#
Cornezuelo del Centeno Reply to 2015-07-31 08:04:59Z
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
Jason Clark
20#
Jason Clark Reply to 2016-06-27 03:57:49Z

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.

Peter Mortensen
21#
Peter Mortensen Reply to 2016-06-25 20:47:28Z

Updating through CTE is more readable than the other answer's 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
Peter Mortensen
22#
Peter Mortensen Reply to 2016-06-25 20:46:44Z

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
Govind Tupkar
23#
Govind Tupkar Reply to 2016-09-08 12:02:24Z
The other way to update from 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'
Yaman
24#
Yaman Reply to 2016-11-30 21:06:38Z
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
Bartosz X
25#
Bartosz X Reply to 2017-01-26 13:28:32Z

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

-- Sample data:
---------------------------------------------------------------------------
CREATE TABLE #SOURCE ([ID] INT, [Desc] VARCHAR(10));
CREATE TABLE #DESTINATION ([ID] INT, [Desc] VARCHAR(10))

INSERT INTO #SOURCE VALUES(1,'Desc_1'), (2, 'Desc_2'), (3, 'Desc_3');
INSERT INTO #DESTINATION VALUES(1,'Desc_4'), (2, 'Desc_5'), (3, 'Desc_6');
---------------------------------------------------------------------------
UPDATE #DESTINATION
SET #DESTINATION.[Desc] = #SOURCE.[Desc]
FROM #SOURCE
WHERE #DESTINATION.[ID] = #SOURCE.[ID]
AND #Source.[Desc] = 'Desc_2'
Richard
26#
Richard Reply to 2017-05-05 12:20:25Z

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
Johannes Wentu
27#
Johannes Wentu Reply to 2017-06-12 06:12:39Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.380988 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO