Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Update Column Data Without Using Temporary Tables in MySQL



For this, use CASE statement. This will work even without using temporary tables. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> UserName varchar(100),
   -> UserStatus varchar(100)
   -> );
Query OK, 0 rows affected (0.74 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John','Active');
Query OK, 1 row affected (0.29 sec)

mysql> insert into DemoTable values('Chris','Inactive');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('Bob','Inactive');
Query OK, 1 row affected (0.32 sec)

mysql> insert into DemoTable values('Robert','Active');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----------+------------+
| UserName | UserStatus |
+----------+------------+
| John     | Active     |
| Chris    | Inactive   |
| Bob      | Inactive   |
| Robert   | Active     |
+----------+------------+
4 rows in set (0.00 sec)

Following is the query to update column data using CASE −

mysql> update DemoTable
   -> set UserStatus=CASE UserStatus WHEN 'Inactive' THEN 'Active' ELSE 'Inactive' END;
Query OK, 4 rows affected (0.28 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----------+------------+
| UserName | UserStatus |
+----------+------------+
| John     | Inactive   |
| Chris    | Active     |
| Bob      | Active     |
| Robert   | Inactive   |
+----------+------------+
4 rows in set (0.00 sec)
Updated on: 2020-06-30T11:20:32+05:30

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements