Is NULL necessary? - sql-server

Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)
I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.
I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?
I am guessing it does not matter from what I've tested and read.
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2

You can skip it, and by default the column will be created as NULL. However it is more legible if you indicate it explicitly.
Keep in mind that if your table already has data, you CANNOT add the column as NOT NULL. For this, you should firstly add the column as NULL, then UPDATE the values with non-null valid data and then alter column to NOT NULL.
Edit: Assuming the default behavior of the sql server when adding columns.

You don't have to write it, when you skip it column will be created as 'NULL'.
Following statements are equal:
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150) NULL;
If you want to add a column and DB engine should guarantee you that this new column will be always populated you can add a NOT NULL column with a default value.
Other option will be to change the column to NOT NULL after the update.

I'd make sure you have something declarative. And if you are setting as "not null," be sure you have a default value or use can suffer LOTS of data loss if data previously exists. It makes me nervous because this an ALTER vs a CREATE.

Related

EF - pass null value to SQL column so default value gets inserted

SQL Server table T2 has 2 columns:
Id INT NOT NULL
CreateDate DateTime NOT NULL, default = (getdate())
This statement inserts the CreateDate value correctly because it uses (getdate()) as default.
Insert T2 (Id)
Values (1)
So far so good. The problem is when I use Entity Framework to insert a row and still wish to use the default (getdate()) value.
Because the CreateDate is defined as NOT NULL, I cannot leave it blank or leave out of the Insert statement when using EF. But I want SQL to generate the timestamp on the server/database side.
Is there a way to handle this?
Thanks to squillman's reference to another SO post, I was able to find the answer.
Go to EDMX diagram, and you can set the StoreGeneratedPattern property to achieve what I am trying to do.
There are three Database Generated Options
Computed : The database generates a value when a row is inserted or updated.
Identity : The database generates a value when a row is inserted.
None : The database does not generate values.
EDIT: Although the picture shows Identity, I had to change it to Computed. The reason is that Identity option only works if the row is Inserted only. If the row is ever updated (other columns updated), then it caused an error. The Computed option seems to work fine with Insert (runs the default script) and Updates (to other columns, default script does not run again).

default date constraint has null records

We are having occasionally EMPTY records in our table/column below when there are multiple records inserted at one shot. While technically this is allowed since the column is nullable, the default constraint should apply for every row inserted.
ALTER TABLE [dbo].[JOB] ADD [DATE_CREATED] [nvarchar](35) NULL CONSTRAINT [DF_JOB_DATE_CREATED] DEFAULT (sysdatetime())
The one possible reason I could think of is "The default will only apply if you don't insert explicitly to that column". But I couldn't find anywhere code does that but I'm still working on that. Any other possible reasons?
We are on SQL Server 2012. The purpose of the column is to capture created date and time for processing. We can't have this column Non-nullable as this is a reporting column which shouldn't have a business impact.
Thank you for your advise.
Make the column NOT NULL. At the very least, do that so you can capture what application/query is explicitly inserting NULLs - which really just shouldn't be allowed.
Short of that, create a trigger:
CREATE TRIGGER trg_JOB_CreateDate
ON dbo.JOB
AFTER INSERT
AS
BEGIN
UPDATE j
SET DateInserted = GETDATE() -- consider using GETUTCDATE()
FROM JOB j
INNER JOIN inserted i
ON i.PrimaryKeyName = JOB.PrimaryKeyName
END
However, this could result in some additional transactional overhead, and won't stop someone from updating the column to = NULL. But again, if having that be null breaks something, then you really should just have the column be NOT NULL.

Insert and initialize a SQL column with value dependent on another column data

I am completely new to writing SQL scripts and could use a little help. I need to create a script that will run only once and add a column to an existing table. This column needs to have a value directly dependent to another column's value. The value is based on whether the other column's text value contains some text.
For instance, I need a way of saying for the following value "MNA-HLTH-CAR":
if (tableValue.contains("HLTH")) {
newColumn.insert("Health"); //Insert new column value Health
} else if (tableValue.contains......
At my attempt thus far I have:
ALTER TABLE [table_name]
ADD [new_element] varchar(5)
IF
CONTAINS([column_name], "HLTH")
I probably am horrible off, and could use some help. Thanks!
If the column is always dependant, and you're using a DBMS that supports it, you can use a computed column. For SQL Server, that looks like:
alter table YourTable
add YourColumn as
(
case
when OtherColumn like '%Health%' then 'HLTH'
else 'Default'
end
)
To add a real column with values, you could use a two-step approach. After adding the column:
alter table YourTable
add YourColumn varchar(5)
Run an update query to set its value:
update YourTable
set YourColumn =
case
when OtherColumn like '%Health%' then 'HLTH'
else 'Default'
end
That should initialize the new column. But unlike the computed column, it's now up to you to maintain it.

Altering a column: null to not null

I have a table that has several nullable integer columns. This is undesirable for several reasons, so I am looking to update all nulls to 0 and then set these columns to NOT NULL. Aside from changing nulls to 0, data must be preserved.
I am looking for the specific SQL syntax to alter a column (call it ColumnA) to "not null". Assume the data has been updated to not contain nulls.
Using SQL server 2000.
First, make all current NULL values disappear:
UPDATE [Table] SET [Column]=0 WHERE [Column] IS NULL
Then, update the table definition to disallow "NULLs":
ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL
I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:
ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];
You will have to do it in two steps:
Update the table so that there are no nulls in the column.
UPDATE MyTable SET MyNullableColumn = 0
WHERE MyNullableColumn IS NULL
Alter the table to change the property of the column
ALTER TABLE MyTable
ALTER COLUMN MyNullableColumn MyNullableColumnDatatype NOT NULL
For Oracle 11g, I was able to change the column attribute as follows:
ALTER TABLE tablename MODIFY columnname datatype NOT NULL;
Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.
this worked for me:
ALTER TABLE [Table]
Alter COLUMN [Column] VARCHAR(50) not null;
As long as the column is not a unique identifier
UPDATE table set columnName = 0 where columnName is null
Then
Alter the table and set the field to non null and specify a default value of 0
In case of FOREIGN KEY CONSTRAINT... there will be a problem if '0' is not present in the column of Primary key table. The solution for that is...
STEP1:
Disable all the constraints using this code :
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
STEP2:
RUN UPDATE COMMAND (as mentioned in above comments)
RUN ALTER COMMAND (as mentioned in above comments)
STEP3:
Enable all the constraints using this code :
exec sp_msforeachtable #command1="print '?'", #command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
this seems simpler, but only works on Oracle:
ALTER TABLE [Table]
ALTER [Column] NUMBER DEFAULT 0 NOT NULL;
in addition, with this, you can also add columns, not just alter it.
It updates to the default value (0) in this example, if the value was null.
In my case I had difficulties with the posted answers. I ended up using the following:
ALTER TABLE table_name CHANGE COLUMN column_name column_name VARCHAR(200) NOT NULL DEFAULT '';
Change VARCHAR(200) to your datatype, and optionally change the default value.
If you don't have a default value you're going to have a problem making this change, as default would be null creating a conflict.
Making column not null and adding default can also be done in the SSMS GUI.
As others have already stated, you can't set "not null" until all
the existing data is "not null" like so:
UPDATE myTable SET myColumn = 0
Once that's done, with the table in design view (right click on
table and click "design view"), you can just uncheck the Allow
Nulls columns like so:
Still in design view with the column selected, you can see the
Column Properties in the window below and set the default to 0 in there as well like so:
Let's take an example:
TABLE NAME=EMPLOYEE
And I want to change the column EMPLOYEE_NAME to NOT NULL. This query can be used for the task:
ALTER TABLE EMPLOYEE MODIFY EMPLOYEE.EMPLOYEE_NAME datatype NOT NULL;
For the inbuilt javaDB included in the JDK (Oracle's supported distribution of the Apache Derby) the below worked for me
alter table [table name] alter column [column name] not null;
You can change the definition of existing DB column using following sql.
ALTER TABLE mytable modify mycolumn datatype NOT NULL;
First make sure the column that your changing to not does not have null values
select count(*) from table where column's_name is null
Impute the missing values. you can replace the nulls with empty string or 0 or an average or median value or an interpolated value. It depends on your back fill strategy or forward fill strategy.
Decide if the column values need to be unique or non-unique. if they need to be unique than add an unique constraint. Otherwise, see if performance is adequate or if you need to add an index.

Force default value when adding column to table - SQL Server

In SQL Server 2000/2005,
Is it possible to force the default value to be written to already existing rows when adding a new column to a table without using NOT NULL on the new column?
You need two statements. First create the column with not null. Then change the not null constraint to nullable
alter table mytable add mycolumn varchar(10) not null default ('a value')
alter table mytable alter column mycolumn varchar(10) null
I understand your question, but you are saying that for future records, NULL (unknown, indeterminate or whatever your semantics are) is acceptable (but if it is left off in an insert, there will be a default), but that for all the existing data, you are going to go ahead and assign it the default.
I would have to look hard at this situation and ask why you are even going to allow NULLs in future records at all - given none of the historical records will have it, and there is a default in place for future records.
I doubt it.
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
The approach recommended by Microsoft is as follows (taken from the url above)
UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL
ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[**WITH VALUES]**
WITH VALUES can be used to store the default value in the new column for each existing row in the table.
more detail on MSDN link .
https://msdn.microsoft.com/en-in/library/ms190273.aspx

Resources