Tobias
Tobias

Reputation: 5453

SQL | Select only first filled column

I have the following table structure:

ID | TXT1 | TXT2 | TXT3 | TXT4 |

I just want to show/get the first filled column from this row. Is there any simple way to do this in sql?

At the moment I have a simple Java IF statement to check this. Examples:

ID | TXT1 | TXT2 | TXT3 | TXT4 |
1  | XX1  | XX2  | XX3  |      |
2  |      | YY2  |      | YY4  |

If ID == 1 then I just want the value of TXT1. If ID == 2 then I just want the value of TXT2 etc.

Upvotes: 0

Views: 271

Answers (2)

DineshDB
DineshDB

Reputation: 6193

Try this answer:

SELECT CASE WHEN TXT1!='' THEN TXT1 
            WHEN TXT2!='' THEN TXT2 
            WHEN TXT3!='' THEN TXT3 
            WHEN TXT4!='' THEN TXT4 END
FROM Your_Table
WHERE ID=1

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269773

You can use COALESCE():

select t.*, COALESCE(TXT1, TXT2, TXT3, TXT4) as first_nonnull

This assumes that the "empty" values are NULL. COALESCE() is so convenient, that if the strings are empty '' rather than NULL, you can do:

select t.*,
       COALESCE(NULLIF(TXT1, ''), NULLIF(TXT2, ''), NULLIF(TXT3, ''), NULLIF(TXT4, '')) as first_nonempty

Upvotes: 3

Related Questions