user10285265
user10285265

Reputation:

pg_get_serial_sequence in postgres fails and returns misleading error

This is not obviuos to me.

When I do:

SELECT MAX("SequenceNumber") FROM "TrackingEvent";

It returns perfectly fine with the correct result

When I do:

SELECT nextval(pg_get_serial_sequence("TrackingEvent", "SequenceNumber")) AS NextId

It returns an error which says

column "TrackingEvent" does not exist.

Not only is it wrong but the first argument of the function pg_get_serial_sequence takes a table name and not a column name, so the error is aslo misleading.

Anyways, can someone explain to me why I get an error on the pg_get_serial_sequence function ?

Upvotes: 0

Views: 1608

Answers (1)

user330315
user330315

Reputation:

pg_get_serial_sequence() expects a string as its argument, not an identifier. String constants are written with single quotes in SQL, "TrackingEvent" is an identifier, 'TrackingEvent' is a string constant.

But because the function converts the string constant to an identifier, you need to include the double quotes as part of the string constant. This however only applies to the table name, not the column name, as explained in the manual

Because the first parameter is potentially a schema and table, it is not treated as a double-quoted identifier, meaning it is lower cased by default, while the second parameter, being just a column name, is treated as double-quoted and has its case preserved.

So you need to use:

SELECT nextval(pg_get_serial_sequence('"TrackingEvent"', 'SequenceNumber'))

This is another good example why using quoted identifiers is a bad idea. You should rename "TrackingEvent" to tracking_event and "SequenceNumber" to sequence_number

Upvotes: 5

Related Questions