Arkadiusz
Arkadiusz

Reputation: 427

First column with NULL value in a table

I would like to get to know how I can get the first column with NULL value from the left for each row in my table, I've tried with SELECT CASE but it doesn't work the way I would like.

Guys, I'd like to be crystal-clear about what I want to accomplish. I have a table with 22 columns and there are rows in which last 10 columns have NULL values but I need to get to know only a name of the first column from the left with NULL value.

Upvotes: 1

Views: 1706

Answers (3)

Alex
Alex

Reputation: 741

The only general approach here is case statement:

Case
when col1 is null then 'col1'
when col2 is null then 'col2'
when col3 is null then 'col3'
end as frst_null

This way frst_null would contain the name of the first column containing Null value. You can order columns whichever order you like.

Upvotes: 0

Matt
Matt

Reputation: 15071

Just specify NULL as your first field selection.

SELECT NULL, FieldA, FieldB, FieldC etc
FROM yourtable

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269753

You get the value from the first non-NULL column using coalesce():

select coalesce(col1, col2, col3, . . .)

You can get the name using case logic:

select (case when col1 is not null then 'col1'
             when col2 is not null then 'col2'
             . . .
        end)

Upvotes: 0

Related Questions