Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence does not reset after truncating the table

I use SELECT lastval() to get wrong serial id after truncated the table.

when I truncate the table, I use SELECT lastval(), I got the wrong ID/

like image 237
user1369887 Avatar asked Dec 21 '12 11:12

user1369887


People also ask

Does truncate table reset sequence?

If specified, all sequences on the truncated tables will be continue and not be reset. This is the default behavior. Optional.

What will happen after truncate a table?

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. To remove the table definition in addition to its data, use the DROP TABLE statement.

Does truncate table reset indexes?

The truncate command only removes all rows of a table. It does not remove the columns, indexes, constraints, and schema.


2 Answers

Following is the standard way to reset sequence:

truncate table table_name restart identity; 

but in some version & platform, it's syntax error,

in that case, you can truncate without reset sequence, and alter the sequence with another sql, try this:

truncate table table_name; alter sequence seq_name start 1; 
like image 20
user218867 Avatar answered Oct 14 '22 13:10

user218867


Use the TRUNCATE SQL command.

For a single table the syntax is the following:

TRUNCATE TABLE table_name RESTART IDENTITY; 

For multiple tables:

TRUNCATE TABLE table_foo, table_bar RESTART IDENTITY; 

What it does:

Automatically restart sequences owned by columns of the truncated table(s).

Details here: TRUNCATE @ postgresql.org

like image 160
Ihor Romanchenko Avatar answered Oct 14 '22 13:10

Ihor Romanchenko