![magic view bot serial key magic view bot serial key](https://www.artificial-solutions.com/wp-content/uploads/chatbots-the-definitive-guide-pdf.jpg)
Tbl_id being the serial column of table tbl, drawing from the sequence tbl_tbl_id_seq (which is the default automatic name). The shortest and fastest way: SELECT setval('tbl_tbl_id_seq', max(tbl_id)) FROM tbl SELECT setval(pg_get_serial_sequence('t2', 'id'), coalesce(max(id),0) + 1, false) FROM t1 SELECT pg_get_serial_sequence('t2', 'id') - returns 't2_custom_id_seq' SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1 īut if sequences were added manually: CREATE TABLE t2 (ĪLTER TABLE t2 ALTER COLUMN id SET DEFAULT nextval('t2_custom_id_seq'::regclass) ĪLTER SEQUENCE t2_custom_id_seq OWNED BY t2.id - required for pg_get_serial_sequence reset the sequence, regardless whether table has rows or not: SELECT pg_get_serial_sequence('t1', 'id') - returns 't1_id_seq' if serial type was used for table creation, this should all work: CREATE TABLE t1 ( This will be the case if the incrementing column was defined as a serial type, however if the sequence was added manually it is necessary to ensure ALTER SEQUENCE. handles tables with existing data, and does not leave aįinally, note that pg_get_serial_sequence only works if the sequence is owned by the column.avoids hard-coding the actual sequence name.It seems the best all-purpose solution is to call setval with false as the 3rd parameter, allowing us to specify the "next value to use": SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1 ALTER SEQUENCE table_name_id_seq RESTART WITH 1 ĪLTER SEQUENCE table_name_id_seq RESTART - 8.4 or higherīut ALTER SEQUENCE is of limited use because the sequence name and restart value cannot be expressions. One workaround for this is to resort to the ALTER SEQUENCE syntax i.e. However this form can't handle empty tables correctly, since max(id) is null, and neither can you setval 0 because it would be out of range of the sequence. Or more concisely: SELECT pg_tval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name This resets the sequence in one shot: SELECT pg_tval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1) Pg_get_serial_sequence can be used to avoid any incorrect assumptions about the sequence name.