SQL标准中有TRUNCATE TABLE语句,用来清空表的所有内容。但SQLite不支持这个语句。在SQLite中直接使用“DELETE FROM TableName”就可以了。对于大多数DBMS来说,用DELETE不如用TRUNCATE 速度快,因为TRUNCATE 不用访问整个表,不用记录数据的变动。
SQLite虽然不支持TRUNCATE,但它对DELETE做了优化:“When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This “truncate” optimization makes the delete run much faster.”
通常在清空表的时候,还需要把自增列归零。在SQLite中定义自增列的方法如下:
CREATE TABLE TableName ( id INTEGER PRIMARY KEY AUTOINCREMENT, ... );
当 SQLite数据库中包含自增列时,会自动建立一个名为 sqlite_sequence 的表。这个表包含两个列:name和seq。name记录自增列所在的表,seq记录当前序号(下一条记录的编号就是当前序号加1)。如果想把某个自增列 的序号归零,只需要修改 sqlite_sequence表就可以了。
UPDATE sqlite_sequence SET seq = 0 WHERE name = ‘TableName‘;
也可以直接把该记录删掉:
DELETE FROM sqlite_sequence WHERE name = ‘TableName‘;
要想将所有表的自增列都归零,直接清空sqlite_sequence表就可以了:
DELETE FROM sqlite_sequence;
使用drop语句删除一个表,然后重新创建表,表的主键也会重新生成。
drop table tablename
欢迎扫描二维码,关注公众号