andrew slaughter andrew slaughter - 7 months ago 18
SQL Question

Set default value in query when value is null

I'm running a really simple query, however for some of the results the value in one field is null. How can I set that value to "a string" if its value is null?

Something like

SELECT RegName,
RegEmail,
RegPhone,
RegOrg,
RegCountry,
DateReg,
(Website IS NULL? 'no website' : Website) AS WebSite
FROM RegTakePart
WHERE Reject IS NULL


It will be running on a sql server 2005

thanks

Answer

Use the following:

SELECT RegName,
       RegEmail,
       RegPhone,
       RegOrg,
       RegCountry,
       DateReg,
       ISNULL(Website,'no website')  AS WebSite 
FROM   RegTakePart 
WHERE  Reject IS NULL

or as, @Lieven noted:

SELECT RegName,
       RegEmail,
       RegPhone,
       RegOrg,
       RegCountry,
       DateReg,
       COALESCE(Website,'no website')  AS WebSite 
FROM   RegTakePart 
WHERE  Reject IS NULL

The dynamic of COALESCE is that you may define more arguments, so if the first is null then get the second, if the second is null get the third etc etc...

Comments