24

This is my sql in SQL server:

SELECT user_Name ,user_pass ,user_hometown FROM user_baseinfo   

Sometimes the column can be null. When it is, I want to replace it with a default value.

4 Answers 4

29
SELECT
    ISNULL(user_Name, 'Unknown Name') AS user_Name,
    ISNULL(user_pass, 'Unknown Pass') AS user_pass,
    ISNULL(user_hometown, 'Unknown Hometown') AS user_hometown
FROM user_baseinfo

Be aware though that ISNULL has precedence of the first argument type. This may cause undesired cutting of the default value, if column in the first argument has type, which is shorter than that of the default value. In such cases COALESCE is the better choice.

Below is an example showing the difference between ISNULL and COALESCE:

CREATE TABLE #Sample (Value1 varchar(100), Value2 char(3));

INSERT INTO #Sample (Value1, Value2)
VALUES
    ('AAA', 'AAA'),
    ('BBB', 'BBB'),
    ('CCC', 'CCC'),
    (NULL, NULL);

SELECT
    ISNULL(Value1, 'Default') AS Value1,
    ISNULL(Value2, 'Default') AS Value2
FROM #Sample;

SELECT
    COALESCE(Value1, 'Default') AS Value1,
    COALESCE(Value2, 'Default') AS Value2
FROM #Sample;

See that Default cuts down to Def when ISNULL is used.

19

Use case

select case 
          when user_Name is null then "default value" 
          else user_name 
       end  
from table
1
  • 1
    Can shorter: isnull(val1, val2) and this way it will respect column specification, so insert from that select will not fail cause of too long replacement. Nov 8, 2017 at 20:12
3

For existing rows (Assuming column is varchar)

ALTER TABLE TableName ADD CONSTRAINT ConstraintName DEFAULT N'Default Value' FOR ColumnName;
3

You want to use the DEFAULT keyword.

Example taken from website

CREATE TABLE Persons
(
    P_Id int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255) DEFAULT 'Sandnes'
)

Here is a link to the site.

2
  • 1
    There are also times when the structure of the DB cannot be changed, and the default value is only needed in one query, this answer is not good for generic cases.
    – TheBat
    Nov 24, 2014 at 21:15
  • 2
    For MS SQL, default values must be not null otherwise MS SQL will not insert a default value. Apr 27, 2020 at 0:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.