DEV Community

Pranav Bakare
Pranav Bakare

Posted on

How Sequences used in Oracle SQL without AUTO_INCREMENT Keyword

AUTO_INCREMENT in MySQL and Sequence in Oracle SQL

In Oracle SQL, there is no AUTO_INCREMENT keyword like in MySQL. This is because Oracle handles auto-increment functionality differently using sequences and optionally triggers. While MySQL has the AUTO_INCREMENT keyword to automatically generate unique numeric values, Oracle relies on the flexibility of sequences to achieve the same outcome.


Why Oracle Doesn't Use AUTO_INCREMENT

Oracle focuses on database objects like sequences to provide more granular control over value generation.

Using sequences, you can:

  • Set custom starting values.
  • Define the increment step.
  • Manage caching or cycling of values.
  • This makes sequences more versatile than the fixed AUTO_INCREMENT approach.

How Oracle Implements Auto-Increment Without AUTO_INCREMENT

Instead of using an AUTO_INCREMENT keyword, Oracle uses the following steps:

1. Create a Sequence: Defines how unique values are generated.

CREATE SEQUENCE my_table_seq
START WITH 1 INCREMENT BY 1 NOCYCLE;
Enter fullscreen mode Exit fullscreen mode

2. Use a Trigger (Optional): Automates the assignment of sequence values to a column.

CREATE OR REPLACE TRIGGER my_table_trigger
BEFORE INSERT ON my_table
FOR EACH ROW
BEGIN
  :NEW.id := my_table_seq.NEXTVAL;
END;
/
Enter fullscreen mode Exit fullscreen mode

3. Direct Sequence Usage: Insert rows by explicitly calling the sequence.

INSERT INTO my_table (id, column1) VALUES (my_table_seq.NEXTVAL, 'value1');
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

  • The AUTO_INCREMENT keyword does not exist in Oracle SQL. Instead:
  • Use sequences to generate unique identifiers.
  • Optionally, automate this with triggers for convenience.

This approach provides flexibility while achieving functionality similar to AUTO_INCREMENT.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry ๐Ÿ‘€

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more โ†’

Top comments (1)

Collapse
 
databasesponge profile image
MetaDave ๐Ÿ‡ช๐Ÿ‡บ โ€ข

Since Oracle 12C, released in 2014, a sequence can be specified as the default value for a column. I doubt anyone is writing new code with triggers to add sequence values.

12C also introduced identity columns: NUMBER GENERATED ALWAYS AS IDENTITY, which use sequences behind the scenes.

oracle-base.com/articles/12c/ident...

Sentry image

See why 4M developers consider Sentry, โ€œnot bad.โ€

Fixing code doesnโ€™t have to be the worst part of your day. Learn how Sentry can help.

Learn more