In SQL, How to add values after add a new column in the existing table? In SQL, How to add values after add a new column in the existing table? sql sql

In SQL, How to add values after add a new column in the existing table?


Two solutions.

  1. Provide a default value for the column. This value will be used initially for all existing rows. The exact syntax depends on your database, but will will usually look like ..

this:

ALTER TABLE YourTableADD YourNewColumn INT NOT NULLDEFAULT 10 WITH VALUES;
  1. Add the column with null values first. Then update all rows to enter the values you want.

Like so:

ALTER TABLE YourTableADD YourNewColumn INT NULL;UPDATE YourTable SET YourNewColumn = 10; -- Or some more complex expression

Then, if you need to, alter the column to make it not null:

ALTER TABLE YourTable ALTER COLUMN YourNewColumn NOT NULL;


Suppose you have a Employee table with these columns Employee_ID, Emp_Name,Emp_Email initially. Later you decide to add Emp_Department column to this table. To enter values to this column, you can use the following query :

Update *Table_Name* set *NewlyAddedColumnName*=Value where *Columname(primary key column)*=value

Example update TblEmployee set Emp_Department='Marketing' where Emp_ID='101'


Why don't you use UPDATE statement:

UPDATE tablename SET column=value <WHERE ...>

WHERE is optional. For instance in T-SQL for table:

enter image description here

I can update column NewTestColumn by this statement:

UPDATE [dbo].[Table] SET [NewTestColumn] = 'Some value'