0

I have a Postgres database with many tables. I want to declare a function that reset all auto_increment values (next_value) of all the tables to max(id) of the table. For example, if max(id) of sample_table is 22:

postgres=# SELECT MAX(id) + 1 FROM sample_table;
 ?column? 
----------
       22
(1 row)

While next_value of the table is 7:

postgres=# SELECT nextval('"public"."sentry_project_id_seq"'::regclass);
 nextval 
---------
       7
(1 row)

I want to set the next_value of all the tables to their max(id) by:

SELECT setval('auth_user_id_seq', (SELECT MAX(id) from "auth_user"));

To do this, I declare a function called reset_auto_increment by:

CREATE OR REPLACE FUNCTION reset_auto_increment(username IN VARCHAR) RETURNS void AS $$
DECLARE
        statements CURSOR FOR
            SELECT tablename FROM pg_tables
            WHERE tableowner = username AND schemaname = 'public';
    BEGIN
        FOR stmt IN statements LOOP
            EXECUTE 'SELECT setval(' || concat(stmt.tablename, '_id_seq') || ' , (SELECT MAX(id) from ' || quote_ident(stmt.tablename) || '));';
        END LOOP;
    END;
$$ LANGUAGE plpgsql;

But the function declared by the statement above has error below:

postgres=# select reset_auto_increment('postgres');
**ERROR:  column "_id_seq" does not exist**
LINE 1: SELECT 'SELECT setval(' || concat(stmt.tablename, "_id_seq")...
                                                          ^
QUERY:  SELECT 'SELECT setval(' || concat(stmt.tablename, "_id_seq") || ' , (SELECT MAX(id) from ' || quote_ident(stmt.tablename) || '));'
CONTEXT:  PL/pgSQL function reset_auto_increment(character varying) line 8 at EXECUTE

How to correct this function?

Mohsen Abasi
  • 1,179
  • 15
  • 25
  • The error message and the function code you showed aren't related. `SELECT 'SELECT setval(' || concat(stmt.tablename, "_id_seq")...` isn't anywhere in the code. – sticky bit Dec 19 '20 at 06:16
  • 1
    There are several solutions that you can use [here](https://stackoverflow.com/questions/244243/) or [here](https://stackoverflow.com/questions/62059947/) – a_horse_with_no_name Dec 19 '20 at 08:10

0 Answers0