change the size of datatype in sql - sql

I have created a table with column id as varchar2(20). Now I want to modify it and change size to 13 i.e column id varchar2(13). How to achieve it? Thanks in advance
p.s.: I don`t have any data in my table.

You may try this for Oracle:-
alter table tablename modify
(
column_name varchar2(13)
);
Also If you dont have any data in the table then you can also drop the table and then create the table with the columname as varchar2(13)

Just run this query for MySQL:
ALTER TABLE tablename CHANGE column `id` varchar2(13);
See here for more details. If you have additional constraints on this column, specify those as well.

Related

SQL Table New Column

I have an existing table in SQL that includes an ID column. I need to have another Textcolumn in same table in a way it is always equal to ID value but stored as text. For now I am updating Textcolumn daily but I want it to be auto filled.
Is that possible?
I actually just recommend that you select your ID column as text if you have that requirement:
SELECT ID, CAST(ID AS varchar(55)) ID_text
FROM yourTable;
If you need to work this ID column as text, then cast as do whatever you need, e.g. a string concatenation.
There are many ways to do the job.
From now on during insert it into the column by casting it as varchar.
You can use trigger for updating the column. For more information creating trigger are in the following link
you can use computed column for solve your problem automatically
CREATE TABLE [dbo].[test](
[Id] [int] NULL,
[Idtext] AS (cast ([id] as nvarchar(10)))
) ON [PRIMARY]
this is my sample table
in my sample table the IdText Column fill automatics when you insert a record in your table
if you wants to add column on the existing table you can use this command
ALTER TABLE [Table Name] ADD [Column Name] AS (cast([id] as nvarchar(10)))
You can use a Trigger to update it automatically.

Convert bit column to integer

I am converting bit columns of a particular table to integer through an SQL script (this table has some default constraints for default value).
I have to alter the columns for the table, not runtime casting, What script can be used to accomplish this?
Try using CAST(columnName AS INT) AS IntValue.
e.g.
SELECT columnName, CAST(columnName AS INT) AS IntValue
FROM table
OR you can use CONVERT(INT, columnName) AS IntValue.
UPDATE: If you need to alter the actual metadata of the table, then you first need to drop the constraints then alter the column:
i.e.
ALTER TABLE [Table] DROP CONSTRAINT [ConstraintName];
GO
ALTER TABLE [Table] ALTER COLUMN [ColumnName] INT;
Then recreate any constraints that you need.
If you are concerned about changing the datatype of the column you can use an ALTER query as follows.
ALTER TableName ALTER COLUMN ColumnName INT
Else, only for display purposes, you can use either the CAST or CONVERT function:
CAST(columnName AS INT) AS IntegerVal
CONVERT(int, columnName) AS IntValue
None of the provided solutions worked for me. I had to used Signed or Unsigned instead of INT e.g.
SELECT columnName, CAST(columnName AS SIGNED) AS IntValue
FROM table
Hope this helps for new users.
SELECT CONVERT(BIT,'False') AS test1
SELECT CONVERT(BIT,'True') AS test2
We can't simply alter the BIT column to INT. So I suggest to create the new integer column in the table and then using the CAST, update the new integer column with the existing bit values. Then at last you can drop the BIT column from the table.
Finally I managed to get it working:
ALTER TABLE tblname DROP CONSTRAINT DF_tbl_tblname_tblcol
ALTER TABLE tblname ALTER COLUMN tblcol int not null
ALTER TABLE tblname WITH NOCHECK ADD CONSTRAINT [DF_tbl_tblname_tblcol] DEFAULT (0) FOR tblcol
I have used the above SQL statements to alter the table column along with its constructor.
I believe you could extract the bit column as an integer by just using standard CAST() command:
SELECT
CAS(Bit_Column AS int) AS Int_Column
FROM
YourTable
However, I'm not sure I understand what you're trying to achieve, probably you could get a better answer if you provided more details, such as the structure of the table and its constraints.
You are getting an error related to a default constraint. Thus you have to drop that constraint before altering the column data type...
Try this to find all the constraints based on this table (you just need to find the proper default on your column) or use SQL Server Management Studio (SSMS) to generate the script for the table, and this will have the default constraint defintion.
select * from sys.all_objects where parent_object_id = object_id('<tablename>')
go
Then first drop the constraint and then alter the column and add the default again.
alter table bittoint drop constraint DF__bittoint__col2__45D500F0
go
alter table bittoint alter column col2 int
go
alter table bittoint add constraint DF__bittoint__col2__45D500F0 default 0 for col2
go

What is the SQL to change the field length of a table column in SQL Server

What is the SQL to make a field go from nvarchar(50) to nvarchar(250)?
When I try to change it through the SQL Server Management Studio, it doesn't allow me to do it, so I figured I would try SQL directly instead of using the GUI.
Alter table tblname ALTER Column colname nvarchar(250) [NOT] NULL
If NULL / NOT NULL is not specified the column will become Nullable irrespective of what ever the original specification was.
ALTER TABLE MyTable
ALTER COLUMN MyColumn varchar(NewSize)
The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
My SQL / Oracle (prior version 10G):
ALTER TABLE table_name
MODIFY COLUMN column_name datatype
Oracle 10G and later:
ALTER TABLE table_name
MODIFY column_name datatype
Its sometimes safer to check if the table exist in the first place...
IF COL_LENGTH('[tablename]','[tablecolumn]') IS NULL
BEGIN
ALTER TABLE tablename
ALTER COLUMN [tablecolumn]
NVARCHAR(500)
END
To change the datatype of many column but same datatype
alter table employee modify (firstname varchar2(9),lastname varchar2(9),email varchar2(9));
-- Table altered.
alter table employee modify (firstname,lastname,email varchar2(9));
-- Table altered.
For Oracle SQL Developers
Alter table tblname MODIFY (colname varchar2(250));
Description : It will increase the length of column. where 250
represent the updated (incremented) length of column.

Can I add a not null column without DEFAULT value

Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:
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 'test' cannot be added to non-empty table 'shiplist' because it does not satisfy these conditions.
If YES, please let me know the syntax, if No please specify the reason.
No, you can't.
Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.
The simplest way to do this is create the column with a default and then remove the default.
ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn
Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.
Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.
No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have
It's easy to create a DEFAULT at the same time, and then immediately drop it.
I use this approach to insert NOT NULL column without default value
ALTER TABLE [Table] ADD [Column] INT NULL
GO
UPDATE [Table] SET [Column] = <default_value>
ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
No.
Just use empty string '' (in case of character type) or 0 (if numeric), etc as DEFAULT value
No you cannot. But you can consider to specify the default value to ('')
No, you can't, as SQL Server, or any other database engines will force this new column to be null for existing rows into your data table. But since you do not allow a NULL, you are required to provide a default value in order to respect your own constraint. This falls under great sense! The DBE will not extrapolate a value for non-null values for the existing rows.
#Damien_The_Unbeliever's comment ,
Is it adding computed column? Neither question nor answer implied anything like that. In case of computed column the error states:
"Only UNIQUE or PRIMARY KEY constraints can be created on computed columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require that computed columns be persisted"
OK, if to continue this guessing game, here is my script illustrating the adding of "NOT NULL" column in one "ALTER TABLE" step:
CREATE TABLE TestInsertComputedColumn
(
FirstName VARCHAR(100),
LastName CHAR(50)
);
insert into TestInsertComputedColumn(FirstName,LastName)
select 'v', 'gv8';
select * from TestInsertComputedColumn;
ALTER TABLE TestInsertComputedColumn
ADD FullName As FirstName + LastName PERSISTED NOT NULL;
select * from TestInsertComputedColumn;
--drop TABLE TestInsertComputedColumn;
I used below approach it worked for me
Syntax:
ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Example:
ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO

Altering a column to be nullable

I want to alter a table column to be nullable. I have used:
ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations NULL
This gives an error at Modify. What is the correct syntax?
Assuming SQL Server (based on your previous questions):
ALTER TABLE Merchant_Pending_Functions ALTER COLUMN NumberOfLocations INT NULL
Replace INT with your actual datatype.
If this was MySQL syntax, the type would have been missing, as some other responses point out.
Correct MySQL syntax would have been:
ALTER TABLE Merchant_Pending_Functions MODIFY NumberOfLocations INT NULL
Posting here for clarity to MySQL users.
In PostgresQL it is:
ALTER TABLE tableName ALTER COLUMN columnName DROP NOT NULL;
for Oracle Database 10g users:
alter table mytable modify(mycolumn null);
You get "ORA-01735: invalid ALTER TABLE option" when you try otherwise
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
Although I don't know what RDBMS you are using, you probably need to give the whole column specification, not just say that you now want it to be nullable. For example, if it's currently INT NOT NULL, you should issue ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations INT.
As others have observed, the precise syntax for the command varies across different flavours of DBMS. The syntax you use works in Oracle:
SQL> desc MACAddresses
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPUTER NUMBER
MACADDRESS VARCHAR2(12)
CORRECTED_MACADDRESS NOT NULL VARCHAR2(17)
SQL> alter table MACAddresses
2 modify corrected_MACAddress null
3 /
Table altered.
SQL> desc MACAddresses
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPUTER NUMBER
MACADDRESS VARCHAR2(12)
CORRECTED_MACADDRESS VARCHAR2(17)
SQL>
For SQL Server or TSQL
ALTER TABLE Complaint.HelplineReturn ALTER COLUMN IsDisposed BIT NULL
This depends on what SQL Engine you are using, in Sybase your command works fine:
ALTER TABLE Merchant_Pending_Functions
Modify NumberOfLocations NULL;
For HSQLDB:
ALTER TABLE tableName ALTER COLUMN columnName SET NULL;
ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT null;
This will work for you.
If you want to change a not null column to allow null, no need to include not null clause. Because default columns get not null.
ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT;
Oracle
ALTER TABLE Merchant_Pending_Functions MODIFY([column] NOT NULL);
SQLite
The ALTER TABLE command is a bit special. There is no possibility to modify a column. You have to create a new column, migrate the data, and then drop the column:
-- 1. First rename
ALTER TABLE
Merchant_Pending_Functions
RENAME COLUMN
NumberOfLocations
TO
NumberOfLocations_old
-- 2. Create new column
ALTER TABLE
Merchant_Pending_Functions
ADD COLUMN
NumberOfLocations INT NULL
-- 3. Migrate data - you need to write code for that
-- 4. Drop the old column
ALTER TABLE
Merchant_Pending_Functions
DROP COLUMN
NumberOfLocations_old
Make sure you add the data_type of the column to modify.
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME DATA_TYPE NULL;