Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does t-sql update work without a join

I think my head is muddy or something. I'm trying to figure out how a t-sql update works without a join when updating one table from another. I've always used joins in the past but came across a stored proc where someone else created one without a join. This update is being used in SQL 2008R2 and it works.

Update table1

SET col1 = (SELECT TOP 1 colX FROM table2 WHERE colZ = colY),

col2 = (SELECT TOP 1 colE FROM table2 WHERE colZ = colY)

Obviously, colY is a field in table1. To get the same results in a select statement (not update), a join is required. I guess I don't understand how an update works behind the scenes but it must be doing some kind of join?

like image 661
user2437255 Avatar asked Apr 28 '26 00:04

user2437255


1 Answers

SQL Server translates those subqueries into joins. You can look at this by getting the query plan. You can write an equivalent query with UPDATE ... FROM ... JOIN syntax and observe the query plan to be essentially the same.

The sample code shown is unusual, hard to understand, redundant and inflexible. I recommend against using this style.

like image 134
usr Avatar answered Apr 29 '26 13:04

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!