๐Ÿ” MySQL Sequences & Auto Increment โ€“ Generating Unique IDs in MySQL


๐Ÿงฒ Introduction โ€“ Why Use Sequences and Auto-Increment?

In relational databases, every record often needs a unique identifierโ€”for referencing, indexing, and joining. In MySQL:

  • ๐Ÿ”ข AUTO_INCREMENT generates a monotonically increasing value
  • ๐Ÿ” MySQL lacks native SEQUENCE objects (like Oracle or PostgreSQL) but provides workarounds
  • ๐Ÿงญ These tools are essential for creating primary keys, invoice numbers, order IDs, and more

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How AUTO_INCREMENT works in MySQL
  • How to simulate sequences
  • Use cases, best practices, and caveats
  • Alternatives using stored procedures or custom tables

๐Ÿ”ข 1. AUTO_INCREMENT โ€“ Native Way to Generate IDs

๐Ÿ”น Syntax

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(100)
);

๐Ÿ”น Example โ€“ Insert Rows

INSERT INTO users (username) VALUES ('alice');
INSERT INTO users (username) VALUES ('bob');

โœ… id will be auto-assigned as 1, 2, 3…


๐Ÿ”น Retrieve Last Generated ID

SELECT LAST_INSERT_ID();

โœ… Returns the last auto-incremented ID for the current session.


๐Ÿ”น Customize Starting Value

ALTER TABLE users AUTO_INCREMENT = 1000;

โœ… Useful for starting from a specific offset (e.g., ORD-1000).


โš ๏ธ AUTO_INCREMENT Caveats

BehaviorDescription
Skips on failed insertsFailed transactions still increment the counter
Not rolled back on ROLLBACKValues are consumed even on rollback
Gaps between valuesNormal and expected (no guarantees on sequence)

๐Ÿ” 2. Simulating Sequences in MySQL

MySQL doesn’t support CREATE SEQUENCE, but you can simulate it using a custom table or stored procedure.


๐Ÿ”น A. Sequence Table Workaround

CREATE TABLE sequence (
  name VARCHAR(50) PRIMARY KEY,
  current_value BIGINT
);

INSERT INTO sequence VALUES ('invoice', 1000);

๐Ÿ”น Fetch Next Value

UPDATE sequence SET current_value = current_value + 1 WHERE name = 'invoice';
SELECT current_value FROM sequence WHERE name = 'invoice';

โœ… Use inside a stored procedure for controlled ID generation.


๐Ÿ”น B. Custom Stored Procedure Sequence

DELIMITER //

CREATE PROCEDURE get_next_invoice_id(OUT next_id INT)
BEGIN
  UPDATE sequence SET current_value = current_value + 1 WHERE name = 'invoice';
  SELECT current_value INTO next_id FROM sequence WHERE name = 'invoice';
END //

DELIMITER ;

Call Example:

CALL get_next_invoice_id(@next);
SELECT @next;

๐Ÿ”€ 3. AUTO_INCREMENT vs SEQUENCE Table โ€“ Comparison

FeatureAUTO_INCREMENTSimulated SEQUENCE Table
Native Supportโœ… YesโŒ Requires manual setup
Rollback FriendlyโŒ Noโœ… Yes (if wrapped in transaction)
Multi-purpose UseโŒ One column per tableโœ… Reusable across tables
Custom logicโŒ Limitedโœ… Supports custom increments
Gaps on failureโœ… YesโŒ Can avoid if coded properly

๐Ÿ“˜ Best Practices

โœ… Tip๐Ÿ’ก Why It Matters
Use AUTO_INCREMENT for single-column IDsSimple and efficient for most tables
Use SEQUENCE logic for multi-table countersEnsures shared counters (e.g., invoice numbering)
Always retrieve LAST_INSERT_ID() in same sessionPrevents confusion when multiple inserts occur
Avoid assuming no gapsGaps are expected in both auto-increment and sequences
Use transactions with sequence logicPrevents race conditions and duplicates

๐Ÿš€ Real-World Use Cases

ScenarioGenerator UsedWhy
User ID assignmentAUTO_INCREMENTEach user gets a unique integer ID
Order or invoice numberingSEQUENCE TableShared, customized across modules
External reference IDsStored Function or UUID()Unique IDs for APIs or cross-systems
Ticket numbersAUTO_INCREMENTSimple, fast auto-numbering

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

MySQL supports AUTO_INCREMENT for table-specific counters and allows custom sequence logic via manual tables and stored routines for more control.

๐Ÿ” Key Takeaways

  • Use AUTO_INCREMENT for simple primary key generation
  • Use LAST_INSERT_ID() to retrieve the new value after insert
  • Simulate sequences using a control table or stored procedure
  • Gaps are normalโ€”donโ€™t rely on strict numeric continuity
  • Use transactions when manually managing sequence values

โš™๏ธ Real-World Relevance

Used in accounting systems, order processing, inventory control, and ticketing platforms where ID generation and integrity are essential.


โ“ FAQ โ€“ MySQL Sequences & Auto Increment


โ“ Does MySQL support the CREATE SEQUENCE statement?

โŒ No. MySQL (even 8.0+) doesn’t support native SEQUENCE objects like PostgreSQL.


โ“ Can I reset an auto-increment column?

โœ… Yes:

ALTER TABLE users AUTO_INCREMENT = 1;

Or, truncate the table:

TRUNCATE TABLE users;

โ“ How do I get the ID generated in a multi-user environment?

Use:

SELECT LAST_INSERT_ID();

It returns the correct value per session.


โ“ Can two tables share the same auto-increment sequence?

โŒ Not with AUTO_INCREMENT, but โœ… possible with a shared sequence table.


โ“ Can I create a sequence that increments by 10?

โœ… Yes, manually:

UPDATE sequence SET current_value = current_value + 10 WHERE name = 'receipt';

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ” MySQL Sequences & Auto Increment

Or Copy Link

CONTENTS
Scroll to Top