10

I'm wondering about the following query :

   UPDATE statisticsTable
   SET Value = (select count(*) 
                FROM OtherTable o
                WHERE o.UserId = UserId ) <-- this is the part that concerns me
   WHERE id in (1,2,3) 

How does SQL Server know that the second "UserId" field comes from statisticsTable and not from OtherTable ? Why can't I give an alias to statisticstable like 'stat' to clarify where I want to get that UserId ? Or is there a way?

3
  • 1
    Is this working correctly? I usually do something like WHERE o.UserId = statisticsTable.UserId to be sure. Commented Aug 16, 2017 at 14:10
  • stackoverflow.com/questions/4981481/… Commented Aug 16, 2017 at 14:11
  • Cant you have UPDATE statisticsTable as s and then have WHERE o.UserID = s.UserId in your subquery? I haven't tested this though. I've never had an UPDATE where a subquery has been neccessary. Commented Aug 16, 2017 at 14:34

4 Answers 4

17

SQL Server supports updates using joins.
This means you can write your query like this:

UPDATE s
SET Value = d.NumOfRows
FROM statisticsTable s
INNER JOIN
(
     SELECT UserId, COUNT(*) As NumOfRows
     FROM OtherTable
     GROUP BY UserId
) d ON s.UserId = d.UserId
WHERE id in (1,2,3) 
Sign up to request clarification or add additional context in comments.

3 Comments

This is something I have never seen before. Thanks!
I marked you as the answer and upvoted it to show appreciation :-)
1

Try this:

UPDATE s
   SET Value = x.cnt
from statisticsTable s
 outer apply (select count(*) as cnt
                FROM OtherTable o
                WHERE o.UserId = s.UserId ) x
WHERE s.id in (1,2,3) 

Comments

1

An alias for the table you are updating is not allowed but you can use the table name in the normal way:

UPDATE statisticsTable
SET Value = (select count(*) 
            FROM OtherTable o
            WHERE o.UserId = statisticsTable.UserId ) 
WHERE id in (1,2,3) 

Comments

0

The second "UserId" field comes from statisticsTable rather from OtherTable because the SQL server will first look for the "UserId" column within the statisticsTable. If "UserId" column exists in the statisticsTable, it will be used in the condition o.UserId = UserId. However, if there's no "UserId" column in the statisticsTable, SQL Server will then look for it in the OtherTable.

You can write the query using an alias to statisticsTable like 'stat'.

UPDATE stat
SET Value = (
SELECT COUNT(*) FROM OtherTable o
WHERE o.UserId = stat.UserId
)
FROM statisticsTable stat
WHERE stat.id IN (1,2,3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.