Q
Problem solve Get help with specific problems with your technologies, process and projects.

COALESCE on three columns

I have three columns (NUM1, NUM2, NUM3) that are of "number" datatype, and while inserting to another table using...

INSERT INTO table2 SELECT * FROM table1, I want to insert the three columns into one column (NUM) in my table2. In my case, only one of the three columns will have a value in a row, while the other two will be null. I'm using Oracle8i.

The answer for the nulls problem is to use the COALESCE function. This is a standard SQL function that takes a parameter consisting of a list of expressions:

COALESCE( expression1, expression2, ...)

The result of the function is the first non-null value starting from the left. If all the expressions in the function are null, then the result is null.

Thank you for mentioning the database system that you're using. Fortunately, Oracle supports COALESCE (otherwise you would have to build a CASE structure, which is more verbose).

insert 
  into table2 
     ( foo
     , bar
     , num )
select foo
     , bar
     , coalesce( num1, num2, num3, 0 )
  from table1

Notice that the 0 is added as a fourth expression to guard against all three of NUM1, NUM2, NUM3 being null.

For More Information


This was last published in November 2002

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close