Generating a Primary Key Automatically (Cont.)


Creating a Sequence
A SEQUENCE is a data object that multiple users can access to automatically generate incremented values. It prevents duplicate values from being created simultaneously because multiple users are effectively forced to “take turns” before each sequential item is generated. For the purposes of creating a unique primary key for a new table,
  1. First we must CREATE the table, course3, we’ll be using.

  2. Add a primary key to the table by using ALTER TABLE.

  3. We’ll create our SEQUENCE that will be utilized later to actually generate the unique, auto incremented value.

  4. INSERT a row into the table and use NEXTVAL function to generate a primary key.
SQL> CREATE TABLE course3 (
  2    cnumber  NUMBER       NOT NULL,
  3    title    VARCHAR2(64) NOT NULL );

Table created.

SQL> ALTER TABLE course3
  2    ADD ( CONSTRAINT course3_pk PRIMARY KEY ( cnumber ) );

Table altered.

SQL> CREATE SEQUENCE course3_seq;

Sequence created.

SQL> INSERT INTO course3 VALUES ( course3_seq.NEXTVAL, 'Databases' );

1 row created.

SQL> INSERT INTO course3 VALUES ( course3_seq.NEXTVAL, 'Advanced Database Systems' );

1 row created.

SQL> INSERT INTO course3 VALUES ( course3_seq.NEXTVAL, 'Data Engineering and Mining' );

1 row created.

SQL> SELECT * FROM course3;

   CNUMBER    TITLE
----------    ------------------------------------
         1    Databases
         2    Advanced Database Systems
         3    Data Engineering and Mining



Demonstration
Below is an SQL test area from W3Schools, which uses the well-known Northwind sample database. The tables here are for read only because of the problem of embedding the scripts. For a fully working example, check this by using Chrome.

SQL Statement:

Edit the SQL statement and click     to see the result, or  

Result:
The Database includes:
The Database includes:

TablenameRecord
Customers91
Categories8
Employees10
OrderDetails518
Orders196
Products77
Shippers3
Suppliers29