CYBERTEC PostgreSQL Logo

Sequences – transactional behavior

09.2013 / Category: / Tags: |

In this posting I would like to describe some important aspects of PostgreSQL sequences. In our daily work we have noticed that some people are not fully aware of those implications described in this section.

Database sequences are database objects from which multiple users can generate unique numbers. Unique means that there are no duplicates – it does not mean that you cannot have gaps.

Creating and using sequences

Before we dive head on into transactions we can simply create a sequence:

In the next step we can simply increment the sequence and fetch values:

PostgreSQL will return one value after the other from the sequence:

Taking care of PostgreSQL transactions

The most important thing you have to keep in mind when using sequences is that they provide ascending numbers, BUT those numbers are in no way uninterrupted. Here is an example:

We start a transaction and perform a ROLLBACK. Now, most people would simply assume that the sequence will also do a rollback and continue with 3. This is not the case:

Why is it that way? While a transaction is running, there is no way for the database to know whether the transaction is actually going to commit or not. Just imagine a thousand long running transactions – some of them doing a COMMIT and some of them failing. How would you ever be able to track holes and gaps? This is totally impossible. Therefore it is essential to keep in mind that sequences can indeed produce gaps.

When you are dealing with invoices and accounting, avoiding gaps is especially important. Sequences are no suitable tool to achieving what is needed in this area.

----------
In order to receive regular updates on important changes in PostgreSQL, subscribe to our newsletter, or follow us on Facebook or LinkedIn.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andreas Korth
Andreas Korth
10 years ago

Thanks for the article, Hans-Jürgen. I am currently dealing with invoices and need to generate uninterrupted sequences of numbers. What is, in your experience, the best way to achieve this?

CYBERTEC Logo white
CYBERTEC PostgreSQL International GmbH
Römerstraße 19
2752 Wöllersdorf
Austria

+43 (0) 2622 93022-0
office@cybertec.at

Get the newest PostgreSQL Info & Tools


    This site is protected by reCAPTCHA and the Google Privacy Policy & Terms of Service apply.

    ©
    2024
    CYBERTEC PostgreSQL International GmbH
    phone-handsetmagnifiercrosscross-circle
    linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram