Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating null to string using + results in null

Tags:

sql

ms-access

I have the following SQL Query in Access:

SELECT ID, CurrencyName + ' (' + CurrencySymbol + ')' AS [Currency], 
CurrencyLocation, CurrencySymbol FROM Currencies ORDER BY SortOrder

What I noticed is that I get a full table of results except if if the field CurrencySymbol is left NULL or empty. If the CurrencySymbol field is null, rather than Concatenate nothing, Access skips over the record and continues as shown below

Snapshot of Access.

Did I get something wrong or is there a better way to write this Query?

like image 237
Paul Williams Avatar asked Aug 09 '15 12:08

Paul Williams


2 Answers

If you concatenate strings with +, string + NULL yields NULL.

If you concatenate strings with &, string & NULL yields string.

Thus, you have two options to fix this:

Option 1: CurrencyName + ' (' + Nz(CurrencySymbol, '') + ')'. Nz (NullToZero) converts Null values to its second argument.

Option 2: CurrencyName & ' (' & CurrencySymbol & ')'

You can use this fact to create an expression that only shows the parenthesis when a currency symbol is present (Credit for this idea goes to this blog post):

CurrencyName & (' (' + CurrencySymbol + ')') will yield Points and Euro (€).

like image 183
Heinzi Avatar answered Nov 15 '22 01:11

Heinzi


That's because concatenating a string and NULL results in NULL.

SELECT ID, CurrencyName + ' (' + Iif(IsNull(CurrencySymbol), '', CurrencySymbol) + ')'
  AS [Currency], CurrencyLocation, CurrencySymbol
FROM Currencies
ORDER BY SortOrder
like image 35
Amit Avatar answered Nov 15 '22 02:11

Amit