Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Sequence starting with 2 instead of 1

Unexpected behavior:

I am encountering strange behavior of Oracle sequences with 11g (works with 10g):

CREATE SEQUENCE test_sequence START WITH 1;
CREATE TABLE test_table ( val INT );

INSERT INTO test_table VALUES ( test_sequence.NEXTVAL );

Even though the sequence starts with 1, the first value inserted is 2:

SELECT * FROM test_table;

       VAL
----------
         2

Expected behavior:

Selecting NEXTVAL without the insert works as expected:

CREATE SEQUENCE test_sequence_2 START WITH 1;

SELECT test_sequence_2.NEXTVAL FROM dual

   NEXTVAL
----------
         1

Question:

Can anyone reproduce this using Oracle 11g? Is this a known issue?

I'm using
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production.

like image 807
Peter Lang Avatar asked Nov 11 '10 11:11

Peter Lang


People also ask

Can we alter sequence in Oracle?

Use the ALTER SEQUENCE statement to change the increment, minimum and maximum values, cached numbers, and behavior of an existing sequence. This statement affects only future sequence numbers.

What is Nocache in sequence?

Specify NOCACHE to indicate that values of the sequence are not preallocated. If you omit both CACHE and NOCACHE, the database caches 20 sequence numbers by default.


1 Answers

Use:

CREATE SEQUENCE SQ_SEQUENCE_NAME
    INCREMENT BY 1
    START WITH 1
    MINVALUE 0  -- This will ensure start at 1!
    MAXVALUE 99
    NOCYCLE
    NOCACHE
    ORDER;
like image 166
Leomir Andrade Avatar answered Sep 18 '22 15:09

Leomir Andrade