SELECT vs SET in SQL




SET
SELECT
Set statements are used only for assigning values to variables.

SET @x = 1;

Select statements are used both for assigning values to variables and for querying data.

SELECT @x = 1;

SELECT @age = p.age
FROM persons p
When performing assignments, SET can perform only one assignments at once.

SET @x = 1@y = 2 would not work
When performing assignments, SELECT can perform multiple assignments at once.

SELECT @x = 1@y = 2 would work fine
Performance wise, SET is a little bit slower when compared to SELECT. This is because the operator separately assigns values to each individual variable.

SELECT is faster than SET in a way that it allows multiple assignments in a single go instead of making variable assignments separately.
When making assignment from a query that returns more than one rows of result, SET will raise an error.


When making assignment from a query that returns more than one rows of result, SELECT will assign the last result value to variable.


When making assignment from a query that returns no results, SET will assign NULL to the variable 


When making assignment from a query that returns no results, SELECT will not make assignment so the variable will remain unchanged.


Comments