Syntax error Only update the MySQL field if the field contains null or 0?

Only update the MySQL field if the field contains null or 0?



For this, set conditions using MySQL IF(). Let us first create a table −

mysql> create table DemoTable1592
   -> (
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1592 values(56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1592 values(NULL);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1592 values(98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1592 values(0);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1592 values(75);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1592 values(NULL);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1592;

This will produce the following output −

+--------------+
| StudentMarks |
+--------------+
|           56 |
|         NULL |
|           98 |
|            0 |
|           75 |
|         NULL |
+--------------+
6 rows in set (0.00 sec)

Here is the query to only update the field if it contains null or 0 −

mysql> update DemoTable1592 set StudentMarks=if(StudentMarks IS NULL or StudentMarks=0,33,StudentMarks);
Query OK, 3 rows affected (0.17 sec)
Rows matched: 6  Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1592;

This will produce the following output −

+--------------+
| StudentMarks |
+--------------+
|           56 |
|           33 |
|           98 |
|           33 |
|           75 |
|           33 |
+--------------+
6 rows in set (0.00 sec)
Updated on: 2019-12-16T06:52:29+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements