Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB2: How to concatenate null strings in DB2?

Tags:

sql

database

db2

I have to concatenate 2 columns (ex. FIRSTANME and LASTNAME).
I do it this way:

FIRSTNAME || ' ' || LASTNAME`.   

If one of them is null, but the other one is not null, I get null as concatenation result.
And I want following behavior

FIRSTNAME = null and LASTNAME = "Smith" ==> 
  FIRSTANME || ' ' || LASTNAME == ' Smith'. 

How to solve this in DB2?

like image 584
adrift Avatar asked Sep 29 '11 11:09

adrift


People also ask

How do I concatenate strings in SQL Db2?

You can concatenate strings by using the CONCAT operator or the CONCAT built-in function. When the operands of two strings are concatenated, the result of the expression is a string. The operands of concatenation must be compatible strings.

How do I concatenate fields in Db2?

The DB2 CONCAT function will combine two separate expressions to form a single string expression. You can also combine two seperate expression to form a single string expression using '||' (double pipe) notation. Concatenation: It is joining values together (by appending them to each other) to form a single long value.

How does Db2 handle null values?

A null value is a special value that Db2 interprets to mean that no data is present. If you do not specify otherwise,Db2 allows any column to contain null values. Users can create rows in the table without providing a value for the column. Using the NOT NULL clause enables you to disallow null values in the column.

What does || mean in Db2?

4. The || is the concatenation operator in SQL.


1 Answers

Use coalesce

...
CONCAT( COALESCE(firstname,'') , COALESCE(lastname,'') )

Or using the || concat operator

...
COALESCE(firstname,'') || COALESCE(lastname,'') 

Note that IBM recomments using the keyword concat and not the || operator.

Concat: http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2.doc.sqlref%2Ffconc.htm
Coalesce: http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2.doc.sqlref%2Ffcoal.htm

like image 192
Johan Avatar answered Sep 29 '22 18:09

Johan