Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server how to set a default value when the column is null

Tags:

sql-server

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.

like image 507
user2594582 Avatar asked Jul 18 '13 08:07

user2594582


People also ask

Can a nullable column have a default value?

The Simple Answer If the column is nullable then it will create the column with a NULL value instead of the default value, however, if column is not nullable and there is a default value, SQL Server has to apply that value to column to avoid violating not null constraint.

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

We can replace NULL values with a specific value using the SQL Server ISNULL Function. The syntax for the SQL ISNULL function is as follow. The SQL Server ISNULL function returns the replacement value if the first parameter expression evaluates to NULL.

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.


3 Answers

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.

like image 161
i-one Avatar answered Oct 11 '22 16:10

i-one


Use case

select case 
          when user_Name is null then "default value" 
          else user_name 
       end  
from table
like image 33
zxc Avatar answered Oct 11 '22 17:10

zxc


For existing rows (Assuming column is varchar)

ALTER TABLE TableName ADD CONSTRAINT ConstraintName DEFAULT N'Default Value' FOR ColumnName;
like image 39
Jay Patel Avatar answered Oct 11 '22 16:10

Jay Patel