4 Simple Steps to Emulating Real Sequences in MySQL
Submitted by intellicon on Tuesday, July 9, 2013 - 00:24.
If all you want to do is create a unique ID for a record, the auto_increment feature in MySQL will do the job nicely. Sometimes, however, you need more functionality. Unfortunately, unlike Oracle or PostgreSQL, MySQL doesn't have native support for the nextval() function, so creating real sequences is a little more challenging.
First, we need to define what we want the nextval() function to achieve. We want to be able to begin the sequence with any number, and auto increment in multiples of any number, not just 1, including negative integers (-1 for example). We would also like the ability to define a maximum or minimum value, and have the sequence reset itself when that parameter is reached. Finally, we have to be able to determine the next number in the sequence.
1. Create the table. First things first. Before we can implement a sequence, we first need to create the table.
2. Insert the values. Now we define the parameters of the sequence, and specify its values. In this example, we're cycling down from 100 to 0 with step 2.
3. Define nextval(). Finally, we create the nextval() function to determine the next number in the sequence, and to reset the counter when the minimum value is exceeded.
4. Accessing the sequence. For our countdown sequence to be useful, we need to be able to call the function and extract the values from the sequence. Here's how:
- CREATE TABLE `sequence` (
- `name` VARCHAR(100) NOT NULL,
- `increment` INT(11) NOT NULL DEFAULT 1,
- `min_value` INT(11) NOT NULL DEFAULT 1,
- `max_value` BIGINT(20) NOT NULL DEFAULT 9223372036854775807,
- `cur_value` BIGINT(20) DEFAULT 1,
- `cycle` BOOLEAN NOT NULL DEFAULT FALSE,
- PRIMARY KEY (`name`)
- ) ENGINE=MyISAM;
- INSERT INTO SEQUENCE
- ( name, INCREMENT, min_value, max_value, cur_value )
- VALUES
- ('my_sequence', -2, 0, 100, 100, 1);
- DELIMITER $$
- CREATE FUNCTION `nextval` (`seq_name` VARCHAR(100))
- RETURNS BIGINT NOT DETERMINISTIC
- BEGIN
- DECLARE cur_val BIGINT;
- SELECT
- cur_value INTO cur_val
- FROM
- SEQUENCE
- WHERE
- name = seq_name;
- IF cur_val IS NOT NULL THEN
- UPDATE
- SEQUENCE
- SET
- cur_value = IF (
- (cur_value + INCREMENT) > max_value OR (cur_value + INCREMENT) < min_value,
- IF (
- cycle = TRUE,
- IF (
- (cur_value + INCREMENT) > max_value,
- min_value,
- max_value
- ),
- NULL
- ),
- cur_value + INCREMENT
- )
- WHERE
- name = seq_name;
- END IF;
- RETURN cur_val;
- END;
- $$
SELECT NEXTVAL('my_sequence');
So there you have it. Four simple steps to create a real sequence in MySQL for use in your databases. For more tips and tricks to help you make the most of MySQL and other popular databases, visit: http://www.convert-in.com/articles.htmAdd new comment
- 77 views