Oracle Sequences π’ΒΆ
Prerequisites: Table Management
Mentor's Note: Before Identity Columns existed (Pre-12c), Sequences were the only way to get "Auto-incrementing" IDs in Oracle. They are still powerful today because a single sequence can be shared across many tables! π‘
π The Scenario: The Token Machine ποΈΒΆ
Imagine a machine that prints tokens (1, 2, 3...). - The machine doesn't care who takes the token. - Once a token is taken, it's gone. - A Sequence is that token machine for your database.
π» 1. CREATE SEQUENCEΒΆ
π» 2. Using the Sequence (NEXTVAL) π οΈΒΆ
To get the next number, we use .NEXTVAL.
ποΈ Architect's Note: Cache Performance π‘οΈΒΆ
Sequences have a CACHE option (e.g., CACHE 20).
- The Architect's Secret: If you use CACHE, Oracle pre-generates numbers and keeps them in memory. This is extremely fast for high-concurrency apps.
- The Warning: If the database crashes, the cached numbers are lost. You will see a "gap" in your IDs (e.g., 1, 2, 21, 22).
- Architecture Tip: For most business apps, gaps are fine. Use CACHE for performance!