Professional Documents
Culture Documents
Home
|
Feed
|
Log in
|
Contact
After pointing out how not to create auto increment columns in Oracle, I suppose I should point out how to create
auto increment columns in oracle.
Many will gripe about this not being a standard feature in Oracle, but when its as easy as two more commands
after your CREATE TABLE command I cant see any good reason to use fancy SQL on every insert.
Table created.
Now well assume we want ID to be an auto increment field. First we need a sequence to grab values from.
SQL> CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
Sequence created.
Now we can use that sequence in an BEFORE INSERT trigger on the table.
CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON test
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;
/
Trigger created.
1 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
This trigger will automatically grab the next value from the sequence we just created and substitute it
into the ID column before the insert is completed.
Trying Microsoft Sql
Now well do some inserts: 12 Ways to Reduce
Cost with SQL Server.
Download Free Trial !
SQL> INSERT INTO test (name) VALUES ('Jon'); Microsoft.com/SQLServe
1 row created.
Forms Migration
SQL> INSERT INTO test (name) VALUES ('Bork'); Migrate legacy forms
and reports to 10g or
1 row created. to JAVA/ADF
formsmigration.imexsyste
1 row created.
ID NAME
---------- ------------------------------
1 Jon
2 Bork
3 Matt
Because the sequence is updated independent of the rows being committed there will be no conflict if multiple users are
inserting into the same table simultaneously.
If you need to capture the value of the auto increment column youll want to check out my other article Oracle Auto
increment Columns Part 2
Matt has posted a similar method in which he uses a sequence in the insert eliminating the need for the trigger. That will
work just as well without the need for the trigger. The only drawback to this method is slightly longer SQL commands.
[...] This article is about how not to create auto increment columns. If youre looking for a more acceptable way, youll
want to check out this article. [...]
There is an issue caused by using directly the increment of a sequence in an insert statement
is okay, but will not make inserts work in the table in some case.
For example, I had to use and MS Access interface to insert rows in an oracle db. Using the statement above will not
work.
Youll have to use the trigger one behaivor, demanding the sequence increment directy to the oracle server.
2 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
DECLARE
seqNo NUMBER;
Please let me know if they are really needed (ie, is this going to bite me later?)
Thanks again,
Tony Jackson
atjsfo@hotmail.com
4. Jon Says:
March 21st, 2006 at 9:18 pm
The DECLARE portion must be left from some previous revision of some other trigger. Its not necessary and I will be
removing it form the code above. Thanks for pointing this out.
The REFERENCING NEW AS NEW OLD AS OLD gives you the :NEW and :OLD objects so you can refer to
columns as :NEW.id or :NEW.name. If its an insert there is really just a :NEW, but for an update you would have the
new values in :NEW and the old values in :OLD.
Hope that all makes sense. Let me know if youre looking for more.
5. Jon Says:
March 21st, 2006 at 10:00 pm
Update: Thanks to Tony for pointing out a couple things that could be tightened up.
I left out the OLD AS OLD since there is no OLD data on inserts. The NEW AS NEW could also be excluded, but its
nice to be explicit here. I also took out the DECLARE line where I declared a variable I never used.
6. Narender Says:
March 22nd, 2006 at 4:49 am
7. Jon Says:
March 22nd, 2006 at 8:10 am
Youre welcome.
Jon
8. Daniel Says:
3 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Great post!
Id like to use your trigger solution, but was wondering about the best way to capture the most recent ID.
Any thoughts?
Thank you!
Im doing a java program that interfaces with an oracle database and require to know how to get the id generated for
the last insert for use in later processing.
Shaun
Thanks For this Post! this has made the oracle world easy!
Any clue how I can easily and reliably grab that id number in PHP? In PHP with MySQL I would use the function
mysql_insert_id() to grab it. However, there is obviously no direct equivelant in Oracle Im aware of. Thoughts?
12. Life After Coffee Oracle Auto increment Columns - Part 2 Says:
May 22nd, 2006 at 5:20 pm
[...] Three separate people have commented on my previous article on How to Create Auto Increment Columns in
Oracle asking how they can retrieve the value of an auto increment column for use later in their code. Well Daniel,
Shaun and Zach, heres the answer. [...]
I copied your codes (create table, sequence and trigger). The first two (table and sequence) worked, but the creating of
trigger failed. The error message is trigger created with PL/SQL compilation error. And could insert any vales to
tables due to fault trigger. Any hints? By the way, I used MS_Query to execute those SQL statements.
D, what version of Oracle are you using? Im not familiar with MS_Query, but some apps dont like having a
semicolon at the end of a PL/SQL block (before the forward slash).
Try again and then run the command show errors and that should give you some better error messages. Good luck!
Jon
4 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
I tried to create the trigger without simicolon but it still doesnt work. I tried show errors, but was told Invalid SQL
statement. Because of that invalid trigger, I couldnt insert any information into the table. Any more hints? Thanks.
Try it through SQL*Plus if possible. At least then the show errors command should work.
I would think this would work just fine in 8.1 but its been a while since I worked with anything prior to 9i.
Jon
Im getting the following error when I try the above trigger with my table.
java.sql.SQLException: ORA-04098: trigger CCTP_WDB.PROD_TRIGGER is invalid and failed re-validation
Keyur,
Try running the trigger creation in SQLPlus or SQL Developer. If the trigger still gives that error type show errors
and you should get a more meaningful error message.
Jon
Hey, thanks for the post. Im getting PLS-00049: bad bind variable NEW.ID when I run these create statements in
SQL*Plus.
Am using REFERENCING NEW AS NEW and SELECT INTO :NEW.ID FROM DUAL.
Jon
5 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
I had the same problem as Keyur. I was attempting to create my triggers using Squirrel (which I have to say is an
excellent program, but not particularly good for proceedures). I found that Squirrel couldnt interpret the commands,
and was therefore creating invalid triggers, and wouldnt tell me why. The Show errors command didnt work. So I
downloaded another excellent program called TOAD, which allowed me to create the triggers and get everything
working. It has an excellent interface with SQL window and proceedure window. It also has a wizard type feature
which helps you create triggers or a series of other statements if you are a novice or unsure of the syntax.
Stu
Stuart,
Glad TOAD worked for you. We used to use it heavily for development but have recently switched to Oracles SQL
Developer. Check it out. It has much of the functionality of TOAD with less clutter.
Hi Jon, thank you for taking the time to address sequencing. I have a variation of the code above that Im trying to
write. It would dynamically identify the number by which I have to ALTER the incremental value of a SEQUENCER
in Oracle. My scenario is that we have an external batch load of data into the data warehouse that is not using the
sequencer.. The SEQ field is manually being set to begin at the max+1 of the value in the table. So every night I have
to reset the sequencer to be the max value of that same table to account for the recently added records.
So Ive got all the pieces I need, but when I put them together inside a stored procedure I get a syntax error with no
explanation. Heres the code. I must be missing something really simple that I hope you will see easily. If you have a
moment, Id appreciate your insight. Thanks. Mike
/* I just keep this code here for safe keeping ignore for now
create table MGA_AUDIT_SEQ (
MGA_POLICY_MAXVAL NUMBER
, MAX_POL_SEQ_NEXTVAL NUMBER THIS IS THE VALUE IN CACHE FOR THE SEQUENCER
, SEQ_DIFF NUMBER THIS IS THE DIFFERENCE BETWEEN THE 2 ABOVE VALUES
, LOAD_DATE VARCHAR2(10) JUST SYSDATE IN MM/DD/YYYY FORMAT
);
COMMIT;
*/
6 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Hey there
GREAT SITE! Im moving over from MySQL so this site is extremely helpful for me.
Just one question, I was thinking of creating a sequence that I could use on lots of other tables, so say:
Then later for all my tables I would just use that sequence called auto_increment, however my question is as follows:
Would using the same sequence for all my other tables that need to be incremented be effected by other uses of it. As
in say another table was using that sequence, would it effect my current table who is also using that same sequence? or
would it be best to create a special sequence for every table that needs one.
Thanks
7 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Dave
Hopefully you might know what has happened to me here, I am getting a compilation error:
I created a table, created a sequence and then created the trigger in exactly the same way as your site describes, but it
failed with the following errors:
so I ran:
LINE/COL ERROR
2/46 PLS-00049: bad bind variable NEW.ID
AUTO_INCREMENT
trigger
ops I had a blonde moment! the reason it didnt work was ID was not in my users table, it is userID not ID
8 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Well I hope I helped something out there who may have had that highlighted moment
Michael,
You should try running this in SQL*Plus and after you get procedure
compiled with compilation errors or an error like this (Im guessing
thats what youre getting) type show
errors.
That should give you a more useful ORA- error. Im guessing the
problem youre having is with the ALTER SEQUENCE command.
That is DDL (data description language), language that defines or
changes the objects and structures in the database. PL/SQL has
trouble with DDL and most ALTER, DROP and
CREATE commands will result in an error when they are in
PL/SQL blocks.
30. Life After Coffee Happy Birthday Life After Coffee! Says:
August 2nd, 2006 at 3:04 pm
Thank you very much for this clarification. It has been of great help. There is none the less one thing that I do not
understand (althought your code works perfectly in my DB) is the DUAL keyword. What is its purpose?
http://www.adp-gmbh.ch/ora/misc/dual.html
dual is a table which is created by oracle along with the data dictionary. It consists of exactly one column whose name
is dummy and one record. The value of that record is X.
rene@ora92> desc dual
Name Null? Type
-
DUMMY VARCHAR2(1)
D
-
9 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
X
The owner of dual is SYS but dual can be accessed by every user. As dual contains exactly one row (unless someone
fiddled with it), it is guaranteed to return exactly one row in select statements if a constant expression is selected
against dual, such as in:
select sysdate from dual
Although it is possible to delete the one record, or inse
Hi,
Do you think there will be any issues with using a sequence and triggers in an OLTP as there involves a context switch
when executing a trigger in the database?. In my approach I use my ORM layer (TROQUE) to generate the id, and it
has served me well.
thanks
Nadeem,
There should not be an issue if a sequence is used. If you grab nextval from a sequence and some one else grabs one
even before you have committed your changes they will receive the next number in the sequence. Even if you do not
use the value you retrieve from the sequence it is yours forever.
Im not familiar with TROQUE, but if youre worried you should probably ask their support about this?
[...] Graas ao Life After Coffee por este post jeitoso [...]
The trigger method guarantees that you can never have a duplicate primary key.
Using the sequence in the insert statement method works, until someone does an insert without using the sequence.
Lets say you have one row in your table, with ID = 1. Someone decides they need to have a record with ID = 10, and
so they insert using insert into table (id) values (10). You now have a ticking timebomb the sequence will
continue to increment 2, 3 etc, until it reaches 10 at which time the insert fails with
ERROR at line 1:
ORA-00001: unique constraint (SYS.SYS_C002948) violated
However using the trigger method, if someone tries to specify an explicit ID value, the trigger will overwrite the
specified value with the value from the sequence.
I guess there is some performance gain from not using the trigger, so if you trust all the code that accesses your
database and performance is critical, the sequence in the insert statement method may be what you need. Otherwise,
the trigger method is safest, and also means you can be lazy when inserting.
All good points Sam. From a data architecture standpoint my tendency is to not trust the developers, especially in big
organizations. Either is valid, just one tends to be riskier than the other.
10 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Hi,
let me know how can get the sum of first and second sal ,second and third sal ,third and fourth sal and so on.. from
emp table.please give me the SQL statement for this query
Many will gripe about this not being a standard feature in Oracle
Hello Jon, Greetings!!! Great post.. This really helped me to resolve one of my critical requirements Thank
you so much Cheers @Srinivas
This way you are able to specify the primary key (column id in my example) if you need to.
Hi,
I am using sage crm in the frontend and oracle in the backend, we are using sage crm to log cases from the customer,
whenever a new case is created, a ref id is generated by using the procedure and this works fine.
The problem occurs only when i create a new case and cancel it, ie; i am not saving the case, but when i create a new
case again, i get a new ref id instead of previous ref id. This is destroying my report.
If i create a new case and cancel it then my ref id should be free and must be fetched for the next new case, how can i
resolve this problem.
TIA
Mohammed.
11 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Just a minor suggestion. This does not work the same as the MySQL solution (which allows you to specify a value for
ID if you want to), as the trigger will always add the value from the sequence.
to be:
This will now only use the sequence if no value is passed in for ID.
hey,wot do i do, if i need to generate a number sequence with character prefixes,say I need to auto increment the
column Product_id for every product inserted??
S.
If you want to have the same character appear before each sequence number all you need to do is concatenate the
letter in the trigger like this:
If youre looking to increment the leading letter youre going to have to get a bit trickier. Maybe others will have ideas,
but something like a switch may be in order.
this code works perfectly right up until i delete a row from the table and start adding new rows.. the sequence starts
jumping numbers.. help! any suggestions would be appreciated!
12 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
CREATE TABLE person (ID NUMBER(11) NOT NULL, givenName NVARCHAR2(60) default A default value
NOT NULL, surName NVARCHAR2(60) NOT NULL, CONSTRAINT person_pk PRIMARY KEY ( ID ) )
ORGANIZATION INDEX;
The returned Object is a ROWID, and im not able to get the ID for the inserted row.
if (st.executeUpdate() != 0)
{
ResultSet rs = st.getGeneratedKeys();
if (rs.next())
int idValue = rs.getInt(1);
}
Leave a Reply
Name (required)
Website
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime="">
<em> <i> <q cite=""> <strike> <strong>
13 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Search
My Books
Oracle Shell Scripting
14 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
NetApp Pulses
Strength
Discover How NetApp
is Revolutionizing
Enterprise Storage
www.NetApp.com
PunchOut Catalogs
Integrates seamlessly
with ALL
eProcurement
platforms
www.PunchOutCatalogs.com
CRM Integration
Integrate any CRM
with any App. Fin,
ERP, DB, Web
Service, etc.
www.interweave.biz
Demantra
Consulting
End-to-End consulting
services Value Chain
Planning experts
www.gaeaglobal.com
Categories
Recent Comments
narumon sirchok on American Inventor Season 2 Or Not Season 2
Nitin on Oracle SQL Developer A New GUI For Database Development
shanice on Dress made of condoms
theo on SQL Finding the Last Weekday in a Month
Wayne Bradey on The Straight Poop on Kopi Luwak Coffee
Blogroll
15 of 16 6/9/2010 2:25 PM
Life After Coffee How to Create Auto Increment Columns in Oracle http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment...
Always Learning
BorkWeb.com
MaisonBisson.com
Miscellany of a Cheshire Cat
NoSheep.net
SpiralBound.net
MasterWish
MasterWish.com
My Wishlist
Oracle Resources
BC Remote DBA
Blogs.Oracle.com
Daily Oracle News
Oracle.com
Sponsored Links
Cappuccino Coffee Machines
Coffee Pods and Cappuccino Machines
16 of 16 6/9/2010 2:25 PM