Can we replace a number with a String in a MySQL result set?

MySQLMySQLi Database

Yes, we can do that using the CASE statement. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> isMarried boolean
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(true);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values(false);
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values(false);
Query OK, 1 row affected (0.13 sec)

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-----------+
| isMarried |
+-----------+
| 1         |
| 0         |
| 0         |
| 1         |
+-----------+
4 rows in set (0.00 sec)

Here is the query to replace a number with a String in a MySQL result set −

mysql> select isMarried, CASE isMarried WHEN 1 THEN 'Married' ELSE 'Not Married' END AS Status from DemoTable
-> ;

Output

+-----------+-------------+
| isMarried | Status      |
+-----------+-------------+
| 1         | Married     |
| 0         | Not Married |
| 0         | Not Married |
| 1         | Married     |
+-----------+-------------+
4 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 12:48:36
Advertisements