• Home
  • SQL Sequences – Syntax and Use

SQL Sequences – Syntax and Use

SQL sequences are a type of database object or data structure that is used to generate a sequence of unique integers in a database management system (DBMS). SQL sequences are typically used to generate a sequence of unique numbers or values that can be used as primary keys or identifiers for rows or records in a database table.

SQL sequences are created using the CREATE SEQUENCE statement, and they can be used in SQL queries or statements using the NEXT VALUE FOR function. Here is an example of how to create and use an SQL sequence in a database:

-- Create an SQL sequence called 'employee_id_seq'
CREATE SEQUENCE employee_id_seq
START WITH 1 -- The first value generated by the sequence
INCREMENT BY 1 -- The amount by which the sequence is incremented
MINVALUE 1 -- The minimum value that the sequence can generate
MAXVALUE 99999 -- The maximum value that the sequence can generate
CYCLE -- Specifies that the sequence should start over when it reaches the maximum value
;

-- Insert a new row into the 'employees' table, using the next value from the 'employee_id_seq' sequence
INSERT INTO employees (id, name, salary)
VALUES (NEXT VALUE FOR employee_id_seq, 'John Smith', 10000);

-- Insert another row into the 'employees' table, using the next value from the 'employee_id_seq' sequence
INSERT INTO employees (id, name, salary)
VALUES (NEXT VALUE FOR employee_id_seq, 'Jane Doe', 12000);

-- Select all rows from the 'employees' table, ordered by the 'id' column
SELECT * FROM employees ORDER BY id;

The above SQL code will create an SQL sequence called ’employee_id_seq’ that generates a sequence of unique integers starting from 1, and that increments by 1 for each new value. The sequence will have a minimum value of 1 and a maximum value of 99999, and it will cycle back to the minimum value when it reaches the maximum value. The SQL code will then insert two new rows into the ’employees’ table, using the next value from the ’employee_id_seq’ sequence as the value for the ‘id’ column. Finally, the SQL code will select all rows from the ’employees’ table, ordered by the ‘id’ column.

SQL sequences are a useful and convenient way to generate a sequence of unique integers in a database, and they are commonly used as primary keys or identifiers for rows or records in a database table. SQL sequences are created using the CREATE SEQUENCE statement, and they can be used in SQL queries or statements using the NEXT VALUE FOR function.