2

I am new to postgres.

I have fields(title) as below:

Title      Date1        Date2        Date3        Date4        Date5   Date6

Vaccine1   01/08/1980   01/08/1981   01/08/1982   01/08/1983   Null    Null

I have a situation at work where I need to find out the first null value. In the case above, it should be Date5 based on the title. I have some other conditions which need to be checked. But this would be in my main case.

I am trying to do something as below:

case
when title ='AAA'
and
??

I am stuck right there.

Any help is appreciated. Thanks.

2
  • So you want to find a record with a certain title and data5 as null? and you want to select the first of such records? Commented Oct 28, 2013 at 2:24
  • 2
    Having multiple columns that contain the same "type" of data (such that comparisons between them make sense) usually indicates that the data model is incorrect - you ought to have multiple rows with a single column that contains the date, and then an additional column that holds the data values 1-6 that have somehow become embedded in the column names. Commented Oct 28, 2013 at 7:22

1 Answer 1

2

If you want to know which column has the first NULL then you could do something like this:

case when date1 is null then 'date1'
     when date2 is null then 'date2'
     when date3 is null then 'date3'
     when date4 is null then 'date4'
     when date5 is null then 'date5'
     when date6 is null then 'date6'
     else null
end

Demo: http://sqlfiddle.com/#!1/6fd74/1

Note that the whens in a case are checked in the listed order and execution stops at the first matching when so this structure will tell you the first non-NULL column (assuming of course that the whens are in the right order).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.