Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use SQL to display custom text that is based on the column value?

Tags:

sql

mysql

Is there a way to show different strings based on value found in a column?

i.e.

SELECT value FROM table;

+--------+
| value  |
+--------+
|      1 |
|      0 |
|      1 |
|      1 |
+--------+

The output I want is this:

+--------+
| value  |
+--------+
|    yes |
|     no |
|    yes |
|    yes |
+--------+

How?

like image 977
Dennis Avatar asked Dec 23 '22 23:12

Dennis


2 Answers

Using CASE statement you can get the expected result:

SELECT CASE WHEN value = 1 THEN 'yes' 
            WHEN value = 0 THEN 'no' 
            ELSE '' 
       END AS value
FROM testtable;

or using IF statement

SELECT IF(value = 1, 'yes', IF(value = 0, 'no', '')) AS value
FROM testtable;

Demo on db<>fiddle

like image 141
Arulkumar Avatar answered May 20 '23 18:05

Arulkumar


A fun way to do this uses elt():

select elt(value + 1, 'no', 'yes')

elt() returns the nth string based on the first argument.

like image 31
Gordon Linoff Avatar answered May 20 '23 20:05

Gordon Linoff