Display records with conditions set using if statement in UPDATE statement with MySQL


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentMarks int,
   -> Status varchar(20)
   -> );
Query OK, 0 rows affected (0.97 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentName,StudentMarks) values('Chris',79);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentName,StudentMarks) values('David',59);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(StudentName,StudentMarks) values('Bob',60);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(StudentName,StudentMarks) values('Mike',45);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+--------------+--------+
| StudentId | StudentName | StudentMarks | Status |
+-----------+-------------+--------------+--------+
|        1 | Chris        |           79 | NULL   |
|        2 | David        |           59 | NULL   |
|        3 | Bob          |           60 | NULL   |
|        4 | Mike         |           45 | NULL   |
+-----------+-------------+--------------+--------+
4 rows in set (0.00 sec)

Following is the query to set conditions while updating −

mysql> update DemoTable
   -> set Status=if(StudentMarks > 60 ,'PASS','FAIL');
Query OK, 4 rows affected (0.40 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+--------------+--------+
| StudentId | StudentName | StudentMarks | Status |
+-----------+-------------+--------------+--------+
|         1 | Chris       |           79 | PASS   |
|         2 | David       |           59 | FAIL   |
|         3 | Bob         |           60 | FAIL   |
|          4 | Mike       |           45 | FAIL   |
+-----------+-------------+--------------+--------+
4 rows in set (0.00 sec)

Updated on: 18-Dec-2019

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements