Lastval(): lastval is not yet defined in this session, but it should be!

I’m getting an error lastval(): lastval is not yet defined in this session when I try to call lastval() after inserting to a table that has a serial column. Shouldn’t the serial column define lastval() to the last value it been automatically assigned to?

Or is there something more going on here? One thing I noticed is that using a serial doesn’t automatically create a sequence, so maybe lastval() is only available if we have a sequence? In this case how can I make my serial column use a sequence?

I’ve created an issue for this: lastval(): lastval is not yet defined in this session, but it should be! · Issue #58751 · cockroachdb/cockroach · GitHub

Thank you!

Hi @fiatjaf,

Since CockroachDB has several kinds of serial columns, I’d recommend using the RETURNING id form to avoid having to make a separate call to the DB to retrieve the last sequence value. This will be portable, regardless of your choice of serial, sequence, random id, etc.

Check out our docs on serial here: SERIAL | CockroachDB Docs They will advise you further on how to actually use a sequence if you desire. Though, we recommend not using sequences, since they tend to introduce hotspots!

Cheers,
Jordan

1 Like

Thank you!

I’m mostly using it because I’m trying to make a project that worked with Postgres run on top of Cockroach because of its replication capabilities, but maybe we can rewrite some parts of it to use RETURNING id.

Makes sense. For the record, the RETURNING id syntax works in Postgres too.

1 Like