How to write a valid MySQL query and update with a custom variable?


Let us first create a table −

mysql> create table DemoTable2027
   -> (
   -> UserId int
   -> );
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2027 values(10);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable2027 values(20);
Query OK, 1 row affected (0.28 sec)

mysql> insert into DemoTable2027 values(31);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable2027 values(11);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2027;

This will produce the following output −

+--------+
| UserId |
+--------+
| 10     |
| 20     |
| 31     |
| 11     |
+--------+
4 rows in set (0.00 sec)

Here is the query to write a valid query and update with a custom variable −

mysql> set @uId:=100;
Query OK, 0 rows affected (0.00 sec)

mysql> update DemoTable2027
   -> set UserId=(@uId:=@uId+10);
Query OK, 4 rows affected (0.13 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records. −

mysql> select *from DemoTable2027;

This will produce the following output −

+--------+
| UserId |
+--------+
| 110    |
| 120    |
| 130    |
| 140    |
+--------+
4 rows in set (0.00 sec)

Updated on: 06-Apr-2020

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements