4

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?

Dennis
  • 7,907
  • 11
  • 65
  • 115
  • 2
    yes, check out case statement – Brad May 16 '19 at 19:22
  • Possible duplicate of [How do I perform an IF...THEN in an SQL SELECT?](https://stackoverflow.com/questions/63447/how-do-i-perform-an-if-then-in-an-sql-select) – JeffUK May 16 '19 at 19:35

2 Answers2

7

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

Arulkumar
  • 12,966
  • 14
  • 47
  • 68
5

A fun way to do this uses elt():

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

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

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786