2

I have a django script which loads data, the beginning of the script deletes all datas in database. So when I execute 1st time this script, the auto increment primary keys begin to 1 to 15 (if 15 objects) and if I want to reload data, I reexecute the script. My issue is when I execute it again, pks numbers begin to 16 (for 2nd launch), I would like each time auto_increment begins to 1, is it possible whitout regenerating tables structure each time ?

Thanks

ark
  • 21
  • 2

2 Answers2

3

You could use ALTER TABLE, but I'm not sure that is that much better than just regenerating the schema.

ALTER TABLE table AUTO_INCREMENT = 1;
martin clayton
  • 76,436
  • 32
  • 213
  • 198
2

When you delete rows from the database, you're not really:

  1. Freeing up the disk space

  2. Resetting the auto_increment values as you've noticed.

As such, it might actually be a better idea to drop the table and re-create it as required. Failing that you can use just either:

  1. TRUNCATE <table name>; (Depending on your storage engine, this will actually drop/re-create as mentioned above for you.)

  2. ALTER TABLE <table name> SET AUTO_INCREMENT = X;

Of these, I'd recommend using the truncate approach.

John Parker
  • 54,048
  • 11
  • 129
  • 129
  • Thanks, truncate seems the good solution, but I need to run it with django orm engine. I found this, http://stackoverflow.com/questions/2988997/how-do-i-truncate-table-using-django-orm – ark Jan 15 '11 at 18:10