Alter a MySQL column to be AUTO_INCREMENT - sql

I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact. I have tried the following SQL, but got a syntax error notification.
ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
Am I doing something wrong or is this not possible?
+--------------------+
| VERSION() |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+

ALTER TABLE document MODIFY COLUMN document_id INT auto_increment

Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY

In my case it only worked when I put not null. I think this is a constraint.
ALTER TABLE document MODIFY COLUMN document_id INT NOT NULL AUTO_INCREMENT;

You can apply the atuto_increment constraint to the data column by the following query:
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:
SET foreign_key_checks = 0;
Therefore, use the following query instead:
SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;

The SQL to do this would be:
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE `document` MODIFY `document_id` INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.

You must specify the type of the column before the auto_increment directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT.

AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
ALTER COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)

You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;

You can use the following query to make document_id to increment automatically
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
It is preferred to make document_id primary key as well
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment PRIMARY KEY;

Below statement works. Note that you need to mention the data type again for the column name (redeclare the data type the column was before).
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT;

AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)

If none of the above works try this. This is what I did in MYSQL and yes, you need to write the column name (document_id) twice.
ALTER TABLE document
CHANGE COLUMN document_id document_id INT(11) NOT NULL AUTO_INCREMENT ;

Setting column as primary key and auto_increment at the same time:
mysql> ALTER TABLE persons MODIFY COLUMN personID INT auto_increment PRIMARY KEY;
Query OK, 10 rows affected (0.77 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql>

To modify the column in mysql we use alter and modify keywords. Suppose we have created a table like:
create table emp(
id varchar(20),
ename varchar(20),
salary float
);
Now we want to modify type of the column id to integer with auto increment. You could do this with a command like:
alter table emp modify column id int(10) auto_increment;

Previous Table syntax:
CREATE TABLE apim_log_request (TransactionId varchar(50) DEFAULT NULL);
For changing the TransactionId to auto increment use this query
ALTER TABLE apim_log_request MODIFY COLUMN TransactionId INT auto_increment;

alter table tbl_user MODIFY COLUMN id int(10) auto_increment;

Just like this:
alter table document modify column id int(11) auto_increment;

As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;

Try the following:
ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;

Since SQL tag is attached to the question I really think all answers missed one major point.
MODIFY command does not exist in SQL server So you will be getting an error when you run the
ALTER TABLE Satellites MODIFY COLUMN SatelliteID INT auto_increment PRIMARY KEY;
In this case you can either add new column as INT IDENTITY
ALTER TABLE Satellites
ADD ID INT IDENTITY
CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED;
OR
Fill the existing null index with incremental numbers using this method,
DECLARE #id INT
SET #id = 0
UPDATE Satellites SET #id = SatelliteID = #id + 1

Use the following queries:
ALTER TABLE YourTable DROP COLUMN IDCol
ALTER TABLE YourTable ADD IDCol INT IDENTITY(1,1)

Related

Why is the column not altering when I try to convert it to UUID?

I have a primary key column in my SQL table in PostgreSQL named "id". It is a "bigseries" column. I want to convert the column to a "UUID" column. It entered the below command in the terminal:
alter table people alter column id uuid;
and
alter table people alter column id uuid using (uuid_generate_v4());
but neither of them worked.
In both tries I got the error message
ERROR: syntax error at or near "uuid"
LINE 1: alter table people alter column id uuid using (uuid_generate...
What is the correct syntax?
First of all uuid_generate_v4() is a function which is provided by an extension called uuid-ossp. You should have install that extension by using;
CREATE EXTENSION uuid-ossp;
Postgresql 13 introduced a new function which does basically the same without installing extension. The function is called gen_random_uuid()
Suppose that we have a table like the one below;
CREATE TABLE people (
id bigserial primary key,
data text
);
The bigserial is not a real type. It's a macro which basically creates bigint column with default value and a sequence. The default value is next value of that sequence.
For your use case, to change data type, you first should drop the old default value. Then, alter the type and finally add new default value expression. Here is the sample:
ALTER TABLE people
ALTER id DROP DEFAULT,
ALTER id TYPE uuid using (gen_random_uuid() /* or uuid_generate_v4() */ ),
ALTER id SET DEFAULT gen_random_uuid() /* or uuid_generate_v4() */ ;
CREATE TABLE IF NOT EXISTS people (
id uuid NOT NULL CONSTRAINT people_pkey PRIMARY KEY,
address varchar,
city varchar(255),
country varchar(255),
email varchar(255),
phone varchar(255)
);
This is the correct syntax to create table in postgres SQL, it's better to do these constraints at beginning to avoid any error.
For using alter command you would do the following:
ALTER TABLE customer ADD COLUMN cid uuid PRIMARY KEY;
Most of errors that you could find while writing command either lower case or undefined correct the table name or column.

How to modify column to auto increment in PL SQL Developer?

I have created one table in PL SQL Developer.
CREATE TABLE Patient_List
(
Patient_ID number NOT NULL,
Patient_Name varchar(50) NOT NULL,
Patient_Address varchar(100) NULL,
App_Date date NULL,
Descr varchar(50),
CONSTRAINT patient_pk PRIMARY KEY(Patient_ID)
);
I want to auto increment Patient_ID, I tried altering the table and modifying the Patient_ID column but it's showing an error "invalid ALTER TABLE option"
ALTER TABLE Patient_List
MODIFY Patient_ID NUMBER NOT NULL GENERATED ALWAYS AS IDENTITY;
Please help, Thanks in advance.
This is not possible.
Oracle 10g didn't even have identity columns, they were introduced in Oracle 12.1
But even with a current Oracle version, you can't convert a regular column to an identity column. You would need to add a new one.
Before identity columns, the usual way was to create a sequence and a trigger to populate the column.
See here: How to create id with AUTO_INCREMENT on Oracle?
If anybody wants to modify existing column as auto_increment use this three lines
alter table Product drop column test_id;
create sequence Product_test_id_seq INCREMENT BY 1 nocache;
alter table Product add test_id Number default Product_test_id_seq.nextval not null;

Adding a NOT NULL column to a Redshift table

I'd like to add a NOT NULL column to a Redshift table that has records, an IDENTITY field, and that other tables have foreign keys to.
In PostgreSQL, you can add the column as NULL, fill it in, then ALTER it to be NOT NULL.
In Redshift, the best I've found so far is:
ALTER TABLE my_table ADD COLUMN new_column INTEGER;
-- Fill that column
CREATE TABLE my_table2 (
id INTEGER IDENTITY NOT NULL SORTKEY,
(... all the fields ... )
new_column INTEGER NOT NULL,
PRIMARY KEY(id)
) DISTSTYLE all;
UNLOAD ('select * from my_table')
to 's3://blah' credentials '<aws-auth-args>' ;
COPY my_table2
from 's3://blah' credentials '<aws-auth-args>'
EXPLICIT_IDS;
DROP table my_table;
ALTER TABLE my_table2 RENAME TO my_table;
-- For each table that had a foreign key to my_table:
ALTER TABLE another_table ADD FOREIGN KEY(my_table_id) REFERENCES my_table(id)
Is this the best way of achieving this?
You can achieve this w/o having to load to S3.
modify the existing table to create the desired column w/ a default value
update that column in some way (in my case it was copying from another column)
create a new table with the column w/o a default value
insert into the new table (you must list out the columns rather than using (*) since the order may be the same (say if you want the new column in position 2)
drop the old table
rename the table
alter table to give correct owner (if appropriate)
ex:
-- first add the column w/ a default value
alter table my_table_xyz
add visit_id bigint NOT NULL default 0; -- not null but default value
-- now populate the new column with whatever is appropriate (the key in my case)
update my_table_xyz
set visit_id = key;
-- now create the new table with the proper constraints
create table my_table_xzy_new
(
key bigint not null,
visit_id bigint NOT NULL, -- here it is not null and no default value
adt_id bigint not null
);
-- select all from old into new
insert into my_table_xyz_new
select key, visit_id, adt_id
from my_table_xyz;
-- remove the orig table
DROP table my_table_xzy_events;
-- rename the newly created table to the desired table
alter table my_table_xyz_new rename to my_table_xyz;
-- adjust any views, foreign keys or permissions as required

DB2 add auto increment column to an existing table

I have a table with following schema in my DB2 database.
CREATE TABLE IDN_OAUTH_CONSUMER_APPS (
CONSUMER_KEY VARCHAR (255) NOT NULL,
CONSUMER_SECRET VARCHAR (512),
USERNAME VARCHAR (255),
TENANT_ID INTEGER DEFAULT 0,
APP_NAME VARCHAR (255),
OAUTH_VERSION VARCHAR (128),
CALLBACK_URL VARCHAR (1024),
GRANT_TYPES VARCHAR (1024)
/
I need to add a new column ID of Type integer not null auto increment, and make it the primary key. How can I do that without deleting the table?
I could do this successfully using following set of queries.
ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ID INTEGER NOT NULL DEFAULT 0
CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE
CREATE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIGGER NO CASCADE BEFORE INSERT ON IDN_OAUTH_CONSUMER_APPS REFERENCING NEW AS NEW FOR EACH ROW MODE DB2SQL BEGIN ATOMIC SET (NEW.ID) = (NEXTVAL FOR IDN_OAUTH_CONSUMER_APPS_SEQUENCE); END
REORG TABLE IDN_OAUTH_CONSUMER_APPS
UPDATE IDN_OAUTH_CONSUMER_APPS SET ID = IDN_OAUTH_CONSUMER_APPS_SEQUENCE.NEXTVAL
And then add primary key using alter table.
Use a multi-step approach:
add the column ALTER TABLE ADD... with just the integer data type and as nullable
update the table to set the intended identity values for that column
alter the table to add the auto-generation
alter the table to add the primary key on that column
You need to have multiple steps because the identity values need to be added manually. Syntax and examples for ALTER TABLE can be found here.
There is an easy way to do it. Just run the alters above:
ALTER TABLE idn_oauth_consumer_apps ADD COLUMN id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE idn_oauth_consumer_apps ALTER COLUMN id SET GENERATED ALWAYS AS IDENTITY;
It is simple and fast even on big tables. Tested and working on DB2 for i V7R2.
I recommend using this approach. It does not require creating any satellite objects - no triggers, sequences, etc...
alter table test.test2 add column id integer not null default 0;
alter table test.test2 alter column id drop default;
alter table test.test2 alter column id set generated always as identity;
call sysproc.admin_cmd ('reorg table test.test2');
update test.test2 set id = default;
commit;
If using "db2" cli then the reorg command may be run directly without the "call sysproc.admin_cmd" wrapper.
Create a new table with the primary key field. Insert the records from the old table. Drop the old table and if you can, rename the new one. If you can't rename it, recreate it and populate from the one that now has the records.
Building on Chamila Wijayarathna's answer, I used the following:
ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ID INTEGER NOT NULL DEFAULT 0
CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE
CREATE TRIGGER IDN_OAUTH_CONSUMER_APPS_ID_TRIGGER NO CASCADE BEFORE INSERT ON
IDN_OAUTH_CONSUMER_APPS REFERENCING NEW AS NEW
FOR EACH ROW MODE DB2SQL BEGIN ATOMIC SET (NEW.ID) = (NEXTVAL FOR
IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE); END
REORG TABLE IDN_OAUTH_CONSUMER_APPS
UPDATE IDN_OAUTH_CONSUMER_APPS SET ID = IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE.NEXTVAL
ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD PRIMARY KEY (ID)
REORG TABLE IDN_OAUTH_CONSUMER_APPS
Then to reverse:
REORG TABLE IDN_OAUTH_CONSUMER_APPS
ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP PRIMARY KEY
DROP TRIGGER IDN_OAUTH_CONSUMER_APPS_ID_TRIGGER
DROP SEQUENCE IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE
ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP COLUMN ID
REORG TABLE IDN_OAUTH_CONSUMER_APPS
Tried this on DB2 for z/OS v12 and it worked:
alter table TABLE_NAME add column id integer generated always as identity

SQL Alter table default error

I am trying to modify an Integer field on existing table from nullable to non-nullable and adding default value to it.
ALTER TABLE dbo.current_status
ALTER COLUMN next_sign_id INT NOT NULL
This statement works, but this one doesn't:
ALTER TABLE dbo.current_performance_status
ALTER COLUMN next_sign_tp_id INT NOT NULL DEFAULT(0)
What is the problem here and how do I achieve both in one statement? I am using sql 2008.
You have to do this in three statements (thanks #MartinSmith for the sanity check, who suggested WITH VALUES which isn't correct in this case but still reminded me that this table may not be empty):
ALTER TABLE dbo.current_performance_status
ADD CONSTRAINT df DEFAULT (0) FOR next_sign_id;
UPDATE dbo.current_performance_status
SET next_sign_id = 0
WHERE next_sign_id IS NULL
ALTER TABLE dbo.current_performance_status
ALTER COLUMN next_sign_id INT NOT NULL;