views:

2059

answers:

4

What is the command to drop all tables in SQLite?

Similarly I'd like to drop all indexes.

+7  A: 

I don't think you can drop all tables in one hit but you can do the following to get the commands:

select 'drop table ' || name || ';' from sqlite_master
    where type = 'table';

The output of this is a script that will drop the tables for you. For indexes, just replace table with index.

You can use other clauses in the where section to limit which tables or indexes are selected (such as "and name glob 'pax_*'" for those starting with "pax_").

You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.

If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see wht it wouldn't work.

paxdiablo
Thanks. Very strange that there's no simple command but instead this hacky SQL query.
alamodey
Well, the easiest way to get an empty sqlite database is just to delete the file, and then connect to it..
John Fouhy
Hence my final paragraph, @JF.
paxdiablo
+2  A: 

Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).

So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.

Mike Woodhouse
The file doesn't shrink because that's not the way sqlite works - it'll only return disk space to the OS if you vacuum the file (basically recreate it from scratch). Until then, the file is full of reusable space.
paxdiablo
Yah. So dropping all tables and vacuuming would make sense if you didn't have file delete/create privileges, or there was some strange multi-user situation. Otherwise just delete the thing?
Mike Woodhouse
+5  A: 
rm db/development.sqlite3
alamodey
yes, this does delete the database, but there can be other thing in sqlite besides tables; See my full answer for details
Noah
+4  A: 

You can do it with the following DANGEROUS commands:

PRAGMA writable_schema = 1;
delete from sqlite_master where type = 'table';
PRAGMA writable_schema = 0;

you then want to recover the deleted space with

VACUUM

and a good test to make sure everything is ok

PRAGMA INTEGRITY_CHECK;
Noah
+1 - Clever....
sheepsimulator