1

how to add not null column in existing table and then insert values in that column ?? in sql...

4
  • Which database server are you using? Microsoft SQL Server, MySql, etc? Commented Jan 10, 2016 at 10:12
  • 1
    If table has data, you can't. You have to add it as Null then populate the column for all rows and finally alter it to not null. Commented Jan 10, 2016 at 10:27
  • @shadow, as I've pointed out in my answer you can, if you specify a DEFAULT... Commented Jan 10, 2016 at 10:31
  • @Shnugo That's true! Nice! Commented Jan 10, 2016 at 10:35

1 Answer 1

3

If you want to add a NOT NULL column you must specify a DEFAULT:

ALTER TABLE YourTable 
    ADD SomeColumn INT NOT NULL 
    CONSTRAINT DF_YourTable_SomeColumn DEFAULT(0);

Other possibility is to add it with NULL, add your data and alter it to NOT NULL later (see ALTER TABLE)

EDIT: Your comment about "how to insert values"...

This depends very much in your needs. If you want to set all rows to the same value it is:

UPDATE YourTable SET SomeColumn=0;
Sign up to request clarification or add additional context in comments.

4 Comments

then how to insert values in that column ??
@RahulSirohi, edited my answer... This is absolute base knowledge actually. So please use one of the millions of tutorials you'll find out there...
if i want to add different values ?
@RahulSirohi, really... How should I answer this without any knowledge about your data table and its content??? If there is a unique key (might be a primary key) you can set each row separately with UPDATE YourTable SET SomeColumn=aValue WHERE TheKey=123;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.