[Fixed]-Django Max Function not returning Maximum Value

1👍

The PostgreSQL serial datatype internally creates both a smallint/int/bigint column and a sequence. Effectively making it equivalent to a normal int column with a default set to some sequence.

For example, this:

CREATE TABLE tablename (
    colname SERIAL
);

Internally results in this:

CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

This is where your question comes in, while a plain CREATE SEQUENCE just adds a simple sequence that increments by one and will never go down. Using setval you can reset the sequence current value to reuse old numbers.

Do note that this can result in duplicate key constraints since the primary key will still be unique so if you do get duplicate key constraints, simply reset the sequence to a range that isn’t in use yet (SELECT MAX(colname)+1 FROM tablename should give you a correct startpoint).

👤Wolph

Leave a comment