How to change a PG column to NULLABLE TRUE? - sql

How can I accomplish this using Postgres? I've tried the code below but it doesn't work:
ALTER TABLE mytable ALTER COLUMN mycolumn BIGINT NULL;

From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.

Related

DB2: How do I remove AUTO_INCREMENT?

How do I remove AUTO_INCREMENT of a column in DB2?
I tried
ALTER TABLE my_table ALTER my_id
but no luck. What is the correct SQL statement?
You can modify a column definition of a DB2 table and remove the generation of values:
ALTER TABLE mytable ALTER COLUMN mycol DROP GENERATED;
You can remove the Auto_increment by using the following
ALTER TABLE table_name ALTER COLUMN column_name DROP IDENTITY;

Add a column to a table with a default value equal to the value of an existing column

How to add a column to a SQL Server table with a default value that is equal to value of an existing column?
I tried this T-SQL statement:
ALTER TABLE tablename
ADD newcolumn type NOT NULL DEFAULT (oldcolumn)
but it's giving an error:
The name "oldcolumn" is not permitted in this context. Valid
expressions are constants, constant expressions, and (in some
contexts) variables. Column names are not permitted.
Try this:
ALTER TABLE tablename ADD newcolumn type NOT NULL DEFAULT (0)
Go
Update tablename SET newcolumn = oldcolumn Where newcolumn = 0
Go
The AFTER INSERT trigger approach involves overhead due to the extra UPDATE statement. I suggest using an INSTEAD OF INSERT trigger, as follows:
CREATE TRIGGER tablename_on_insert ON tablename
INSTEAD OF INSERT
AS
INSERT INTO tablename (oldcolumn, newcolumn)
SELECT oldcolumn, ISNULL(newcolumn, oldcolumn)
FROM inserted
This does not work though if the oldcolumn is an auto-identity column.
I don't like them very much but here is how you could do this with an AFTER INSERT trigger:
CREATE TRIGGER TableX_AfterInsert_TRG
ON TableX
AFTER INSERT
AS
UPDATE TableX AS t
SET t.newcolumn = t.oldcolumn
FROM Inserted AS i
WHERE t.PK = i.PK ; -- where PK is the PRIMARY KEY of the table
You can use computed column to insert new column in a table based on an existing column value
ALTER TABLE dbo.TableName ADD NewColumn AS (OldColumn) PERSISTED;
OR, if you want to make some changes to the value based on existing column value, use
ALTER TABLE dbo.TableName ADD NewColumn AS (OldColumn * 1.5) PERSISTED;
To extend Kapil's answer, and avoid the unwanted default constraint, try this:
ALTER TABLE tablename ADD newcolumn type NOT NULL CONSTRAINT DF_TMP_TABLENAME_NEWCOLUMN DEFAULT -9999
Go
Update tablename SET newcolumn = oldcolumn
Go
ALTER TABLE tablename DROP CONSTRAINT DF_TMP_TABLENAME_NEWCOLUMN
Go
Replace -9999 by 'noData' if your type is varchar, nvarchar, datetime,... or by any compatible data for other types: specific value doesn't matter, it will be wiped by the 2nd instruction.
For my case, I want to add a new not null unique column named CODE but I don't know about the value at the creation time. I set the default value for it by get a default value from NewID() then update later.
ALTER TABLE [WIDGET] ADD [CODE] CHAR(5) NOT NULL DEFAULT(SUBSTRING(CONVERT(CHAR(36), NEWID()), 1, 5))
ALTER TABLE [dbo].[WIDGET] WITH CHECK ADD CONSTRAINT [UQ_WIDGET_CODE] UNIQUE ([CODE])
Use a computed column, which will even work with IDENTITY column values:
CREATE TABLE #This
( Id INT IDENTITY(1,1)
,MyName VARCHAR(10)
,FullName AS (Myname + CONVERT(VARCHAR(10),Id)) PERSISTED);
INSERT #This VALUES ('Item'),('Item');
SELECT * FROM #This;
DROP TABLE #This;
yields the following:
I think it will work if you use Set Identity_Insert <TableName> OFF and after the insert Statement that you wrote just use Set Identity_Insert <TableName> ON.

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.

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;