How do I UPDATE from a SELECT in SQL Server?
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
sql sql-server tsql select
add a comment |
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
sql sql-server tsql select
add a comment |
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
sql sql-server tsql select
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
sql sql-server tsql select
sql sql-server tsql select
edited May 14 '18 at 12:07
jamesmhaley
asked Feb 25 '10 at 14:36
jamesmhaleyjamesmhaley
17.1k72944
17.1k72944
add a comment |
add a comment |
32 Answers
32
active
oldest
votes
1 2
next
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'
10
If you are editing the the link between tables (SET Table.other_table_id = @NewValue
) then change the ON statement to something likeON Table.id = @IdToEdit AND other_table.id = @NewValue
– Trisped
Oct 24 '12 at 18:41
24
Isn't this missing theWHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to theON
like:ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?
– J V
May 31 '13 at 18:15
9
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
7
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
5
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
– dennislloydjr
Aug 21 '15 at 19:48
|
show 2 more comments
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;
114
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 '12 at 19:51
15
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
16
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 '13 at 3:58
17
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
12
@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 withUPDATE
thanMERGE
, folks have just learned to live with them and they become part of the landscape ('features'). Consider that blogs didn't exist whenUPDATE
was the new kid on the block.
– onedaywhen
Oct 3 '14 at 15:29
|
show 5 more comments
UPDATE table
SET Col1 = i.Col1,
Col2 = i.Col2
FROM (
SELECT ID, Col1, Col2
FROM other_table) i
WHERE
i.ID = table.ID
5
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
7
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.
– Alan Macdonald
Feb 1 '16 at 14:46
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
add a comment |
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
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
3
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.
– quillbreaker
Nov 11 '11 at 20:27
44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.
– Martin Smith
May 27 '12 at 9:44
4
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 '13 at 4:03
3
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.
– quillbreaker
May 16 '13 at 16:35
|
show 1 more comment
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'
add a comment |
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).
1
is there any meaning of the nameCTE
?
– Raptor
Oct 8 '12 at 12:48
14
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
2
This also works well with multiple CTEs:;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
add a comment |
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
4
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
3
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
add a comment |
Using alias:
UPDATE t
SET t.col1 = o.col1
FROM table1 AS t
INNER JOIN
table2 AS o
ON t.id = o.id
add a comment |
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
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.
– Ben West
Feb 14 '13 at 22:11
18
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
add a comment |
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
add a comment |
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".
add a comment |
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
add a comment |
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
add a comment |
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.
add a comment |
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
7
+1 but you should have used relevant alias names liketargett1
andsourcet1
rather than (or as well as) comments.
– Mark Hurd
Jun 30 '14 at 2:05
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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')
add a comment |
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];
1
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 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 '17 at 15:53
1
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
1
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 '17 at 18:19
add a comment |
The below solution works for a MySQL database:
UPDATE table1 a , table2 b
SET a.columname = 'some value'
WHERE b.columnname IS NULL ;
3
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
add a comment |
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)
add a comment |
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'
3
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.
– B001ᛦ
Sep 8 '16 at 12:29
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 '16 at 22:09
add a comment |
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
1
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
add a comment |
Consolidating all the different approaches here.
- Select update
- Update with a common table expression
- Merge
Sample table structure are below and will update from Product_BAK to Product table.
Product
CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1, 1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Description] [nvarchar](100) NULL
) ON [PRIMARY]
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 the 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 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);
add a comment |
You can use from this for update in sql server
UPDATE
T1
SET
T1.col1 = T2.col1,
T1.col2 = T2.col2
FROM
Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE
T1.col3 = 'cool'
add a comment |
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
set m.std_name=s.name
from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id
select * from @tblMarks
add a comment |
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 Table.id = other_table.id
WHERE sql = 'cool'
add a comment |
1 2
next
protected by Mr. Alien Apr 11 '13 at 8:51
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
32 Answers
32
active
oldest
votes
32 Answers
32
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
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'
10
If you are editing the the link between tables (SET Table.other_table_id = @NewValue
) then change the ON statement to something likeON Table.id = @IdToEdit AND other_table.id = @NewValue
– Trisped
Oct 24 '12 at 18:41
24
Isn't this missing theWHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to theON
like:ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?
– J V
May 31 '13 at 18:15
9
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
7
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
5
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
– dennislloydjr
Aug 21 '15 at 19:48
|
show 2 more comments
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'
10
If you are editing the the link between tables (SET Table.other_table_id = @NewValue
) then change the ON statement to something likeON Table.id = @IdToEdit AND other_table.id = @NewValue
– Trisped
Oct 24 '12 at 18:41
24
Isn't this missing theWHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to theON
like:ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?
– J V
May 31 '13 at 18:15
9
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
7
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
5
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
– dennislloydjr
Aug 21 '15 at 19:48
|
show 2 more comments
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'
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'
edited Apr 30 '16 at 1:26
Dai
72.2k13114201
72.2k13114201
answered Feb 25 '10 at 14:39
Robin DayRobin Day
79.3k20103156
79.3k20103156
10
If you are editing the the link between tables (SET Table.other_table_id = @NewValue
) then change the ON statement to something likeON Table.id = @IdToEdit AND other_table.id = @NewValue
– Trisped
Oct 24 '12 at 18:41
24
Isn't this missing theWHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to theON
like:ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?
– J V
May 31 '13 at 18:15
9
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
7
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
5
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
– dennislloydjr
Aug 21 '15 at 19:48
|
show 2 more comments
10
If you are editing the the link between tables (SET Table.other_table_id = @NewValue
) then change the ON statement to something likeON Table.id = @IdToEdit AND other_table.id = @NewValue
– Trisped
Oct 24 '12 at 18:41
24
Isn't this missing theWHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to theON
like:ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?
– J V
May 31 '13 at 18:15
9
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
7
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
5
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
– dennislloydjr
Aug 21 '15 at 19:48
10
10
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 '12 at 18:41
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 '12 at 18:41
24
24
Isn't this missing the
WHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to the ON
like: ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?– J V
May 31 '13 at 18:15
Isn't this missing the
WHERE
clause in the question? I don't have a server on this system to test it but wouldn't you be able to add that to the ON
like: ON Table.id = other_table.id AND other_table.sql='cool'
? Or am I misinterpreting the question?– J V
May 31 '13 at 18:15
9
9
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
This works by using UPDATE to iterate over the INNER JOIN. As such the ON functions as your WHERE clause and the INNER JOIN skips records that are not found in the JOINed table. Adding a WHERE clause would limit the result set of the JOINed table as well. @Roger Ray what version of MySQL and what was your query, as this DOES infact function as stated.
– fyrye
Sep 6 '13 at 17:14
7
7
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
@RogerRay, this question is about Microsoft SQL Server. Unfortunately, the syntax between various SQL implementations can vary.
– Charles Wood
Nov 26 '13 at 17:12
5
5
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
– dennislloydjr
Aug 21 '15 at 19:48
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
– dennislloydjr
Aug 21 '15 at 19:48
|
show 2 more comments
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;
114
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 '12 at 19:51
15
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
16
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 '13 at 3:58
17
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
12
@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 withUPDATE
thanMERGE
, folks have just learned to live with them and they become part of the landscape ('features'). Consider that blogs didn't exist whenUPDATE
was the new kid on the block.
– onedaywhen
Oct 3 '14 at 15:29
|
show 5 more comments
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;
114
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 '12 at 19:51
15
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
16
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 '13 at 3:58
17
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
12
@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 withUPDATE
thanMERGE
, folks have just learned to live with them and they become part of the landscape ('features'). Consider that blogs didn't exist whenUPDATE
was the new kid on the block.
– onedaywhen
Oct 3 '14 at 15:29
|
show 5 more comments
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;
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;
edited Apr 3 '14 at 8:06
answered Sep 9 '11 at 9:40
onedaywhenonedaywhen
43.2k1076121
43.2k1076121
114
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 '12 at 19:51
15
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
16
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 '13 at 3:58
17
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
12
@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 withUPDATE
thanMERGE
, folks have just learned to live with them and they become part of the landscape ('features'). Consider that blogs didn't exist whenUPDATE
was the new kid on the block.
– onedaywhen
Oct 3 '14 at 15:29
|
show 5 more comments
114
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 '12 at 19:51
15
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
16
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 '13 at 3:58
17
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
12
@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 withUPDATE
thanMERGE
, folks have just learned to live with them and they become part of the landscape ('features'). Consider that blogs didn't exist whenUPDATE
was the new kid on the block.
– onedaywhen
Oct 3 '14 at 15:29
114
114
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 '12 at 19:51
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 '12 at 19:51
15
15
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
This was around 10x quicker than the equivalent update...join statement for me.
– Paul Suart
Apr 3 '13 at 2:49
16
16
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 '13 at 3:58
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 '13 at 3:58
17
17
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
Merge bugs: mssqltips.com/sqlservertip/3074/…
– Simon D
Aug 27 '14 at 9:38
12
12
@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 '14 at 15:29
@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 '14 at 15:29
|
show 5 more comments
UPDATE table
SET Col1 = i.Col1,
Col2 = i.Col2
FROM (
SELECT ID, Col1, Col2
FROM other_table) i
WHERE
i.ID = table.ID
5
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
7
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.
– Alan Macdonald
Feb 1 '16 at 14:46
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
add a comment |
UPDATE table
SET Col1 = i.Col1,
Col2 = i.Col2
FROM (
SELECT ID, Col1, Col2
FROM other_table) i
WHERE
i.ID = table.ID
5
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
7
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.
– Alan Macdonald
Feb 1 '16 at 14:46
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
add a comment |
UPDATE table
SET Col1 = i.Col1,
Col2 = i.Col2
FROM (
SELECT ID, Col1, Col2
FROM other_table) i
WHERE
i.ID = table.ID
UPDATE table
SET Col1 = i.Col1,
Col2 = i.Col2
FROM (
SELECT ID, Col1, Col2
FROM other_table) i
WHERE
i.ID = table.ID
edited May 20 '15 at 10:11
shA.t
12.9k43664
12.9k43664
answered Jan 22 '12 at 17:47
JamalJamal
5,547182
5,547182
5
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
7
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.
– Alan Macdonald
Feb 1 '16 at 14:46
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
add a comment |
5
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
7
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.
– Alan Macdonald
Feb 1 '16 at 14:46
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
5
5
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
By far the simplest! However your missing the ID field from the inner SELECT. You'll need this for the WHERE clause to work
– John Doherty
Oct 31 '14 at 18:03
7
7
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.
– Alan Macdonald
Feb 1 '16 at 14:46
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.
– Alan Macdonald
Feb 1 '16 at 14:46
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
@dotnetN00b stackoverflow.com/a/2334741/206730 is not good for you ?
– Kiquenet
Nov 29 '17 at 14:45
add a comment |
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
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
3
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.
– quillbreaker
Nov 11 '11 at 20:27
44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.
– Martin Smith
May 27 '12 at 9:44
4
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 '13 at 4:03
3
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.
– quillbreaker
May 16 '13 at 16:35
|
show 1 more comment
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
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
3
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.
– quillbreaker
Nov 11 '11 at 20:27
44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.
– Martin Smith
May 27 '12 at 9:44
4
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 '13 at 4:03
3
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.
– quillbreaker
May 16 '13 at 16:35
|
show 1 more comment
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.
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.
edited May 19 '18 at 17:18
Peter Mortensen
13.5k1984111
13.5k1984111
answered Sep 8 '11 at 21:20
quillbreakerquillbreaker
4,76532243
4,76532243
6
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
3
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.
– quillbreaker
Nov 11 '11 at 20:27
44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.
– Martin Smith
May 27 '12 at 9:44
4
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 '13 at 4:03
3
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.
– quillbreaker
May 16 '13 at 16:35
|
show 1 more comment
6
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
3
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.
– quillbreaker
Nov 11 '11 at 20:27
44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.
– Martin Smith
May 27 '12 at 9:44
4
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 '13 at 4:03
3
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.
– quillbreaker
May 16 '13 at 16:35
6
6
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
This assumes none of the columns are nullable though.
– Martin Smith
Nov 6 '11 at 0:03
3
3
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.
– quillbreaker
Nov 11 '11 at 20:27
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.
– quillbreaker
Nov 11 '11 at 20:27
44
44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.– Martin Smith
May 27 '12 at 9:44
WHERE EXISTS(SELECT T1.Col1, T1.Col2 EXCEPT SELECT T2.Col1, T2.Col2))
is more concise.– Martin Smith
May 27 '12 at 9:44
4
4
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 '13 at 4:03
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 '13 at 4:03
3
3
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.
– quillbreaker
May 16 '13 at 16:35
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.
– quillbreaker
May 16 '13 at 16:35
|
show 1 more comment
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'
add a comment |
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'
add a comment |
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'
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'
edited May 20 '15 at 10:12
shA.t
12.9k43664
12.9k43664
answered Feb 25 '10 at 14:41
SQLMenaceSQLMenace
111k23181210
111k23181210
add a comment |
add a comment |
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).
1
is there any meaning of the nameCTE
?
– Raptor
Oct 8 '12 at 12:48
14
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
2
This also works well with multiple CTEs:;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
add a comment |
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).
1
is there any meaning of the nameCTE
?
– Raptor
Oct 8 '12 at 12:48
14
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
2
This also works well with multiple CTEs:;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
add a comment |
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).
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).
edited May 19 '18 at 17:21
Peter Mortensen
13.5k1984111
13.5k1984111
answered Nov 6 '11 at 0:18
Martin SmithMartin Smith
342k58575684
342k58575684
1
is there any meaning of the nameCTE
?
– Raptor
Oct 8 '12 at 12:48
14
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
2
This also works well with multiple CTEs:;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
add a comment |
1
is there any meaning of the nameCTE
?
– Raptor
Oct 8 '12 at 12:48
14
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
2
This also works well with multiple CTEs:;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
1
1
is there any meaning of the name
CTE
?– Raptor
Oct 8 '12 at 12:48
is there any meaning of the name
CTE
?– Raptor
Oct 8 '12 at 12:48
14
14
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
@ShivanRaptor - It is the acronym for Common Table Expression. Just an arbitrary alias in this case.
– Martin Smith
Oct 8 '12 at 13:05
2
2
This also works well with multiple CTEs:
;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
This also works well with multiple CTEs:
;WITH SomeCompexCTE AS (...), CTEAsAbove AS (SELECT T1.Col1,... FROM T1 JOIN SomeComplexCTE...) UPDATE CTEAsAbove SET Col1=_Col1, ...
– VeeTheSecond
Aug 29 '13 at 20:09
add a comment |
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
4
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
3
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
add a comment |
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
4
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
3
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
add a comment |
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
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
answered Oct 5 '12 at 14:20
Adrian MacneilAdrian Macneil
10.4k34467
10.4k34467
4
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
3
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
add a comment |
4
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
3
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
4
4
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
Why is this upvoted so often? Would be the same if I post for the record ruby code if someone asks for C#...
– isHuman
Mar 9 '16 at 17:10
3
3
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
@isHuman It is very common to reach in a sql-server question when you seek for my-sql answers (and vice-versa). It is entirely different from posting a ruby answer in a c# question.
– Gabriel
Oct 25 '17 at 18:46
add a comment |
Using alias:
UPDATE t
SET t.col1 = o.col1
FROM table1 AS t
INNER JOIN
table2 AS o
ON t.id = o.id
add a comment |
Using alias:
UPDATE t
SET t.col1 = o.col1
FROM table1 AS t
INNER JOIN
table2 AS o
ON t.id = o.id
add a comment |
Using alias:
UPDATE t
SET t.col1 = o.col1
FROM table1 AS t
INNER JOIN
table2 AS o
ON t.id = o.id
Using alias:
UPDATE t
SET t.col1 = o.col1
FROM table1 AS t
INNER JOIN
table2 AS o
ON t.id = o.id
edited Mar 12 '18 at 16:10
answered May 23 '12 at 13:06
rageitrageit
2,7542134
2,7542134
add a comment |
add a comment |
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
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.
– Ben West
Feb 14 '13 at 22:11
18
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
add a comment |
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
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.
– Ben West
Feb 14 '13 at 22:11
18
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
add a comment |
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
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
edited Jul 25 '16 at 19:39
Shiva
13.9k95989
13.9k95989
answered Nov 14 '12 at 13:17
Patrick FrenettePatrick Frenette
67152
67152
1
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.
– Ben West
Feb 14 '13 at 22:11
18
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
add a comment |
1
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.
– Ben West
Feb 14 '13 at 22:11
18
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
1
1
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.
– Ben West
Feb 14 '13 at 22:11
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.
– Ben West
Feb 14 '13 at 22:11
18
18
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
This is not SQl Server syntax and it will not work in SQL server
– HLGEM
Apr 24 '13 at 18:32
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Jun 11 '12 at 16:58
RyanRyan
1,54242341
1,54242341
add a comment |
add a comment |
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".
add a comment |
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".
add a comment |
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".
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".
edited Apr 14 '14 at 19:44
Peter Mortensen
13.5k1984111
13.5k1984111
answered May 2 '13 at 9:48
efiratefirat
2,19922434
2,19922434
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Sep 8 '11 at 21:35
HLGEMHLGEM
79.6k888157
79.6k888157
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Aug 11 '16 at 8:16
Simon Hughes
2,99231840
2,99231840
answered Oct 3 '13 at 13:16
HentoldHentold
643610
643610
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Nov 24 '18 at 7:56
BSMP
2,54952334
2,54952334
answered Nov 30 '15 at 5:48
Jason ClarkJason Clark
5431434
5431434
add a comment |
add a comment |
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
7
+1 but you should have used relevant alias names liketargett1
andsourcet1
rather than (or as well as) comments.
– Mark Hurd
Jun 30 '14 at 2:05
add a comment |
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
7
+1 but you should have used relevant alias names liketargett1
andsourcet1
rather than (or as well as) comments.
– Mark Hurd
Jun 30 '14 at 2:05
add a comment |
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
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
edited May 19 '18 at 19:28
answered Jun 27 '14 at 21:14
JakubJakub
1,0441227
1,0441227
7
+1 but you should have used relevant alias names liketargett1
andsourcet1
rather than (or as well as) comments.
– Mark Hurd
Jun 30 '14 at 2:05
add a comment |
7
+1 but you should have used relevant alias names liketargett1
andsourcet1
rather than (or as well as) comments.
– Mark Hurd
Jun 30 '14 at 2:05
7
7
+1 but you should have used relevant alias names like
targett1
and sourcet1
rather than (or as well as) comments.– Mark Hurd
Jun 30 '14 at 2:05
+1 but you should have used relevant alias names like
targett1
and sourcet1
rather than (or as well as) comments.– Mark Hurd
Jun 30 '14 at 2:05
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Jun 25 '16 at 21:28
Peter Mortensen
13.5k1984111
13.5k1984111
answered Sep 25 '13 at 6:18
Aleksandr FedorenkoAleksandr Fedorenko
12.7k62537
12.7k62537
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited May 19 '18 at 17:31
Peter Mortensen
13.5k1984111
13.5k1984111
answered Dec 12 '15 at 16:32
Pரதீப்Pரதீப்
75.3k1175111
75.3k1175111
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited May 19 '18 at 17:37
Peter Mortensen
13.5k1984111
13.5k1984111
answered Feb 20 '17 at 16:34
RichardRichard
919813
919813
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Jun 25 '16 at 20:46
Peter Mortensen
13.5k1984111
13.5k1984111
answered Feb 24 '16 at 23:35
sqlusersqluser
4,34772340
4,34772340
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Nov 30 '16 at 21:06
YamanYaman
650924
650924
add a comment |
add a comment |
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')
add a comment |
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')
add a comment |
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')
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')
edited May 19 '18 at 17:24
Peter Mortensen
13.5k1984111
13.5k1984111
answered Jun 18 '14 at 11:40
russruss
41336
41336
add a comment |
add a comment |
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];
1
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 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 '17 at 15:53
1
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
1
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 '17 at 18:19
add a comment |
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];
1
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 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 '17 at 15:53
1
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
1
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 '17 at 18:19
add a comment |
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];
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];
edited Oct 18 '18 at 14:24
answered Jan 26 '17 at 13:28
Bartosz XBartosz X
1,0871020
1,0871020
1
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 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 '17 at 15:53
1
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
1
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 '17 at 18:19
add a comment |
1
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 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 '17 at 15:53
1
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
1
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 '17 at 18:19
1
1
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 at 13:30
YES - there is no JOIN on purpose and NO - this can't be applied on table variables.
– Bartosz X
Jan 26 '17 at 13:30
1
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 '17 at 15:53
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 '17 at 15:53
1
1
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
What does this have to do with updating from a SELECT?
– Martin Smith
Feb 5 '17 at 18:10
1
1
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 '17 at 18:19
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 '17 at 18:19
add a comment |
The below solution works for a MySQL database:
UPDATE table1 a , table2 b
SET a.columname = 'some value'
WHERE b.columnname IS NULL ;
3
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
add a comment |
The below solution works for a MySQL database:
UPDATE table1 a , table2 b
SET a.columname = 'some value'
WHERE b.columnname IS NULL ;
3
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
add a comment |
The below solution works for a MySQL database:
UPDATE table1 a , table2 b
SET a.columname = 'some value'
WHERE b.columnname IS NULL ;
The below solution works for a MySQL database:
UPDATE table1 a , table2 b
SET a.columname = 'some value'
WHERE b.columnname IS NULL ;
edited May 19 '18 at 17:26
Peter Mortensen
13.5k1984111
13.5k1984111
answered Oct 1 '14 at 6:24
MateenMateen
685717
685717
3
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
add a comment |
3
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
3
3
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
Not working in MS SQL Server
– Eugene Evdokimov
Jun 17 '16 at 7:04
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
edited Apr 28 '18 at 12:33
user9713753
answered Apr 27 '17 at 7:54
Johannes WentuJohannes Wentu
478717
478717
add a comment |
add a comment |
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'
3
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.
– B001ᛦ
Sep 8 '16 at 12:29
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 '16 at 22:09
add a comment |
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'
3
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.
– B001ᛦ
Sep 8 '16 at 12:29
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 '16 at 22:09
add a comment |
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'
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'
edited May 19 '18 at 17:32
Peter Mortensen
13.5k1984111
13.5k1984111
answered Sep 8 '16 at 12:02
Govind TupkarGovind Tupkar
25825
25825
3
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.
– B001ᛦ
Sep 8 '16 at 12:29
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 '16 at 22:09
add a comment |
3
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.
– B001ᛦ
Sep 8 '16 at 12:29
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 '16 at 22:09
3
3
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.
– B001ᛦ
Sep 8 '16 at 12:29
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.
– B001ᛦ
Sep 8 '16 at 12:29
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 '16 at 22:09
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 '16 at 22:09
add a comment |
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
1
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
add a comment |
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
1
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
add a comment |
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...
answered Jul 31 '15 at 8:04
Cornezuelo del CentenoCornezuelo del Centeno
389318
389318
1
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
add a comment |
1
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
1
1
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
This format is what works in MS Access. Putting the JOIN at the end will get "Syntax error (missing operator)" messages. More examples here: fmsinc.com/microsoftaccess/query/snytax/update-query.html
– travis
Mar 18 '16 at 14:31
add a comment |
Consolidating all the different approaches here.
- Select update
- Update with a common table expression
- Merge
Sample table structure are below and will update from Product_BAK to Product table.
Product
CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1, 1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Description] [nvarchar](100) NULL
) ON [PRIMARY]
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 the 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 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);
add a comment |
Consolidating all the different approaches here.
- Select update
- Update with a common table expression
- Merge
Sample table structure are below and will update from Product_BAK to Product table.
Product
CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1, 1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Description] [nvarchar](100) NULL
) ON [PRIMARY]
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 the 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 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);
add a comment |
Consolidating all the different approaches here.
- Select update
- Update with a common table expression
- Merge
Sample table structure are below and will update from Product_BAK to Product table.
Product
CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1, 1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Description] [nvarchar](100) NULL
) ON [PRIMARY]
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 the 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 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);
Consolidating all the different approaches here.
- Select update
- Update with a common table expression
- Merge
Sample table structure are below and will update from Product_BAK to Product table.
Product
CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1, 1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Description] [nvarchar](100) NULL
) ON [PRIMARY]
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 the 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 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);
edited Dec 1 '18 at 2:10
answered Jan 31 '18 at 15:42
Abdul AzeezAbdul Azeez
192211
192211
add a comment |
add a comment |
You can use from this for update in sql server
UPDATE
T1
SET
T1.col1 = T2.col1,
T1.col2 = T2.col2
FROM
Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE
T1.col3 = 'cool'
add a comment |
You can use from this for update in sql server
UPDATE
T1
SET
T1.col1 = T2.col1,
T1.col2 = T2.col2
FROM
Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE
T1.col3 = 'cool'
add a comment |
You can use from this for update in sql server
UPDATE
T1
SET
T1.col1 = T2.col1,
T1.col2 = T2.col2
FROM
Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE
T1.col3 = 'cool'
You can use from this for update in sql server
UPDATE
T1
SET
T1.col1 = T2.col1,
T1.col2 = T2.col2
FROM
Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE
T1.col3 = 'cool'
answered Aug 31 '18 at 16:48
Erfan MohammadiErfan Mohammadi
1303
1303
add a comment |
add a comment |
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
set m.std_name=s.name
from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id
select * from @tblMarks
add a comment |
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
set m.std_name=s.name
from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id
select * from @tblMarks
add a comment |
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
set m.std_name=s.name
from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id
select * from @tblMarks
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
set m.std_name=s.name
from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id
select * from @tblMarks
answered Oct 8 '18 at 12:22
Saikh RakifSaikh Rakif
513
513
add a comment |
add a comment |
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 Table.id = other_table.id
WHERE sql = 'cool'
add a comment |
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 Table.id = other_table.id
WHERE sql = 'cool'
add a comment |
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 Table.id = other_table.id
WHERE sql = 'cool'
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 Table.id = other_table.id
WHERE sql = 'cool'
answered Nov 22 '18 at 6:54
CAGDAS AYDINCAGDAS AYDIN
5418
5418
add a comment |
add a comment |
1 2
next
protected by Mr. Alien Apr 11 '13 at 8:51
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?