How do you use the SEQUENCE object to generate unique numbers?
Posted by MaryJns
Last Updated: July 17, 2024
In many SQL databases, the SEQUENCE object is used to generate unique numbers automatically, often to provide a unique identifier for rows in a table. Here's a general overview of how to use a SEQUENCE object to generate unique numbers:
Creating a SEQUENCE
To create a SEQUENCE, you'll use the CREATE SEQUENCE statement. Here’s an example:
CREATE SEQUENCE my_sequence
    START WITH 1    -- Starting value
    INCREMENT BY 1  -- Increment value
    MINVALUE 1      -- Minimum value
    MAXVALUE 10000  -- Maximum value
    CACHE 10        -- Amount of values to cache for performance
    CYCLE;          -- Optionally allow the sequence to restart when maximum is reached
Using a SEQUENCE
Once you have created a SEQUENCE, you can use it to generate unique numbers in your SQL operations. The most common ways to use a SEQUENCE are through the NEXTVAL and CURRVAL functions. 1. Getting the Next Value: You can call the NEXTVAL function to get the next value from the SEQUENCE:
SELECT NEXTVAL(my_sequence) AS unique_number;
An example of using it when inserting data into a table:
INSERT INTO your_table (id, other_column)
   VALUES (NEXTVAL(my_sequence), 'some_value');
2. Getting the Current Value: You can call the CURRVAL function to get the current value of the SEQUENCE after a NEXTVAL has been called during the session:
SELECT CURRVAL(my_sequence) AS current_number;
Considerations
- Concurrency: SEQUENCE objects are typically designed to be thread-safe and can handle multiple concurrent requests without generating duplicate values. - Performance: Caching can improve performance by reducing the number of times the database needs to access the SEQUENCE. - Cycle Option: If you choose to allow cycling, be aware that the sequence will restart when it reaches the maximum value.
Example
Here’s a full example of creating a SEQUENCE and using it to insert records into a table:
-- Create a table
CREATE TABLE my_table (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

-- Create a sequence
CREATE SEQUENCE my_sequence
    START WITH 1
    INCREMENT BY 1;

-- Insert data using the sequence
INSERT INTO my_table (id, name) VALUES (NEXTVAL(my_sequence), 'Alice');
INSERT INTO my_table (id, name) VALUES (NEXTVAL(my_sequence), 'Bob');

-- Query the table
SELECT * FROM my_table;
In this example, the id column will automatically have unique values for each row based on the SEQUENCE.