How to alter column of a table with indexes? - sql

I would like to change the column size of the a column in a table with some indexes from varchar(200) to varchar(8000). How should I proceed?

Since is VARCHAR and you're increasing the size, then simply ALTER TABLE ... ALTER COLUMN ... should be enough.
The data type of columns included in an index cannot be changed unless the column is a varchar, nvarchar, or varbinary data type, and the new size is equal to or larger than the old size.
Otherwise you would drop the index(es), alter the column, then add back the index(es).
Be aware though that SQL Server maximum index key size is 900 (or 1700 for newer editions), so even though the ALTER will succeed, a future INSERT of
data over the 900 length limit will fail with error:
Msg 1946, Level 16, State 3, Line 13
Operation failed. The index entry of length ... bytes for the index '...' exceeds the maximum length of 900 bytes.

Try this for MSSQL:
drop index person.idx_pers_fullname
ALTER table person alter COLUMN pers_firstname nvarchar(8000)
create index idx_pers_fullname on person(pers_firstname)

Example in Oracle:
CREATE TABLE EMP (NAME VARCHAR(200));
ALTER TABLE EMP MODIFY NAME VARCHAR(800);

Related

Error in changing column length in Postgres

I am trying to change the column size from 100 to 150 varchar data type using following query:
alter table data_warehouse.tbl_abc
alter column first_nm varchar(150) null;
Getting the following error:
SQL Error [42601]: ERROR: syntax error at or near "varchar"
Position: 77
The syntax is a bit different, so try this:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm type varchar(120);
The error in your syntax is that you missed a TYPE keyword:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150);
and if you have a NOT NULL constraint you want to remove, add a new ALTER COLUMN inside the same ALTER TABLE statement:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150),
ALTER COLUMN first_nm DROP NOT NULL;
for reference look here: https://www.postgresql.org/docs/current/sql-altertable.html
Edit: as in the comment, if you have a view which involves the same column, drop it and re-create it under transaction:
BEGIN TRANSACTION;
DROP VIEW [...];
ALTER TABLE [...];
CREATE VIEW [...];
COMMIT;
Be aware that to alter a table, you must acquire an exclusive lock on it, so during the whole process, all the queries over the same table and on the views of the table are locked, also if they don't read from the altered column (because the whole table is locked) - use with caution in production environment

Use user-defined function in CREATE TABLE statement

I'm trying to create the following table
CREATE TABLE Ingredient.Ingredient
(
GUID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL,
Name NVARCHAR(MAX) NOT NULL UNIQUE
)
but I've come to realize that the max size of a NVARCHAR UNIQUE column is 450 (at least in the current version of SQL Server). In order to not use magic literals I've created a user-defined function that returns the current max size of a NVARCHAR UNIQUE column.
CREATE FUNCTION [Max NVARCHAR Index Size]()
RETURNS INTEGER
BEGIN
RETURN(450)
END
This function runs correctly when called as
SELECT dbo.[Max NVARCHAR Index Size]()
I was hoping to use this function in a CREATE TABLE statement, but it errors as shown below.
CREATE TABLE Ingredient.Ingredient
(
GUID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL,
Name NVARCHAR(dbo.[Max NVARCHAR Index Size]()) NOT NULL UNIQUE
)
Error:
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '('
To try and circumvent this I made a variable with the value of the function, and then using the variable, but that didn't work either.
DECLARE
#NVARCHARIndexSize INTEGER = dbo.[MAX NVARCHAR Index Size]()
CREATE TABLE Ingredient.Ingredient
(
GUID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL,
Name NVARCHAR(#NVARCHARIndexSize) NOT NULL UNIQUE
)
Error:
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '#NVARCHARIndexSize'
where line 13 is Name NVARCHAR(#NVARCHARIndexSize) NOT NULL UNIQUE.
Is there a way to use variables/functions instead of literals in a CREATE TABLE statement?
Thanks in advance.
You can create a custom type in SQL Server with following syntax
CREATE TYPE MyCustomType
FROM NVARCHAR(420);
And later on can use the custom type while creating tables
CREATE TABLE Ingredient
(
GUID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL,
[Name] MyCustomType NOT NULL UNIQUE
)
DDL can't be parameterized. You'd have to use dynamic SQL for that. eg
DECLARE
#NVARCHARIndexSize INTEGER = dbo.[MAX NVARCHAR Index Size]()
declare #sql nvarchar(max) = concat('
CREATE TABLE Ingredient.Ingredient
(
GUID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL,
Name NVARCHAR(',#NVARCHARIndexSize,') NOT NULL UNIQUE
)'
)
exec (#sql)
Prior to SQL Server 2016, the maximum key length was 900 bytes. MSDN Reference
Index Key Size
The maximum size for an index key is 900 bytes for a clustered index and 1,700 bytes for a nonclustered index. (Before
SQL Database and SQL Server 2016 (13.x) the limit was always 900
bytes.) Indexes on varchar columns that exceed the byte limit can be
created if the existing data in the columns do not exceed the limit at
the time the index is created; however, subsequent insert or update
actions on the columns that cause the total size to be greater than
the limit will fail. The index key of a clustered index cannot contain
varchar columns that have existing data in the ROW_OVERFLOW_DATA
allocation unit. If a clustered index is created on a varchar column
and the existing data is in the IN_ROW_DATA allocation unit,
subsequent insert or update actions on the column that would push the
data off-row will fail.
Nonclustered indexes can include non-key columns in the leaf level of
the index. These columns are not considered by the Database Engine
when calculating the index key size
You can define a NVARCHAR(450) column with check constraint, to ensure that your data does not go beyond 450 characters. I would suggest you to use DATALENGTH to ensure that column length is <= 900.
CREATE TABLE #test(id int identity(1,1) not null,
a NVARCHAR(500) CHECK (DATALENGTH(a) <= 900),
CONSTRAINT ak_a unique(a))
insert into #test
values('a') -- 1 row affected
insert into #test
values(REPLICATE('a',450)) -- 1 row affected
insert into #test
values(REPLICATE('a',451)) -- Error
Msg 547, Level 16, State 0, Line 12 The INSERT statement conflicted
with the CHECK constraint "CK__#test__________a__AC6651A7". The
conflict occurred in database "tempdb", table "#test", column 'a'.
In future, when you move to higher versions, you can increase length of NVARCHAR and CHECK constraint accordingly.

Can't ALTER COLUMN TYPE in PostgreSQL "0A000: Cannot alter column "FIELDA" of relation "TABLEA"

Trying to run the below script:
ALTER TABLE SCHEMA.TABLEA
ALTER COLUMN FIELDA TYPE VARCHAR(5)
And I am getting the following error:
0A000: Cannot alter column "FIELDA" of relation "TABLE"
The field is currently an integer and contains no data, only nulls.
As per the AWS documentation you cannot change the data type of a VARCHAR only the size.
https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html

Oracle SQL to change column type from number to varchar2 while it contains data

I have a table (that contains data) in Oracle 11g and I need to use Oracle SQLPlus to do the following:
Target: change the type of column TEST1 in table UDA1 from number to varchar2.
Proposed method:
backup table
set column to null
change data type
restore values
The following didn't work.
create table temp_uda1 AS (select * from UDA1);
update UDA1 set TEST1 = null;
commit;
alter table UDA1 modify TEST1 varchar2(3);
insert into UDA1(TEST1)
select cast(TEST1 as varchar2(3)) from temp_uda1;
commit;
There is something to do with indexes (to preserve the order), right?
create table temp_uda1 (test1 integer);
insert into temp_uda1 values (1);
alter table temp_uda1 add (test1_new varchar2(3));
update temp_uda1
set test1_new = to_char(test1);
alter table temp_uda1 drop column test1 cascade constraints;
alter table temp_uda1 rename column test1_new to test1;
If there was an index on the column you need to re-create it.
Note that the update will fail if you have numbers in the old column that are greater than 999. If you do, you need to adjust the maximum value for the varchar column
Add new column as varchar2, copy data to this column, delete old column, rename new column as actual column name:
ALTER TABLE UDA1
ADD (TEST1_temp VARCHAR2(16));
update UDA1 set TEST1_temp = TEST1;
ALTER TABLE UDA1 DROP COLUMN TEST1;
ALTER TABLE UDA1
RENAME COLUMN TEST1_temp TO TEST1;
Look at Oracle's package DBMS_REDEFINE. With some luck you can do it online without downtime - if needed. Otherwise you can:
Add new VARCHAR2 column
Use update to copy NUMBER into VARCHAR2
Drop NUMBER column
Rename VARCHAR2 column
Here you go, this solution did not impact the existing NOT NULL or Primary key constraints. Here i am going to change the type of Primary key from Number to VARCHAR2(3), Here are the Steps on example table employee.
Take backup of table and Index, Constraints
created table employee_bkp
create table employee_bkp as select * from employee
commit;
Truncate the table to empty it
truncate table employee
Alter the table to change the type
ALTER TABLE employee MODIFY employee_id varchar2(30);
Copy the data back from backup table
insert into employee (select * from employee_bkp)
commit;
Verify

is of a type that is invalid for use as a key column in an index

I have an error at
Column 'key' in table 'misc_info' is of a type that is invalid for use as a key column in an index.
where key is a nvarchar(max). A quick google search finds that the maximum length of an index is 450 chars. However, this doesn't explain what a solution is. How do I create something like Dictionary where the key and value are both strings and obviously the key must be unique and is single? My sql statement was
create table [misc_info] (
[id] INTEGER PRIMARY KEY IDENTITY NOT NULL,
[key] nvarchar(max) UNIQUE NOT NULL,
[value] nvarchar(max) NOT NULL);
A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:
create table [misc_info]
(
[id] INTEGER PRIMARY KEY IDENTITY NOT NULL,
[key] nvarchar(450) UNIQUE NOT NULL,
[value] nvarchar(max) NOT NULL
)
i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.
There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table.
The condition is:
([dbo].[CheckKey]([key])=(1))
and [dbo].[CheckKey] is a scalar function defined as:
CREATE FUNCTION [dbo].[CheckKey]
(
#key nvarchar(max)
)
RETURNS bit
AS
BEGIN
declare #res bit
if exists(select * from key_value where [key] = #key)
set #res = 0
else
set #res = 1
return #res
END
But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.
The only solution is to use less data in your Unique Index. Your key can be NVARCHAR(450) at most.
"SQL Server retains the 900-byte limit for the maximum total size of all index key columns."
Read more at MSDN
A solution would be to declare your key as nvarchar(20).
Noting klaisbyskov's comment about your key length needing to be gigabytes in size, and assuming that you do in fact need this, then I think your only options are:
use a hash of the key value
Create a column on nchar(40) (for a sha1 hash, for example),
put a unique key on the hash column.
generate the hash when saving or updating the record
triggers to query the table for an existing match on insert or update.
Hashing comes with the caveat that one day, you might get a collision.
Triggers will scan the entire table.
Over to you...