Re: using the nextval('sequence_name') in sql, the result maybe is not right

From: Alban Hertroys <haramrae(at)gmail(dot)com>
To: jluwln(at)163(dot)com
Cc: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: using the nextval('sequence_name') in sql, the result maybe is not right
Date: 2018-09-26 13:18:10
Message-ID: CAF-3MvORo-dgX6hv4O_ctmN9YPy6hvPx8Xi9iEbto6icBdkDiQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, 26 Sep 2018 at 14:08, Wanglin <jluwln(at)163(dot)com> wrote:
>
> Hi, all:
> PostgreSQL version : 10.3. I use "nextval" in the sql , but I think the result is not right, maybe it is a bug.
> The test case as bellow:
> create sequence seq1;
> select nextval('seq1');
> create table tx1(id1 int, id2 int);
> insert into tx1 select generate_series(1,100), random()*102;
> explain verbose select * from tx1 where id2 = nextval('seq1');;
> select * from tx1 where id2 = nextval('seq1');
> postgres=# explain verbose select * from tx1 where id2 = nextval('seq1');; QUERY PLAN ------------------------------------------------------------ Seq Scan on public.tx1 (cost=0.00..43.90 rows=11 width=8) Output: id1, id2 Filter: (tx1.id2 = nextval('seq1'::regclass)) (3 rows)
>
> postgres=# select * from tx1 where id2 = nextval('seq1'); -- here, may be the result is not right id1 | id2 -----+----- 56 | 57 (1 row)
>
> :: I think "nextval('seq1')" equal 2, so " select * from tx1 where id2 = nextval('seq1')" equals " select * from tx1 where id2 = 2", is it ?

No. nextval("seq1") increments the sequence and returns the new value.
It never[*] returns the same value in subsequent calls, that is the
purpose of the function (and sequences in general).

Normally, you would assign a sequence to a surrogate key field in your
table, so that you automatically get unique values in that field
(unless you mess around).
That's not how you're using it, so I wonder what your purpose is for
the sequence?

[*] Never is never without exceptions, just like always always has.
--
If you can't see the forest for the trees,
Cut the trees and you'll see there is no forest.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2018-09-26 13:35:26 Re: using the nextval('sequence_name') in sql, the result maybe is not right
Previous Message Wanglin 2018-09-26 12:05:19 using the nextval('sequence_name') in sql, the result maybe is not right