Ask the Expert

Generate unique ID based on records in table

I want to generate the unique ID based on records in the table. If I have any record in the table then I'm able to fire a query like "select max(id) from table" but the first time, when there is no record, then what should I do?

    Requires Free Membership to View

A better design would be to generate the id from a sequence. First, create a sequence similar to the following:
CREATE SEQUENCE my_sequence START WITH 1 INCREMENT BY 1;
Then create a trigger to automatically populate your table's column with the next number in the sequence:
CREATE TRIGGER my_tab_trig
BEFORE INSERT ON my_table
AS
   next_num NUMBER;
BEGIN
   SELECT my_sequence.NEXTVAL INTO next_num FROM dual;
   :new.my_column := next_num;
END;
/
When a user inserts a row of data into the table, Oracle will run the trigger which will set the column value to the next unique number in the sequence. Forgive me if the above code is not perfectly correct as I typed it all off the top of my head. But this is definitely enough to get you started.

This was first published in April 2007

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: