9

I'd like to use SEQUENCE support in Apache Derby 10.7. I've created the sequence with the following statement:

CREATE SEQUENCE SAMPLE_SEQ AS INT MAXVALUE 999999 CYCLE;

How can I select next/current value from the SAMPLE_SEQ? Could you please help me out with the query?

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
Tomasz Błachowicz
  • 5,731
  • 9
  • 41
  • 47

6 Answers6

8

Apache Derby Doc says: Use a NEXT VALUE FOR expression

Should be something like

SELECT NEXT VALUE FOR SAMPLE_SEQ;
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
3

Use NEXT VALUE FOR as documented in the manual:

http://db.apache.org/derby/docs/10.7/ref/rrefsqljnextvaluefor.html#rrefsqljnextvaluefor

1

To get the current value of the sequence the following SQL should be executed:

SELECT CURRENTVALUE FROM SYS.SYSSEQUENCES WHERE SEQUENCENAME='SAMPLE_SEQ'
user611544
  • 19
  • 1
  • That is not the current value. – Aseem Bansal Jul 12 '14 at 09:09
  • Querying `SYSSEQUENCES` can cause concurrency issues. Derby provides the built-in system function `SYSCS_UTIL.SYSCS_PEEK_AT_SEQUENCE` to read the next number from the sequence generator; see the [Derby Ref Guide](https://db.apache.org/derby/docs/10.14/ref/rrefsyscspeeksequence.html) and [Derby Tuning Guide](https://db.apache.org/derby/docs/10.14/tuning/ctunperfsequences.html) for details. – MikeOnline Aug 14 '23 at 20:55
0

In the SQL command prompt, you can query the next value with this statement:

values NEXT VALUE FOR <sequence_name>

This will work as an expression embedded into an INSERT statement. E.g.:

INSERT INTO <table_name> (IDFIELD) VALUES (NEXT VALUE FOR <sequence_name>)
sola
  • 1,498
  • 14
  • 23
0

In case you want to fetch the 'current value' from the 'sequence':

  • values ( next value for <sequence> )

Same in Java using JDBC:

ResultSet rs = conn.prepareStatement("values (next value for <sequence>)").executeQuery();
rs.next();
int seqValue = rs.getInt(1);

Source: Derby-user-mailing list archive

ankurrc
  • 1,072
  • 9
  • 12
0

The following SQL returns the next value of a SEQUENCE in Derby:

select next value for SAMPLE_SEQ from (values 1) t

The part "(values 1) t" makes a table with 1 row and 1 column, which then gets substituted with the next value from the sequence. In Oracle you can use the standard DUAL table, and in other databases you can execute SELECT without a table.

Adam Gawne-Cain
  • 1,347
  • 14
  • 14