Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Chandrababu.

Asked: May 13, 2025 - 3:29 pm UTC

Last updated: May 19, 2025 - 7:44 am UTC

Version: MySQL 8.0.22

Viewed 100+ times

You Asked

With row‑based replication (binlog_format = ROW), the function generates duplicate sequence values; in mixed mode (binlog_format = MIXED), no duplicates occur. Using AWS RDS 8.0.22


CREATE DEFINER=abc@% FUNCTION nextval(seq_name varchar(100)) RETURNS bigint
BEGIN
DECLARE cur_val bigint(20);
SELECT
sequence_cur_value INTO cur_val
FROM

sequence_data

WHERE
sequence_name = seq_name
;

IF cur_val IS NOT NULL THEN
UPDATE
sequence_data
SET
sequence_cur_value = IF (
(sequence_cur_value + sequence_increment) > sequence_max_value,
IF (
sequence_cycle = TRUE,
sequence_min_value,
NULL
),
sequence_cur_value + sequence_increment
)
WHERE
sequence_name = seq_name
;

END IF;

RETURN cur_val;

and Connor said...

I don't know MySQL but I'd be willing to bet its read consistency here, eg assuming an increment of 1 with time going down the page

      Session 1            Session 2

     read seq
     - gets 20
     
     updates seq
     - sets to 21

                           read seq
                           - gets 20
                           (because we dont
                            see the update 
                            in session 1 until
                            it commits)

     commits;                            

                           updates seq
                           - sets to 21

                          commits;                            
 
     


MySQL has a native SEQUENCE type to handle this.