Altering the Table to assign default value in case of NULL

M, Murugeswari (Cognizant) 456 Reputation points
2022-02-21T15:48:59.143+00:00

We have a table in Azure Sql Database. Currently one of the columns in the table is accepting null . I want to modify the column like whenever NULL occurs from the source data, it should be assigned to a default value. How can I change it

Thanks

Azure SQL Database
0 comments No comments
{count} vote

Accepted answer
  1. Alberto Morillo 34,671 Reputation points MVP Volunteer Moderator
    2022-02-21T16:59:17.697+00:00

    Here is how you can specify a default value for a column (column_b in below example)

    CREATE TABLE dbo.doc_exz (column_a INT, column_b INT); -- Allows nulls.
    GO
    INSERT INTO dbo.doc_exz (column_a) VALUES (7);
    GO
    ALTER TABLE dbo.doc_exz
      ADD CONSTRAINT DF_Doc_Exz_Column_B
      DEFAULT 50 FOR column_b;
    GO
    

    You can update rows with a null value stored already on the column:

    UPDATE dbo.doc_exz
    SET column_b = 50
    WHERE column_b is null
    

    Let me know if this helps in your scenario.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. M, Murugeswari (Cognizant) 456 Reputation points
    2022-02-22T07:10:21.937+00:00

    Hello Alberto,

    Thanks for your quick solution.. It worked !!!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.