Thread: currval(seq) fails if no nextval(seq) first

currval(seq) fails if no nextval(seq) first

From
Louis-David Mitterrand
Date:
Hello,

I am trying to select the most recently inserted row in a table by
matching the id column with the current value of the sequence that
generated the id (I know this is not the best way to do it, because the
sequence might have holes in it). By the way what is the canonical way
of selecting the most recently inserted row in a table?

The strange thing is that currval() fails until nextval() is called on
the sequence. Is this normal?

Thanks in advance,

auction=# SELECT * FROM auction* WHERE login = 'vindex' AND id = currval('auction_id_seq');
ERROR:  auction_id_seq.currval is not yet defined in this session
auction=# select nextval('auction_id_seq');
 nextval
---------
      67
(1 row)

auction=# SELECT * FROM auction* WHERE login = 'vindex' AND id = currval('auction_id_seq');
 id | login | startdate | stopdate | description | startprice | reserveprice | category | imageurl | title | quantity |
created| modified | option | auto_renew | renew_count | private | dutch | accept_visa | accept_amex | accept_cheque |
accept_bank_transfer| accept_bank_cheque | ship_international | buyer_pays_shipping | currency  

----+-------+-----------+----------+-------------+------------+--------------+----------+----------+-------+----------+---------+----------+--------+------------+-------------+---------+-------+-------------+-------------+---------------+----------------------+--------------------+--------------------+---------------------+----------
(0 rows)

--
Louis-David Mitterrand - ldm@apartia.org - http://www.apartia.fr

Radioactive cats have 18 half-lives.