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
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.
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.
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.
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.
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...
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With