Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 493
andrew slaughter Avatar asked Oct 09 '13 09:10

andrew slaughter


People also ask

Can SQL default value be NULL?

By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL is used to prevent inserting NULL values into the specified column, considering it as a not accepted value for that column.

How do I change the default value of NULL in SQL?

In SQL, we can use two functions to replace null entries with a default value. These functions are COALESCE() and ISNULL() . We'll use only the COALESCE() method in this Answer.

Can a default value be NULL?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

Can a default constraint be NULL?

The DEFAULT value constraint only applies if the column does not have a value specified in the INSERT statement. You can still insert a NULL into an optional (nullable) column by explicitly inserting NULL.


2 Answers

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...

like image 73
Giannis Paraskevopoulos Avatar answered Sep 24 '22 00:09

Giannis Paraskevopoulos


As noted above, the coalesce solution is preferred. As an added benefit, you can use the coalesce against a "derived" value vs. a selected value as in:

SELECT
       {stuff},
       COALESCE( (select count(*) from tbl where {stuff} ), 0 )  AS countofstuff
FROM
       tbl
WHERE
       {something}

Using "iif" or "case" you would need to repeat the inline whereas with coalesce you do not and it allows you to avoid a "null" result in that return...

like image 28
T. Baum Avatar answered Sep 25 '22 00:09

T. Baum