Syntax error Alternative to MySQL CASE WHEN in MySQL

Alternative to MySQL CASE WHEN in MySQL



Use IF() method as an alternative to CASE WHEN in MySQL. Let us first create a table −

mysql> create table DemoTable1593
   -> (
   -> PlayerScore int
   -> );
Query OK, 0 rows affected (0.44 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1593 values(78);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1593 values(0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1593 values(89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1593 values(0);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1593;

This will produce the following output −

+-------------+
| PlayerScore |
+-------------+
|          78 |
|           0 |
|          89 |
|           0 |
+-------------+
4 rows in set (0.00 sec)

Here is the query to use MySQL IF() −

mysql> select if(PlayerScore=0,'',PlayerScore) from DemoTable1593;

This will produce the following output −

+----------------------------------+
| if(PlayerScore=0,'',PlayerScore) |
+----------------------------------+
| 78                               |
|                                  |
| 89                               |
|                                  |
+----------------------------------+
4 rows in set (0.00 sec)
Updated on: 2019-12-16T07:04:51+05:30

704 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements