What is the difference between = and := in MySQL?
Asked Answered
J

4

24

What is the difference in between

set test_var = 20;

and

set test_var:=20;

as they both seem to assign the value ?

Jaguarundi answered 25/3, 2013 at 11:47 Comment(0)
S
17

Both of them are assignment operators but one thing I can find their differences is that = can be used to perform boolean operation while := cannot.

valid: SUM(val = 0)
Invalid: SUM(val := 0)

FROM User-Defined Variables

One more thing, You can also assign a value to a user variable in statements other than SET. In this case, the assignment operator must be := and not = because the latter is treated as the comparison operator = in non-SET statements.

mysql> SET @t1=1, @t2=2, @t3:=4;
mysql> SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;
+------+------+------+--------------------+
| @t1  | @t2  | @t3  | @t4 := @t1+@t2+@t3 |
+------+------+------+--------------------+
|    1 |    2 |    4 |                  7 | 
+------+------+------+--------------------+
Sallee answered 25/3, 2013 at 11:50 Comment(0)
E
18

It's more or less Syntactic sugar.

Take a look here

Most important difference is

Unlike =, the := operator is never interpreted as a comparison operator. This means you can use := in any valid SQL statement (not just in SET statements) to assign a value to a variable.

Esemplastic answered 25/3, 2013 at 11:49 Comment(0)
S
17

Both of them are assignment operators but one thing I can find their differences is that = can be used to perform boolean operation while := cannot.

valid: SUM(val = 0)
Invalid: SUM(val := 0)

FROM User-Defined Variables

One more thing, You can also assign a value to a user variable in statements other than SET. In this case, the assignment operator must be := and not = because the latter is treated as the comparison operator = in non-SET statements.

mysql> SET @t1=1, @t2=2, @t3:=4;
mysql> SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;
+------+------+------+--------------------+
| @t1  | @t2  | @t3  | @t4 := @t1+@t2+@t3 |
+------+------+------+--------------------+
|    1 |    2 |    4 |                  7 | 
+------+------+------+--------------------+
Sallee answered 25/3, 2013 at 11:50 Comment(0)
B
3

You can only use := for assignment - never for comparison. It's just a bit of syntactic sugar, it doesn't really change the functionality at all. You'll see it a lot in generated SQL from code.

Bridal answered 25/3, 2013 at 11:51 Comment(1)
Dang, everyone beats me to it. Hah.Bridal
D
1

Using := in a SET and SELECT statement is interpreted as assignment.

Using = in a SET statement is interpreted as assignment.

However, Using = in a SELECT statement is interpreted as a bool operator (comparison).

So if you mean assignment, it is always safe to use :=

Durable answered 9/1, 2022 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.