IBM DB2 Sequence Usage Guide | Generated by AI
IBM DB2 Sequence Usage with NEXT VALUE FOR
In IBM DB2, NEXT VALUE FOR is used to retrieve the next value from a sequence, which generates unique, incrementing numbers. Sequences are useful for generating primary keys or other unique identifiers.
Example: Creating and Using a Sequence
- Create the sequence (run this once in your DB2 environment):
CREATE SEQUENCE my_sequence START WITH 1 INCREMENT BY 1 NO CYCLE;- This creates a sequence named
my_sequencestarting at 1, incrementing by 1 each time.
- This creates a sequence named
- Use the sequence in an INSERT statement to get the next value:
INSERT INTO employees (id, name, department) VALUES (NEXT VALUE FOR my_sequence, 'Alice Johnson', 'Engineering');- This inserts a new row with
idas the next sequence value (e.g., 1 for the first use, 2 for the next, etc.).
- This inserts a new row with
Key Notes
- You can also use it in SELECT queries:
SELECT NEXT VALUE FOR my_sequence FROM SYSIBM.SYSDUMMY1; - Sequences are separate from tables and can be shared across multiple tables if needed.
- For more details, refer to the IBM DB2 documentation on sequences. If you need examples for other sequence functions like
PREVIOUS VALUE FOR, let me know!