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 which will return ColumnA, and then a second column which will either show the value of ColumnB unless ColumnB is null; otherwise it will show the value of ColumnC, even it it's NULL. Can I use an IF statement for that? Something like:
SELECT ColumnA,
IF(ColumnB IS NULL, ColumnC, ColumnB)
FROM table
**If I get this working, the next step would be to return the value of a joined column instead of ColumnB. In effect the IF statement would be
IF(table.ColumnB IS NULL, table.ColumnC, table2.ColumnD)
The coalesce in MySQL can be used to return first not null value. If there are multiple columns, and all columns have NULL value then it returns NULL otherwise it will return first not null value. The syntax is as follows. SELECT COALESCE(yourColumnName1,yourColumnName2,yourColumnName3,.......
Use COALESCE
SELECT ColumnA, COALESCE(ColumnB, ColumnC) as 'Value'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With