简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM