SQL Server – Parentheses Use in SET Statement

selectsql servert-sql

I am trying to compute the number of distinct pairs sender_id, send_to_id and assign it to a variable @UniqueRequests. When I try the statmement below, I get an error saying the syntax near ) is incorrect.

DECLARE @UniqueRequests int;
SET @UniqueRequests = (SELECT COUNT(*) FROM (SELECT DISTINCT sender_id, send_to_id FROM friend_request));

So my questions would be

  1. What is the correct statement?
  2. It seems that we must use parentheses around a SELECT when assigninig a variable. That is to say, we need to write SET @MyVariable = (SELECT some_expression); Why is that so?
  3. Is there any documentation page on the use of parentheses in SQL Server in general?

Thank you for your help!

Best Answer

Actually this error is a bit confusing and that's the reason you are asking these questions.

Correct statement would be:

DECLARE @UniqueRequests int;
SET @UniqueRequests = (SELECT COUNT(*) FROM (SELECT DISTINCT sender_id, send_to_id FROM friend_request) friends);

I did testing on some other table with same concept and you may see the result as below:

Select Distinct

Answer to these questions are as below:

  1. What is the correct statement?
DECLARE @UniqueRequests int;
SET @UniqueRequests = (SELECT COUNT(*) FROM (SELECT DISTINCT sender_id, send_to_id FROM friend_request) friends);
  1. It seems that we must use parentheses around a SELECT when assigninig a variable. That is to say, we need to write SET @MyVariable = (SELECT some_expression); Why is that so?

This is because you are setting the value, and you can't assign keyword and other strings to an int, rather you want to assign the value which means query has to run first and that result you want to assign to this particular integer variable.

Alternatively if you wish to only set the value, you can use below:

DECLARE @UniqueRequests int;
select @UniqueRequests = COUNT(*) FROM CommandLog
print @UniqueRequests
  1. Is there any documentation page on the use of parentheses in SQL Server in general?

You may refer this from Micrososoft, this thread and this link.

Hope this helps.