Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a auto increment primary key to existing table in oracle [duplicate]

Tags:

oracle

I want to add a new auto increment primary column to a existing table which has data. How do I do that?

I first added a column and then try to add a sequence after that, I lost how to insert and make that column as primary key.

like image 560
mallikarjun Avatar asked Jul 13 '12 05:07

mallikarjun


People also ask

How do I add an auto increment to an existing table?

To add a new AUTO_INCREMENT integer column named c : ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c); We indexed c (as a PRIMARY KEY ) because AUTO_INCREMENT columns must be indexed, and we declare c as NOT NULL because primary key columns cannot be NULL .

How do I create an existing column auto increment in Oracle?

You can double click the name of the column or click on the 'Properties' button. Column Properties dialog box appears. Select the General Tab (Default Selection for the first time). Then select both the 'Auto Increment' and 'Identity Column' check boxes.

Can you create an auto increment on a unique key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do I change my primary key to auto increment?

To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table. Look at the above sample output, StudentId column has been changed to auto_increment.


1 Answers

Say your table is called t1 and your primary-key is called id
First, create the sequence:

create sequence t1_seq start with 1 increment by 1 nomaxvalue;  

Then create a trigger that increments upon insert:

create trigger t1_trigger before insert on t1 for each row    begin      select t1_seq.nextval into :new.id from dual;    end; 
like image 172
Nir Alfasi Avatar answered Nov 16 '22 05:11

Nir Alfasi