Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL View - add default values if null?

I'm generating a view, and I want to populate cells with a pre-defined value if they are null.

The select for the view is:

SELECT a_case.Id, 
    R1.Type AS Referred_by_1,
    R1.Type AS Referred_by_2,
    R1.Type AS Referred_by_3
FROM dbo.CaseInfo a_case LEFT JOIN
    dbo.Referrer R1 ON P.Id = R1.Case_Id AND R1.Seq = 1 LEFT JOIN
    dbo.Referrer R2 ON P.Id = R2.Case_Id AND R2.Seq = 2 LEFT JOIN
    dbo.Referrer R3 ON P.Id = R3.Case_Id AND R3.Seq = 3 

The referrers are optional, and if not specified, I need to populate the field with 'ND'.

I think I maybe should be using CASE WHEN, but I'm not sure how to integrate that into the existing select...

Any advice gratefully received! - L

like image 703
laura Avatar asked Feb 10 '11 11:02

laura


People also ask

Can SQL default value be NULL?

By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL is used to prevent inserting NULL values into the specified column, considering it as a not accepted value for that column.

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

You can use ISNULL:

SELECT a_case.Id,      
    ISNULL(R1.Type, 'ND') AS Referred_by_1,     
    ISNULL(R2.Type, 'ND') AS Referred_by_2,     
    ISNULL(R3.Type, 'ND') AS Referred_by_3 
FROM ...
like image 158
Klaus Byskov Pedersen Avatar answered Sep 21 '22 17:09

Klaus Byskov Pedersen


Use COALESCE e.g.

SELECT a_case.Id, 
       COALESCE(R1.Type, 'ND') AS Referred_by_1,
       COALESCE(R2.Type, 'ND') AS Referred_by_3,
       COALESCE(R3.Type, 'ND') AS Referred_by_3
  FROM ...
like image 44
onedaywhen Avatar answered Sep 21 '22 17:09

onedaywhen


case when R1.Type is null then 'ND' else R1.Type end AS Referred_by_3
like image 38
x2. Avatar answered Sep 21 '22 17:09

x2.