5

I am creating a database column like this:

Alter table tablename
add column columnname null
add constraint df_columnname default 0

After executing above SQL, the new column is added to table with null values.

Does the constraint df_cloumnname have no meaning here?

Please clarify on this..

1 Answer 1

10

If your column is nullable, then adding it with a default constraint has no impact - it can be null, and will remain null. The DEFAULT CONSTRAINT in that case only applies to new rows that are being added (and that do not explicitly specify a value for your column).

If your column were NOT NULL, then the default constraint would be applied right away.

If you're using SQL Server (you didn't specify clearly enough - SQL is the query language - but not a database product...), and you want a nullable column witha default constraint and you want the value to be applied to the existing rows, use this syntax:

ALTER TABLE dbo.tablename
ADD columnname NULL
  CONSTRAINT df_columnname DEFAULT 0 WITH VALUES

Add the WITH VALUES to your command and you should get the desired result.

Sign up to request clarification or add additional context in comments.

4 Comments

@Avinash: then you should always use the sql-server tag for your questions.
I did not under stood , WITH values option..can you please clarify..In my database, i am have an existing table with database columns nullable and also have a default constaint..I am Confused!!!
The database column nullable , after making an entry into table , the value stored for that column is the default value specified in the constraint and not null
@Avinash: as you saw: just adding a nullable column with a default constraint does not add the values to the existing rows; when you use WITH VALUES, for each of the existing rows, the defined default values will be inserted.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.