6

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;

3 Answers 3

16

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.

6
select
  isnull(col1, defaultvalue)
from
  tblname;
0

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.

1
  • "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. Nov 12, 2008 at 6:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.