Add column to table with existing data in SQL Server - sql

I have a table Rates with data in it and I need to add new column to the table however I get the error:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'CreatedOn' cannot be added to non-empty table 'RateIncreases' because it does not satisfy these conditions
How can I do this, I have disabled prevent saving changes that required table re-creation

What part of the error do you not understand? When a column is added to an existing table, there are rows. The column is assigned to each of those rows. SQL Server has to give those rows a value. How does it do this?
It can assign the default value for the column.
It can assign NULL.
In your case, you have defined the column as NOT NULL but not provided a default value. Hence, the database does not know what to do, so it returns an error.
The simplest solution is to remove the NOT NULL constraint in the definition. Very close behind is assigning a default value.

Related

SQL Server: Add a column with calculated Field

I'm trying to alter a table to add an additional column that has the last 3 digits of org_id. I am doing this because software I am using cannot read 34000000000000000002 because of the size. I would like to turn 34000000000000000002 into 002 and put it in the new column. I thought something like below would work
alter table [org] add new_org_id integer value (select right(org_id,3));
I am very new at sql so I apologize if i'm not even close.
You were close. See the documentation for the correct syntax.
alter table [org] add new_org_id as right(org_id,3);
Also, you may want to make this a persisted computed column
PERSISTED Specifies that the Database Engine will physically store the
computed values in the table, and update the values when any other
columns on which the computed column depends are updated. Marking a
computed column as PERSISTED allows an index to be created on a
computed column that is deterministic, but not precise. For more
information, see Indexes on Computed Columns. Any computed columns
used as partitioning columns of a partitioned table must be explicitly
marked PERSISTED. computed_column_expression must be deterministic
when PERSISTED is specified.
Pretty close I think.
I'd do
alter table [org] add new_org_id integer
UPDATE [org]
SET new_org_id = right(org_id,3);

performance impact of default value set on table's column in postgresql

if a table have default value on a column for e.g.
create table emp
(
flag smallint default 1
)
so is there any impact of this default column in bulk import , if I am not using in insert statement.
According to the docs:
Before 11:
Adding a column with a default requires updating each row of the table (to store the new column value). However, if no default is specified, PostgreSQL is able to avoid the physical update. So if you intend to fill the column with mostly nondefault values, it's best to add the column with no default, insert the correct values using UPDATE, and then add any desired default as described below.
source
11 and after:
From PostgreSQL 11, adding a column with a constant default value no longer means that each row of the table needs to be updated when the ALTER TABLE statement is executed. Instead, the default value will be returned the next time the row is accessed, and applied when the table is rewritten, making the ALTER TABLE very fast even on large tables. However, if the default value is volatile (e.g., clock_timestamp()) each row will need to be updated with the value calculated at the time ALTER TABLE is executed. To avoid a potentially lengthy update operation, particularly if you intend to fill the column with mostly nondefault values anyway, it may be preferable to add the column with no default, insert the correct values using UPDATE, and then add any desired default as described below.
source
If you take a look into the source for the generator/planner/optimizer/rewriter
( postgresql/src/backend/rewrite/rewriteHandler.c around line#1112, function build_column_default() ) :
The default value(or function, e.g. for serials) is fetched from the catalogs and added once to the query tree. So, the DEFAULT may even be more efficient than fetching separate values for all affected rows from one of the tables in query.
But you would have to measure the difference to be sure.

Insertion SQL and NOT NULL values

I've created a table schema and specified that for some attributes, values cannot be null. For one column of this table, values are to be imported from a column of some another table but the problem i am facing is that when i use insert statement to copy values from that column of another table to the column of this newly created table, the attributes of this new column start screaming because they kind of have a constraint on them that while insertion their values cannot be NULL!
How do i cope with this?
One solution is that for other attributes, just for time being, i can state that null values can be accommodated so that i can successfully import values from column of other table and then later on put condition on the remaining attributes that values are not be NULL. But how do i do do this?
You need to convert NULL to some DEFAULT values while importing.
I am not sure which DB engine you are using, in mysql:
Use something like IFNULL(column_name, "").
Reference
You may simply be looking for the default clause. When you define a column, you can specify;
intcol int not null default 0
If the column is not specified for an insert, then it will default to 0. In some databases, if a NULL value is supplied, it will also get the default value.

phpPgAdmin automatically creates null row during adding a column

I have a table, called "Route" (part of a production postgres database). Because of a missing column "arrival_time", I used the "Add column" function of phpPgAdmin. There, I added each important property (name, type). When I browse the column after it was created, there is automatically created a value:
arrival_time | count
--------------------
NULL | 9358
Because of this, I cannot set the constraint "NOT_NULL", but which is required. What is the reason for this automatically created value? And how can I avoid it or fix this issue?
This is not a phpPgAdmin issue. You must either add the new column with NULL (which is the default anyway), or add with NOT NULL constraint and a DEFAULT clause. If neither is present, PostgreSQL doesn't know what to do with existing rows.
When a column is added with ADD COLUMN, all existing rows in the table are initialized with the column's default value (NULL if no DEFAULT clause is specified). If there is no DEFAULT clause, this is merely a metadata change and does not require any immediate update of the table's data; the added NULL values are supplied on readout, instead.
If you already added the column, you can use a single UPDATE to set all existing rows to a starting value, f.ex.:
UPDATE table SET arrival_time = NOW();
After that, you can add a NOT NULL constraint to this column.

How to insert columns in between in table in sql server 2008

I want to add or update columns using alter table if i am adding a new column i want show error. I am using the code below
alter table Personal_Details alter columns DOB datetime
if i uncheck the NULL to not NULL then it will shows column does not allow nulls; update fails;
i want to insert the fields in between columns not at end.
Plese fix my bug,
Thanks in advance.
The position of the column in the table declaration has nothing to do with its being NULL or NOT NULL.
If you are adding a column (of any type) which you want to be NOT NULL, i.e. you want to prohibit NULL values in that column, and the table already contains some rows, you must also provide some default value. For example:
ALTER TABLE Personal_Details
ADD COLUMN DOB datetime NOT NULL DEFAULT (GETDATE())
Otherwise the engine will attempt to add that column with NULLs as its values, which will violate the NOT NULL property, and the change, therefore, will be reverted.
Basically, the same applies when you want to set an existing column's NOT NULL property on while the column already contains NULLs. But in this case you must explicitly eliminate the NULLs before the change by either replacing them with values or removing the respective rows.
Source:
ALTER TABLE (Transact-SQL). (The particular section related to your problem is just above this code snippet.)
1)For ur adding column with not null problem
Use
ALTER TABLE Personal_Details ADD COLUMN DOB datetime NULL
Update the DOB column with the required dates and make sure there is no null in the column
then alter the column using
ALTER TABLE Personal_Details ALTER COLUMN DOB datetime not NULL
2)For your column going to the end problem...
you should not be worried...the order in which the columns are arranged doesnt matter...unless u are using a pathetic way of accessing data by column order..in which case again..u should stop accessing it by column order...
If the column order really matters you can change it using design option in the sql management table(rightclick on table >design and drag the column to its required place.)