How to use if clause in MySQL to display Students result as Pass or Fail in a new column?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Subject varchar(100),
   -> Score int
   -> );
Query OK, 0 rows affected (0.94 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Subject,Score) values('Chris','MySQL',80);
Query OK, 1 row affected (0.32 sec)

mysql> insert into DemoTable(Name,Subject,Score) values('Robert','MongoDB',45);
Query OK, 1 row affected (0.62 sec)

mysql> insert into DemoTable(Name,Subject,Score) values('Adam','Java',78);
Query OK, 1 row affected (0.52 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----+--------+---------+-------+
| Id | Name   | Subject | Score |
+----+--------+---------+-------+
|  1 | Chris  | MySQL   |    80 |
|  2 | Robert | MongoDB |    45 |
|  3 | Adam   | Java    |    78 |
+----+--------+---------+-------+
3 rows in set (0.00 sec)

Here is the query to work with if clause in MySQL to display result in the form of Pass or Fail.

mysql> select Name,Subject,Score,if(Score > 75,"PASS","FAIL") AS Status  from DemoTable;

Output

This will produce the following output −

+--------+---------+-------+--------+
| Name   | Subject | Score | Status |
+--------+---------+-------+--------+
| Chris  | MySQL   |    80 | PASS   |
| Robert | MongoDB |    45 | FAIL   |
| Adam   | Java    |    78 | PASS   |
+--------+---------+-------+--------+
3 rows in set (0.00 sec)

Updated on: 30-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements