views:

1563

answers:

4

Hi,

I want to assign default values to a column in my select sql query so that if the value of that column is null I get that default value in my recordset. Is there anyway to do this?

Example:

select col1 (some default value) from tblname;
+5  A: 
select
  isnull(col1, defaultvalue)
from
  tblname;
Jason Lepack
A: 

if you are using SqlServer you can use the CASE statement

example:

select case col1 when null then defaultval else col1 end from tblname

where defaultval is the default value. the data type of defaultval must be the same as that of col1.

"CASE col1 WHEN NULL THEN defaultval ELSE col1 END" will *always* return col1. Equality tests against NULL always return false. You need to use "CASE WHEN col1 IS NULL THEN ..." instead.
Matt Hamilton
+6  A: 

The preferable way is to use ANSI compatible function COALESCE:

SELECT COALESCE(column_name, default_value) FROM table_name;

You also could read an article which compares COALESCE and ISNULL.

Alexander Prokofyev
A: 

link text