18

What's the difference between DECLARE and SET using SQL (or more specifically MySQL)?

Both can set variables it seems. I have read the MySQL docs and I did not understand the difference between the two.

jww
  • 97,681
  • 90
  • 411
  • 885
C H
  • 185
  • 1
  • 1
  • 6

2 Answers2

17

DECLARE does not initialize the variable. When you declare it you declare the variable name, the type, and a default value, which could be an expression.

SET is for initializing the variable you declared previously, and you cannot SET the variable until you DECLARE it.

Leigh
  • 28,765
  • 10
  • 55
  • 103
Hituptony
  • 2,740
  • 3
  • 22
  • 44
  • Thank you! So you have to use both when creating a variable with a value unless you use "DEFAULT". Understood. – C H Nov 19 '13 at 14:22
  • `you cannot SET the variable until you DECLARE it` not sure about version then, but we can't use `DECLARE` outside a stored procedure to declare a variable. We directly use `SET @newVar := 213` to declare as well as initialize – mr.loop Jan 05 '23 at 08:10
8

DECLARE defines the variable type and SET initializes the variable.

DECLARE @Var1 INT;
DECLARE @Var2 INT;
SET @Var1 = 1;
SET @Var2 = 2;
Leigh
  • 28,765
  • 10
  • 55
  • 103
Anand Mishra
  • 400
  • 2
  • 13