Return one of the two columns in the view - whichever is not null

I have a table with three columns:

ColumnA          ColumnB         ColumnC
AAA               NULL            123
BBB               222             NULL
CCC               NULL            NULL

I would like to create a SELECT statement that will return ColumnA and then a second column that will either show the value of ColumnB if ColumnB is not null; otherwise, it will display the ColumnC value, even if it is NULL. Can I use the IF statement for this? Sort of:

SELECT ColumnA, 
IF(ColumnB IS NULL, ColumnC, ColumnB)
FROM table

** If I get this working, the next step is to return the value of the merged column instead of column B. Essentially, the IF statement will be

IF(table.ColumnB IS NULL, table.ColumnC, table2.ColumnD)
+3
source share
2 answers

Reading to the end of your question seems like you need to use CASE

CASE WHEN table.ColumnB IS NULL 
     THEN table.ColumnC 
     ELSE table2.ColumnD 
END AS Whatever
+2
source

Use COALESCE

SELECT ColumnA, COALESCE(ColumnB, ColumnC) as 'Value'

+11

Source: https://habr.com/ru/post/1796395/


All Articles