If you're coming from MySQL or PostgreSQL, generating a primary key in Oracle takes a bit of getting used to. Instead of an AUTO_INCREMENT or SERIAL column, Oracle hands that job to a separate counter object called a sequence.
1. What is an Oracle sequence?
A sequence is a counter that lives in your database and hands out unique numbers whenever you ask for one. It's not attached to any particular table. You set it up once, then pull numbers from it anywhere you need a unique ID, whether that's for a customer_id, an order_id, or something else entirely.
2. Creating your first sequence
A few lines of SQL are all it takes:
A quick rundown of what those settings actually mean:
| Option | What it does |
|---|---|
| START WITH | The first number the sequence will hand out. |
| INCREMENT BY | How much the counter jumps with each new number. |
| MINVALUE / MAXVALUE | The lowest and highest values the sequence is allowed to reach. |
| NOCYCLE | Keeps the sequence from wrapping back around to 1 once it hits MAXVALUE. |
| CACHE 20 | Loads 20 numbers into memory ahead of time so inserts run faster. |
You can double check the sequence actually got created by querying the data dictionary:
3. Testing the sequence
There are two pseudo-columns you'll use to actually read values from a sequence:
- NEXTVAL: pulls the next number in line and moves the counter forward.
- CURRVAL: shows the last number your session generated. It won't work until you've called NEXTVAL at least once.
4. Three ways to link a sequence to a table
Once the sequence exists, you still need to connect it to your table's primary key. Which route you take mostly comes down to which Oracle version you're running.
Option A: DEFAULT (best for Oracle 12c and newer)
This is the cleanest option if you're on a modern Oracle version. You just assign the sequence right in the table definition.
From here you can skip customer_id in your inserts altogether:
Option B: reference NEXTVAL directly in your INSERT
If there's no default set on the table, you'll need to call the sequence yourself every time you insert a row:
Option C: trigger-based (legacy, pre-12c)
On Oracle 11g and earlier, a column couldn't reference a sequence directly, so people used a BEFORE INSERT trigger instead. You'll still run into this in a lot of older codebases:
5. Pros and cons
|
PROS
|
CONS
|
6. Complete working example
Here's a full script you can copy, paste, and run as is:
Which gives you:
| CUSTOMER_ID | FIRST_NAME | LAST_NAME | CREATED_DATE |
|---|---|---|---|
| 100 | Alice | Brown | current date |
| 101 | Bob | Green | current date |
- Oracle sequences are fast, standalone counters. They're not tied to any one table by default.
- You can link one to a table with NEXTVAL in an INSERT, a DEFAULT clause on 12c and up, or a trigger on older versions.
- For anything modern,
DEFAULT cust_seq.NEXTVALis the simplest way to get clean, auto-incrementing keys without writing a trigger.
Comments
Post a Comment