Which is Better for Performance – SELECT or SET? – Interview Question of the Week #166

Question: Which is Better for Performance – SELECT or SET?

Answer: Some questions never get old. This is one of such question.

Which is Better for Performance - SELECT or SET? - Interview Question of the Week #166 selectvsset

Remember that SELECT is designed to return data whereas SET is designed to assign values to local variables.

SET @foo1 = 1;
SET @foo2 = 2;
SET @foo3 = 3;
SELECT
@foo1 = 1,
@foo2 = 2,
@foo3 = 3;

While comparing their performance in loop SELECT statement gives better performance then SET. In other words, SET is slower than SELECT. The reason is that each SET statement runs individually and updates on values per execution, whereas the entire SELECT statement runs once and update all three values in one execution.

SET is the ANSI standard for variable assignment, SELECT is not. SET can only assign one variable at a time, SELECT can make multiple assignments at once – that gives SELECT slight speed advantage over SET. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all keeping the variable unchanged.

Reference : Pinal Dave (https://blog.sqlauthority.com)

,
Previous Post
SQL SERVER – How to Download SQL Server Native Client?
Next Post
How to Estimate Space Saved by Data Compression in SQL Server? – Interview Question of the Week #167

Related Posts

Leave a Reply

Menu