views:

193

answers:

3

I am using SQLite3. I load a table with say 30 rows using integer as Primary ID and it auto-increments.

Now I delete all the rows from the table and then, reload some new information onto the table.

Problem is: the row count (my PrimaryID) now starts with 31. Is there any way that I can start loading new rows from the number 1 onwards?

Thanks! - Maddy

A: 

For MySQL:

Use TRUNCATE TABLE tablename to empty the table (delete all records) and reset auto increment count.

You can also use ALTER TABLE tablename AUTO_INCREMENT = 0; if you just want to reset the count.

For SQLite:

DELETE FROM tablename;
DELETE FROM SQLITE_SEQUENCE WHERE name='tablename';

References

SQLite AutoIncrement
MySQL AutoIncrement

quantumSoup
Setting the auto_increment to zero on MySQL doesn't reset the value to one; it adopts the next highest value based on the existing ones.
OMG Ponies
A: 
ALTER TABLE tbl AUTO_INCREMENT = 0;
websch01ar
A: 

SQLite

Use:

DELETE FROM your_table;    
DELETE FROM sqlite_sequence WHERE name = 'your_table';

Documentation

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

Found the answer on SO: http://stackoverflow.com/questions/1601697/sqlite-reset-primary-key-field

MySQL

Use:

ALTER TABLE tbl AUTO_INCREMENT = 1;

In either case, the database doesn't care if the id numbers are sequencial - only that the values are unique. If users never see the primary key value (they shouldn't, because the data can change & won't always be at that primary key value), I wouldn't bother with these options.

OMG Ponies
If you do `AUTO_INCREMENT = 0` will the first record inserted start with `id` of 0 or 1?
JohnB
@JohnB It'll start from 1
quantumSoup
@JohnB: Thx, the value needs to be one to reset on my 5.1.35 - I updated my answer. Setting it to zero doesn't return an error - the sequence is unchanged.
OMG Ponies
@quantomSoup: See comment to JohnB
OMG Ponies