Click here to Skip to main content
Click here to Skip to main content

How To Create Auto Generated Primary Key in Oracle Database

By , 21 Sep 2012
 

For the first time in my life (finally) I decided to make an article about oracle database. This semester is my first time learn about database, and you know, the curriculum in my country is very suck. Until almost at the end of the semester, I just learned about CDM, PDM, DDL, DML, and some basic queries. So, is that all about database? Of course not. How about sequence, trigger, and anything else. Unfortunately, I have to wait next semester to learn about it (it’s really waste of time).

Like usually, at the end of semester, I was given Final Project. Yeah, this time I have to create an application about convection using oracle database and C#. I already have CDM, PDM, DDL, and DML of database. Now it’s time to create the application. But, before I get into that step, I think about something. It’s about Primary Key.

You know, until yesterday, if I add new record in a table, I also type the primary key manually. It’s really waste of time. You know why? Because Primary Key is always sequential. So, why don’t we make Auto Generated Primary Key?

Okay, let’s make our database create Auto Generated Primary Key. I don’t care if it’s not in this semester’s curriculum. I will implement it in my Project. To do this, we need to use Sequence and Trigger (What is this again?). Leave the complete definition later. I will explain it in simple way. Sequence  is kind of auto generated number with pattern (just like 1,2,3,… or 2,4,6,…). Trigger  is trigger (I don’t know exactly), maybe it’ll be executed after some event. That’s enough for the definition, let’s get into the point.

1. Let’s create a table, let’s make Human table with two columns: HUMAN_ID (Primary Key) and HUMAN_NAME. If you really lazy, you can use DDL below (You can use SQL Developer to execute all queries):
CREATE TABLE HUMAN 
(
  HUMAN_ID VARCHAR2(3) NOT NULL, 

  HUMAN_NAME VARCHAR2(20), 
  CONSTRAINT HUMAN_PK PRIMARY KEY 
  (
    HUMAN_ID 
  )
);

2. Now, let’s make a sequence! We will make the table so it’ll look like something like this:
Human Table

Then, if you look into HUMAN_ID, you’ll notice that that key is start from H01 and will be increased until H99. If you make an application and add the Primary Key manually, it’ll be very annoying. So, let’s make a sequence from 1 to 99 and add ‘H’ prefix so it’ll become the primary key. Here is the query you need to make sequence:
CREATE SEQUENCE HUMAN_PK_SQ
INCREMENT BY 1 
START WITH 1 
MAXVALUE 99 
MINVALUE 1 
CYCLE 
NOCACHE 
ORDER;

Or, if you use SQL developer, you can use the GUI and create it in easy way:
Create New Sequence

Oracle New Sequence

3. Okay, now let’s make a trigger! Here is the query you need if you want to create a trigger that’ll be generate primary key automatically:
CREATE OR REPLACE TRIGGER HUMAN_PK_TG
before insert on HUMAN
for each row 
declare
  max_human_id number;
  cur_id number;
begin
  if inserting then       
    if :NEW."HUMAN_ID" is null then
      -- if HUMAN_ID is not inserted, add new generated ID
      select concat('H', to_char(HUMAN_PK_SQ.nextval, 'FM00')) 
      into :NEW."HUMAN_ID" 
      from dual;
    else
      -- HUMAN_ID is inserted, update the sequence
      select to_number(substr(greatest(max(HUMAN_ID), :NEW."HUMAN_ID"), 2))
      into max_human_id from HUMAN;
      select HUMAN_PK_SQ.nextval into cur_id from dual;
      while cur_id < max_human_id
      loop
        select HUMAN_PK_SQ.nextval into cur_id from dual;
      end loop;
    end if;    
  end if; 
end;
* You can see Oracle Number Format if you want to make your pattern.

4. Now, let’s add some new records, use new records below:
INSERT INTO HUMAN (HUMAN_NAME) VALUES ('Junichi');
INSERT INTO HUMAN (HUMAN_NAME) VALUES ('Baka');
INSERT INTO HUMAN (HUMAN_NAME) VALUES ('Junian');
and here is the result:

Human Table

You see it right? You don’t need to add Primary Key manually. It’s automatic. So, what are you waiting for? Just implement it to get a good result.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Junian Triajianto
Software Developer
Indonesia Indonesia
Member
Just an ordinary geek.
 
For more information visit my blogs:
Kodefun, learning by coding
Junian's Legacy
Junian Universe

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberKlaus Luedenscheidt21 Sep '12 - 17:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 21 Sep 2012
Article Copyright 2012 by Junian Triajianto
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid