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.
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.
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.
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.
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.
Use case
select case
when user_Name is null then "default value"
else user_name
end
from table
For existing rows (Assuming column is varchar
)
ALTER TABLE TableName ADD CONSTRAINT ConstraintName DEFAULT N'Default Value' FOR ColumnName;
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