Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails seed: How to truncate DB table?

Before seeding test data into DB table I need to truncate the table (I need to reset primary key), I am trying to do that this way:

ActiveRecord::Base.connection.execute("TRUNCATE users")

but when I print out data from DB, I still don't see counting primary key from 1.

What am I doing wrong?

EDIT:

Also, I've tried manually run in terminal to PostgreSQL database

truncate users

But the primary count still doesn't start from 1.

SOLUTION:

In Postgres, run:

ALTER SEQUENCE users_id_seq RESTART WITH 1;
like image 805
user984621 Avatar asked Feb 26 '13 21:02

user984621


1 Answers

In MySQL, TRUNCATE table; deletes all rows and resets the auto increment counter.

In PostgreSQL it does not do this automatically. You can use TRUNCATE TABLE table RESTART IDENTITY;.

Just for the record: In SQLite, there is no TRUNCATE statement, instead, it's

DELETE FROM table;
DELETE FROM sqlite_sequence WHERE name='table';
like image 121
iblue Avatar answered Nov 02 '22 23:11

iblue