Auto Increment column in database table

Hello experts, I am using oracle 11g database at windows 7.I have to create a sequence object and a table with an auto increment ID column.For this I have created a trigger before insert to select next sequence from a sequence object. It works well but Now I have the current sequence is 7 and there are 6 records inserted in table. Now I delete two records.Thus I have only 5 records in table but my current sequence is still 7.So if I put it in id column then a new record will be inserted in table with 7 ID number after 5th ID number.I want this record should be inserted with 6 Id number. For this I tried to not use sequence object.I tried a pl/sql trigger before insert, which will count the all records in table and after increment i put it in ID column to insertion....Is this a professional way..? thank You regards aaditya

979801 wrote:
Hello experts, I am using oracle 11g database at windows 7.I have to create a sequence object and a table with an auto increment ID column.For this I have created a trigger before insert to select next sequence from a sequence object. It works well but Now I have the current sequence is 7 and there are 6 records inserted in table. Now I delete two records.Thus I have only 5 records in table but my current sequence is still 7.So if I put it in id column then a new record will be inserted in table with 7 ID number after 5th ID number.I want this record should be inserted with 6 Id number. For this I tried to not use sequence object.I tried a pl/sql trigger before insert, which will count the all records in table and after increment i put it in ID column to insertion....Is this a professional way..? thank You regards aaditya
Sequences only guarantee unique numbers.  You cannot (and should not) attempt to create gapless sesquences.  That's not how oracle works and will not scale to a multi user application.
Imagine two people try to insert records at the same time (and have yet to commit), the trigger you create will count the number of records and determine there are 5 records, so assign the next number of 6, for both people who are inserting records.  The first person to commit will get their data saved, and assuming you have a unique constriaint on that id, the second person will raise a duplicate key on insert or suchlike error.
Gapless sequential numbers are not appropriate to multi-user environments.  Such requirements are often given by managers or business people who do not understand the technology.
Think of it in terms of a real world office, but with people using a paper system instead of a computer.  The only way you can try to guarantee people get the next number and also re-use numbers that have been deleted is to have a single place where each person in the office goes to, to fetch the next number, and they have to queue up behind each other to get the next one off the list.  But if someone has removed an old record, they've got to wait in the same queue to go and put that number back in the pot for someone else to use.  It just doesn't work, even in a manual system.  Yes, people can guarantee that they're only getting unique numbers that nobody else is using, but they cannot guarantee that they are reusing and filling gaps etc.  It's an unrealistic expectation.

Similar Messages

  • Auto Increment Columns Are Not Recognized

    Hi
    I am using postgre 8 and there are some auto incremented columns
    in some tables. The problem is when I create the DataProvider from a table or a view those columns are not recognized by the IDE. I realized this while running the generated SQL. Is this a known issue ? Finally is there a work around this.
    Thanks
    Mehmet Atlihan

    Hi Mehmet,
    Creator requires a JDBC 3 compliant driver and PostgreSQL database driver is not fully compliant. Please take a look at the below thread which discusses about the issue:
    http://swforum.sun.com/jive/thread.jspa?forumID=123&threadID=53064
    Cheers
    Giri

  • Insert data into Access with Auto-Increment column

    Is there anyone out there that has come across this problem I am experiencing?
    I have a form I'm trying to submit to an Access DB that has an Auto-Incremented Table Column. I have followed Stefan Cameron's instructions to a "T" on his blog page here:
    http://forms.stefcameron.com/2006/09/18/connecting-a-form-to-a-database/
    but I keep getting the following error"
    GeneralError: Operation failed.
    XFAObject.open:10:XFA:form1[0]:mysubform[0]:myEIFform[0]:overflowLeader[0]:Submit[0]:click
    open operation failed. [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
    My OLEDB Connection Record Source is the SQL Query which reads: SELECT FedTaxID, LegalID FROM dbtest; My simple test DB is Access and its only 3 columns; dbID, FedTaxID, LegalID. dbID is the Auto-Incremented Column.
    If I remove the Auto column from my DB table it inserts just fine but I get this error:
    GeneralError: Operation failed.
    XFAObject.open:10:XFA:form1[0]:mysubform[0]:myEIFform[0]:overflowLeader[0]:Submit[0]:click
    ado2xfa operation failed. Item cannot be found in the collection corresponding to the requested name or ordinal.
    I've looked over alot of the blogs and other help forums and there's info on Selects, I don't find much on Inserts.
    Can anyone direct me in the right direction? Thank you.

    First, please pay attention to the forum in which you are posting.  This particular post would be more appropriate to tsql rather than datamining.  Second, what specific problem are you trying to solve.  The code you posted appears to be
    correct.  I will say that your DataTable will likely be a source of future problems if it contains only the 2 columns.

  • Primary key violation exception in auto increment column

    Hi All,
    I am facing one issue in Multi threaded environment.
    I am getting Primary key violation exception in auto increment column. I have a table and the primary key is the auto increment column, and I have a trigger which is populating this column.
    5 threads are running and inserting the data in the table and throwing Primary key violation exception randomly.
    create table example (
    id number not null,
    name varchar2(30)
    alter table example
    add constraint PK1example primary key (id);
    create sequence example_id_seq start with 1 increment by 1;
    create or replace trigger example_insert
    before insert on example
    for each row
    begin
    select example_id_seq.nextval into :new.id from dual;
    end;
    Any idea how to handle auto increment column(trigger) in Multi threaded environment??
    Thanks,

    user13566109 wrote:
    Thanks All,
    Problem was in approach; removed the trigger and placed a seq.nextval in insert query. It has resolved the issue.I very much suspect that that was not the issue.
    The trigger would execute for each insertion and the nextval would have been unique for each insertion (that's how sequences work in oracle), so that wouldn't have been causing duplicates.
    I suspect, more likely, that you had some other code somewhere that was using another sequence or some other method of generating the keys that was also inserting into the same table, so there was a conflict in the sources of the sequences being generated.
    The way you showed you had coded above, was a perfectly normal way to assign primary keys from a sequence, and is not a problem in a multi user/threaded environment.

  • Auto Increment column query

    I have a very simple table used for debugging:
    CREATE TABLE APPS.XX_DEBUG_TMP
      TEMP_VALUE  VARCHAR2(255 BYTE),
      TEMP_DATE   DATE
    )Then I can use it to store values as my pl/sql is processed - e.g.:
    INSERT INTO XX_DEBUG_TMP (TEMP_VALUE,TEMP_DATE) VALUES ('line 740 l_username value check:' || l_username,SYSDATE);  COMMIT;Trouble is that if a load of debug statements get processed with the same timestamp, I can't see which came first.
    Can I modify my table creation SQL to include an ID column which just increments for each row that is added to the table?
    I'm familiar with how to do it in MySQL (sorry - I know this is an Oracle forum - but am just putting this here to show what I mean):
    CREATE TABLE  `XX_DEBUG_TMP` (
    `TEMP_ID` MEDIUMINT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `TEMP_VALUE` VARCHAR( 255 ) NOT NULL ,
    `TEMP_DATE` DATETIME NOT NULL
    ) ENGINE = MYISAM ;Is it that simple with Oracle? Probably not!
    Any advice much appreciated.
    Thanks

    There is no auto increment column in Oracle. However, you can create a sequence.
    CREATE TABLE APPS.XX_DEBUG_TMP
      TEMP_ID     NUMBER NOT NULL PRIMARY KEY,
      TEMP_VALUE  VARCHAR2(255 BYTE),
      TEMP_DATE   DATE
    CREATE SEQUENCE APPS.XX_DEBUG_TMP_SEQ;Then in your insert statement do this:
    INSERT INTO XX_DEBUG_TMP (TEMP_ID,TEMP_VALUE,TEMP_DATE) VALUES (APPS.XX_DEBUG_TMP_SEQ.NEXTVAL,'line 740 l_username value check:' || l_username,SYSDATE);  Another possible solution to your problem would be to use a TIMESTAMP data type instead of a DATE data type. It has fractional second resolution (up to 9 places I believe).

  • Can we specify prefix for an auto increment column

    Hi all,
    I want to create an auto increment column in oracle using oracle sequences.
    But i want to specify a prefix for the value appearing after increment.
    Prefix will remain constant.
    If we can how can i do that.
    And one more thing is i will call the sequence using a trigger only for a specified condition.My doubt here is can i allow nulls for auto incrementing column
    With Regards

    <s></s>
    -- Samples.
    create table tab1
    (id   varchar2(6) constraint p_tab1 primary key
    ,data varchar2(255)
    create sequence seq_tab1;
    create or replace
    trigger trg_tab1
    before insert on tab1
    for each row
    declare
      p_prefix varchar2(2) := 'AA';
    begin
      if (:new.id is null) then
        select p_prefix||to_char(seq_tab1.nextval,'fm0009') into :new.id from dual;
      end if;
    end
    -- Test
    SQL> insert into tab1(data) values('abc');
    1 row created.
    SQL> insert into tab1(id,data) values('BB9999','xyz');
    1 row created.
    SQL> select * from tab1;
    ID
    DATA
    AA0001
    abc
    BB9999
    xyz

  • Add auto increment column to trigger

    I want to add auto increment column to after insert trigger. so how can I do that?

    this is my query.
    Create Sequence Up_Seq
    Start With 1
    Increment By 1
    nomaxvalue;
    Create Or Replace Trigger Upf_Trig
    After Insert On members
    Referencing New As New
    For Each Row
    Begin
    Insert Into Upf_Kgl(Member_Id,Mem_Name,Nic,Division)
    Values (Up_Seq.Nextval
    *,:New.Mem_Name*
    *,:New.Nic*
    *,:New.Division);*
    end upf_trig;
    It's worked. but when inserting values to members table, there is an error.
    this is the error
    Error starting at line 21 in command:
    Insert Into Members(Mem_Name,Nic,Full_Name,Age,Sex,Mar_State,Birth_Date,Division,Religon)
    Values(
    *'IA Nawagamuwa'*
    *,'883324356V'*
    *,'Isuru Aravinda Nawagamuwa'*
    *,'22'*
    *,'Male'*
    *,'Single'*
    *,'21-Dec-88'*
    *,'kgl'*
    *,'Buddhist')*
    Error report:
    SQL Error: ORA-00001: unique constraint (SYSTEM.SYS_C004077) violated
    ORA-06512: at "SYSTEM.UPF_TRIG", line 2
    ORA-04088: error during execution of trigger 'SYSTEM.UPF_TRIG'
    *00001. 00000 - "unique constraint (%s.%s) violated"*
    **Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.*
    For Trusted Oracle configured in DBMS MAC mode, you may see
    this message if a duplicate entry exists at a different level.
    **Action: Either remove the unique restriction or do not insert the key.*

  • What does the setting "auto increment column templates"

    I have noticed that there is now a setting "auto increment column templates" but I cannot find out what this setting does.
    There are no sequences generated nor triggers.
    Version 3.0.
    Thanks, Joep

    There are no sequences generated nor triggersYou need to set column as "auto increment". Then sequence and trigger will be generated for Oracle.
    You can set template for generated sequences and triggers and can override these settings at column level setting explicitly the name of sequence and trigger.
    The sequence and related trigger are not created as objects in physical model, however if there are such objects defined then definition from physical model is used for generated DDL.
    Philip

  • Problem with Auo Increment field in Database table

    HI...
    I have a table with Auto increment field.
    I am using Sql Server 2000.
    I have a Table Component on front end which is binded with that (auto increment) table.
    When I call commitChanges() I receive following exception :
    Exception Details:  java.lang.RuntimeException
      Number of conflicts while synchronizing: 1 SyncResolver.INSERT_ROW_CONFLICT row 2 [sunm][SQLServer JDBC Driver][SQLServer]Cannot insert explicit value for identity column in table 'Authorization_Book' when IDENTITY_INSERT is set to OFF.Anybody knows the solution...

    The following excerpts are from http://blogs.sun.com/roller/page/jfbrown?entry=using_creator_to_insert_into. Do they help?
    What about IDENTITY or AUTOINCREMENT or other database-generated columns?
    This is highly database dependent. Some databases require you to obtain the key through vendor-specific means. Others say "set the value to null". Some say to not include the column in the INSERT statement.
    So how do I exclude my IDENTITY or other column from the INSERT statement?
    Use the RowSet's advanced insertableColumns property. Create a boolean[] array with one value for each column in the result. Use true to include the column in the INSERT statement, otherwise use false. The RowSet's property sheet doesn't allow you to set this property (in Creator2-EA2), so set the property in your java code.

  • How can I automatically increment an auto incremented column?

    Hello!
    I have a table with an auto incremented "id" field.
    It looks like this:
    id (PK, auto_increment) name address phone
    I would like to make an insertion like:
    INSERT INTO Person (name, address, phone) VALUES (?,?,?)
    ...but it says that all fields have to be used.
    I get
    java.sql.SQLException: Field 'id' doesn't have a default value
    How can I bypass this?
    I have looked at [this example|http://blog.taragana.com/index.php/archive/java-how-to-get-auto-increment-values-after-sql-insert/] , but it didn´t work for me, it still says the "id" column has not a default value:

    Sorry, it is a MySQL database.
    The table consists of 4 columns:
    id (PK, auto_increment)
    name (Varchar)
    address (Varchar)
    phone (Varchar)
    If I use PHPMyAdmin to insert a new row, then this query works:
    INSERT INTO `mydb`.`person` (
    `id` ,
    `name` ,
    `address` ,
    `phone`
    VALUES (
    NULL , 'Test', 'Roxxor', 'Europe', '12345'
    );{code}I tested to use the method setNull() on the first column in the preparedStatement but it didn&acute;t work.
    Do you need more info from me to be able to help me?
    I have tried this (but got the error that the "Field 'id' doesn't have a default value"):
    [code]con.setAutoCommit(true);
                String query = "INSERT INTO person(id, name, address, phone) VALUES (?, ?, ?, ?)";
                PreparedStatement stmt = con.prepareStatement(query);
                stmt.setNull(1, java.sql.Types.NULL);
                stmt.setString(2, name); 
                stmt.setString(3, address);     
                stmt.setString(4, phone); 
                stmt.executeUpdate(); 
                stmt.close();[/code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Identifying auto-increment columns

    Hi,
    I am developing a database management package for mysql. I want to be able to provide a sql dump facility, which will produce the sql code for creating a table and populating it.
    I do not seem to be able to find a function for identifying if a field is auto-incrementing?
    The only thing that I could find it the DatabaseMetaData.getTypeInfo() will let you know if a field can used for an auto-increment value, not if it is actually auto-incrementing.
    Please help!

    If you do a query of this table and then have a look at
    the ResultSetMetaData you can use the methode:
    boolean isAutoIncrement(int column)
    Indicates whether the designated column is
    automatically numbered, thus read-only.
    Or you can use the MYSQL-command :
    show columns from table to get all the info of each
    column.
    mysql> show columns from table;
    -----------------------------------------------------------------------------+
    | Field | Type | Null | Key | Default | Extra |
    -----------------------------------------------------------------------------+
    where the Extra column contains 'auto_increment ' if it is...
    ...what in fact is not that DB-independent.....
    Regards
    Fredy

  • How can i create an auto increment column

    Hello Everyone
    We are working on an EAM package which has an auto number facility but that is not meeting our requirement because some 10s and 100s of numbers keep on jumping based on the number of records the child table has.Means every record in my parent table will have some child records in another table which we call it a child table.The number of numbers that will be jumped each time will depend on the number of child records it has. Now we want to create a new column and generate a sequential unique number in my parent table with out linking it to its child table and use this number as a reference number. And we cant do that through our package customization. Can any one guide us if we can meet our requirement through oracle triggers or so.
    Thanks and Regards

    Hi,
    For "Auto-Increment" functionality - you can use a combination of a sequence and a trigger like so:
    create table roles ( role_id INT
                       , role_name VARCHAR2(30) NOT NULL
                       , creation_date DATE DEFAULT SYSDATE NOT NULL
                       , role_description VARCHAR2(255)
                       , CONSTRAINT roles_pk PRIMARY KEY (role_id)
                       , CONSTRAINT roles_uk1 UNIQUE (role_name)
    create sequence role_id_seq
    start with 1
    increment by 1
    nocache;
    CREATE OR REPLACE TRIGGER roles_pk_trig
    BEFORE
    insert on roles
    for each row
    begin
    IF :new.role_id IS NULL THEN
       SELECT role_id_seq.NEXTVAL
       INTO :new.role_id
       FROM dual;
    END IF;
    end;
    /Now any insert which leaves the "ROLE_ID" column NULL will have an auto-incremented value put in for that column. This is similar to an "Autonumber" column in Access.
    Hope this helps...
    Take care.

  • Auto increment field in database issue

    Ok, I have read all about the issues with the auto increment field when trying to hook my form up to a ms access database.
    My problem is that the auto increment field is the one field I want in my form.
    Any suggestions how to create a new record with my form? its a simple database, date field, and PO number (the auto incremented field)
    Just trying to get a fresh PO number on my PO form each time its filled out....

    I have a vital form that clients fill out, which is passed to many people in the company along the workflow. The form is a Planner and we have in the following PDF, Word Doc..
    Well before, the Planner.pdf was originally created in Word, since most people have access to Word.. but evolved to a PDF form created from the Word Doc via Adobe LiveCycle Designer 8.0 w/ User Rights enabled so that the form could be filled out and saved using Adobe Reader.. which was a step better than Word.. being that it is free. But this needed to be easier and more to the point b/c some clients don't particularly like installing the latest version of Reader, even if you provide them the link. Nor do they like saving the form, filling the form, and attaching the form to send back.
    My goal is to have the client fill an HTML version of the form, submit and be done with it, but everyone in the workflow be able to easily receive the filled Planner as a PDF form.
    So some months ago I ran into this post Chris Trip, "Populate Livecycle PDF from mySQL database using PHP" #8, 22 Sep 2007 4:37 pm
    which uses the command line Win32 pdftk.exe to merge an FDF file into an existing PDF on the remote server, and serve this to whoever.
    My problem was with shared hosting and having the ability to use the Win32 pdftk.exe along with PHP which is predominantly used on Linux boxes. And we used a Linux box.
    so i created the following unorthodox method, which a client fills the HTML version of the Planner, all field values are INSERTED into a table in MySQL DB, I and all filled planners that have been filled by clients to date can be viewed from a repository page where an XML file is served up of the corresponding client, but someone would have to have Acrobat Professional, to import the form data from the XML file into a blank form.. altoughh this is simple for me.. I have the PHP file already created so that when a Planner is filled and client submits. >> the an email is sent to me with a table row from the repository of the client name, #, email, and a link to d-load the XML file,
    But I also have the PHP files created so that the Planner can be sent to by email to various people in the workflow with certain fileds ommitted they they do not need to see, but instead of the XML file beiong served up i need the filled PDF Planner to be served.
    I can do this locally with ease on a testing server, but I am currently trying to use another host that uses cross-platform compatibility so i can use PHP and the pdftk.exe to achieve this, as that is why I am having to serve up an XML file b/c we use a Linux server for our website, and cant execute the exe.
    Now that I am testing the other server (cross-platform host), just to use them to do the PDF handling (and it's only $5 per month) I am having problems with getting READ, WRITE, EXECUTE permissions..
    Si guess a good question to ask is can PHP do the same procedure as the pdftk.exe, and i can eleminate it.
    or how in the heck can i get this data from the DB into a blank PDF form, like i have described??
    here are some link to reference
    Populating a LiveCycle PDF with PHP and MySQL
    http://www.andrewheiss.com/Tutorials?page=LiveCycle_PDFs_and_MySQL
    HTML form that passed data into a PDF
    http://www.mactech.com/articles/mactech/Vol.20/20.11/FillOnlinePDFFormsUsingHTML/index.htm l
    and an example
    http://accesspdf.com/html_pdf_form/

  • Attaching an Auto Incrementer to an existing table

    Hi!
    Have a few tables orders of records of which I need not to change and add an auto-increment sort of additional field to help in sort and manipulate the same. Any idea how to achieve the same???
    Thanx in advance,
    Best Regards, Faraz A Qureshi

    If you use SQL Server 2012 and onwards take a look ta SEQUENCE
    http://msdn.microsoft.com/en-us/library/ff878091.aspx
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Creating an auto incrementing field with CREATE TABLE from Java

    I'm using the "sun.jdbc.odbc.JdbcOdbcDriver" to get a connection towards an ODBC data source that's linked to a Access (.mdb) database.
    I've tried various combinations in my CREATE TABLE statement execution in order to create a table with an auto incrementing integer but neither of them work, not even the most obvious one:
    stmt.executeUpdate("CREATE TABLE mytable(uid integer AUTO_INCREMENT PRIMARY KEY);");
    I always get this runtime exception: *java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in field definition*; and AUTO_INCREMENT is the problem. I've tried all variations like AUTO, INCREMENT, AUTOINCREMENT and such, but nothing works.
    I've looked everywhere but couldn't find an answer to this. Thanks for the help.

    You used MySQL syntax. I think you agree with me that Access isn't a MySQL database. Either use MySQL with a real JDBC driver (recommended) or use Access syntax.
    That said, creating databases and tables using Java is a bad idea. The database and table must be already there. With Java you just do the usual table operations like select, insert, update and delete. Nothing more is needed.

Maybe you are looking for

  • The replacement battery for Ipod nano true or false

    I was tryin to figure out if it was true that you can't replace your battery in an Ipod nano unless you have good sodering skills or unless you send it in and replace it. Because I bought a third party replacement battery for my Ipod Nano, and it gav

  • How to get input source line number

    I wrote a XSLT transformation that checks the input XML for errors. When the transformer finds a problem, it can terminate with <xsl:message terminate="yes">, which outputs the line number within the transformer XML source. I do so in my implementati

  • Showing text in scrollable way

    Hello I am writing a jsp where it will show some multiple line texts in a scrollable way ( it could be text area or combo box). My requirements are 1. The text must be scrollable 2. User can not edit the text. How can I do that . My first try was put

  • Copy Responses not Working

    I have a folder that I am watching on a ingest station and it is set to do a full scan daily at midnight and a add only scan every 15 minutes. I have a automation setup so that it copies from that folder into a new final destination. I don't have a d

  • Oracle weblogic 12c 64bit

    64-bit version of Oracle WebLogic 12c download .When will there be.