Modifying null column to not null - sql-server

How to make a NULLABLE column to NOT NULL in SQL SERVER. I made a table with four columns:
My table:
id int null
fname varchar not null
last name not null
contact int null.
Now what i am required is to make id column to be not null.So please help me how we can make a null column to be a not null column.

Use the following statements to do it. Change the name of column id as required
UPDATE [Table] SET id=0 WHERE id IS NULL;
ALTER TABLE [Table] ALTER COLUMN id INTEGER NOT NULL;
Replace [Table] with the name of the table

first Update id Column '0'(Zero) where NULL then right Click on table then select Design and uncheck Allow Nulls checkbox of your Column from sql table design.

ALTER TABLE tableName
ALTER COLUMN columnName nvarchar(200) [NULL|NOT NULL]

Related

Trying to set a column not null and add a default constraint in one statement

Currently I have a column named CreatedDate in a Shipper table I created. It is nullable. My task is to change the created date to be a required field, not allow nulls, and have a default of GetDate(). This has to be done in a single query... Keep in mind there is no data in my table yet. I've tried the following code and I can't seem to get it to work. This is a homework assignment and I'm only looking for guidance. Any help would be greatly appreciated. Thanks in advance.
USE Business
ALTER TABLE Shipper
ALTER COLUMN CreatedDate date NOT NULL
CONSTRAINT CNDefaultCreatedDate
DEFAULT GETDATE() For CreatedDate;
Two different statements, I assume this is SQL Server:
--Add the default
ALTER TABLE [Shipper] --What table
ADD CONSTRAINT [def_createddate] --Give the constraint a name
DEFAULT GETDATE() FOR [CreatedDate]; --default of what for which column
--Set to not allow NULL
ALTER TABLE [Shipper] --What table
ALTER COLUMN [CreatedDate] DATE NOT NULL; --altering what column and either NULL or NOT NULL
Understand adding a default will not update existing data. I know you mentioned your table does not have data, but in the future the null values must be updated to some value before the ALTER COLUMN NOT NULL is allowed.
Here's reference to the MS documentation ALTER TABLE
If the column did not already exist you can add it, set it not null and then even update existing rows in one statement:
--If Shipper did not already have the column CreatedDate
ALTER TABLE [Shipper]
ADD [CreatedDate] DATE NOT NULL
CONSTRAINT [def_createddate] DEFAULT GETDATE()
WITH VALUE --if column is nullable use this and it will update existing records with the default. It column is NOT NULL this is applied by default.
Have you tried this:
USE Business
ALTER TABLE Shipper
ALTER COLUMN CreatedDate date NOT NULL DEFAULT GETDATE();

How to set identity constraint on existing column if data already exists in table - sybase ase 15.5

I have a table which already consists a number of records. The table has a column named 'id' of integer type and I have already inserted unique values in id column for all the records in the table.
Now I need to set IDENTITY constraint on the 'id' column so that in any new record added to the table, the value of id column gets inserted automatically incremented from the last value added to the column.
The create table query of the table is like follows:
create table Table1 (
Column1 varchar(255) not null,
Column2 varchar(254) not null,
Column3 int not null,
id int ,
PRIMARY KEY CLUSTERED ( id ) on 'default'
)
I insert data into the table using following query:
Insert into Table1 (Column1, Column2, Column3, id) values("abc","def",12,1)
But when I try to execute following Alter table query on my sybase database it returns an error "Incorrect Syntax near 'IDENTITY'"
ALTER TABLE Table1 MODIFY id int IDENTITY DEFAULT AUTOINCREMENT NOT NULL
Can anyone point me in the right direction about, how to apply IDENTITY constraint on a column which already has data?

SQL alter column datatype from nvarchar to int

Can the datatype of a field be changed to int from nvarchar??
alter table employee alter column designation int
is this valid?? If not can it be done in some other way??
P.S: I am using MS SQL Server
You can try doing an alter table. If it fails do this:
Create a new column that's an integer:
ALTER TABLE tableName ADD newCol int;
Select the data from the old column into the new one:
UPDATE tableName SET newCol = CAST(oldCol AS int);
Drop the old column
It is possible only when you column has no value or blank. If your column has some value which have nvarchar value and you should try to convert it into int, it will give error.
ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]
Add new numeric column.
Copy from old char column to new column with trim and conversion.
Drop old char column.
Rename numeric column to old column name.
This worked for me (with decimals but I suppose it will work with ints):
alter table MyTable add MyColNum decimal(15,2) null
go
update MyTable set MyColNum=CONVERT(decimal(15,2), REPLACE(LTRIM(RTRIM(MyOldCol)), ',', '.')) where ISNUMERIC(MyOldCol)=1
go
alter table MyTable drop column MyOldCol
go
EXEC sp_rename 'MyTable.MyColNum', 'MyOldCol', 'COLUMN'
go
Can be done even simpler in just 2 steps
Update the column and set all non numberic values to null so alter won't fail.
Alter the table and set the type to int.
UPDATE employee
SET designation = (CASE WHEN ISNUMERIC(designation)=1 THEN CAST(CAST(designation AS FLOAT) AS INT)END )
ALTER TABLE employee
ALTER COLUMN designation INT
This takes the assumption that that the columns allow nulls. If not then that needs to be handled as well. For example: By altering the column to allow null, then after it has been converted to int then set all null values to 0 and alter the table to not allow null
Create a temp column
ALTER TABLE MYTABLE ADD MYNEWCOLUMN NUMBER(20,0) NULL;
Copy and casts the data from the old column to the new one
UPDATE MYTABLE SET MYNEWCOLUMN=CAST(MYOLDCOLUMN AS NUMBER(20,0));
Delete the old column
ALTER TABLE MYTABLE DROP COLUMN MYOLDCOLUMN;
Rename the new one to match the same name as the old one.
ALTER TABLE MYTABLE RENAME COLUMN MYNEWCOLUMN TO MYOLDCOLUMN;
Can you try this ?
alter table MyTable add MyColNum Varchar(500) null;
alter table MyTable add MyColNum int null;

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.

Set a existing column of MS SQL table as NOT NULL

How to Set a existing column of MS SQL table as NOT NULL?
ALTER TABLE tablename
ALTER COLUMN columnname datatype NOT NULL
You will obviously have to make sure that the column does not contain any NULL values before doing this.
E.g.
ALTER TABLE orders
ALTER COLUMN customer_id INT NOT NULL
Firstly ensure that the fields have non null values. In this case I'm working with a field that has a GUID nvarchar so I'll do
UPDATE tablename
SET fieldname = Newid()
WHERE fieldname IS NULL;
Then as Adam Ralph says
ALTER TABLE tablename ALTER COLUMN fieldname datatype NOT NULL

Resources