<<<<<<< HEAD nextval | H2 | SQLDoc
Skip to main content

nextval

1. NEXTVAL Function

======= nextval | H2 Function | SQLDoc

nextval

1. NEXTVAL Function

>>>>>>> 9d19b1c8cb744c8e86d5c15b74d8b5f719ad62be

The NEXTVAL function in H2 database is used to retrieve the next value from a sequence.

2. Syntax

The syntax for the NEXTVAL function in H2 database is as follows:

NEXTVAL(sequence_name)

Arguments

  • sequence_name: The name of the sequence from which the next value needs to be retrieved. It should be a valid sequence name.

Return

  • The NEXTVAL function returns the next value from the specified sequence.

3. Notes

  • The NEXTVAL function in H2 database is typically used in conjunction with sequences to generate unique identifiers or primary keys for tables.
  • If the specified sequence does not exist, an error will be thrown.
  • The NEXTVAL function automatically increments the sequence value by 1.
  • The returned value is of the same datatype as the sequence.

4. Examples

Here are a few examples demonstrating the usage of the NEXTVAL function in H2 database:

Example 1 - Retrieving the next value from a sequence:

CREATE SEQUENCE seq START WITH 1;

SELECT NEXTVAL('seq') AS next_value;

Output:

next_value
----------
1

Example 2 - Using NEXTVAL to generate primary keys:

CREATE TABLE employees (
id INT PRIMARY KEY DEFAULT NEXTVAL('seq'),
name VARCHAR(50),
age INT
);

INSERT INTO employees (name, age) VALUES ('John Doe', 30), ('Jane Smith', 25);

SELECT * FROM employees;

Output:

id |    name    | age
---+------------+-----
1 | John Doe | 30
2 | Jane Smith | 25
  • currval - Retrieve the current value from a sequence
  • SETVAL - Set the value of a sequence