Undefined Variable
Undefined Variable

Reputation: 4267

conditional field selection oracle

I know I can do this in my programming language, but I want to try to do it inside the SQL so that I dont have to disturb any frontend code.

I have a table with three name fields - name1, name2, name3.

There might be values in any or all of these fields in random.

I want a query which will return three fields such that,

It will check name1,name2,name3 - which ever first field has value goes into first_name, which ever second field has value goes into second_name, and then third_field.

I can easily write a CASE-END statement for populating first_name, but when I get to writing the logic for second_name its getting more complicated.

The SQL:

SELECT 
  CASE
    WHEN NAME1 IS NOT NULL
    THEN NAME1
    ELSE
      CASE
        WHEN NAME2 IS NOT NULL
        THEN NAME2
        ELSE
          CASE
            WHEN NAME3 IS NOT NULL
            THEN NAME1
            ELSE ''
          END
      END
  END FIRST_NAME
  FROM TABLE_NAME

Now, how do I handle second_name and third_name? Or is their an easier way?

Any help is appreciated..

Upvotes: 0

Views: 714

Answers (1)

Justin Cave
Justin Cave

Reputation: 231661

You could potentially do something like

SELECT coalesce( name1, name2, name3 ) first_name,
       (case when name1 is not null 
             then nvl( name2, name3 )
             when name2 is not null
             then name3
             else null
         end) second_name,
       (case when name1 is not null and
                  name2 is not null
             then name3
             else null
         end) third_name
  FROM your_table

However the desire to do this seems to indicate that you have a data model problem that needs to be addressed. If you have three columns that apparently all store the same data, the table is not normalized correctly. It would be a better data model (and an easier query) if you stored the names in a separate table that had a 1:n relationship with the existing table.

Upvotes: 4

Related Questions