1

I have a question about a problem that I'm sure is pretty often, but I still couldn't find any satisfying answers. Suppose I have a huge-size original SQLite database. Now, I want to create an empty database that is initialized with all the tables, columns, and primary/foreign keys but has no rows in the tables. Basically, I want to create an empty table using the original one as a template.

The "DELETE from {table_name}" query for every table in the initial database won't do it because the resulting empty database ends up having a very large size, just like the original one. As I understand it, this is because all the logs about the deleted rows are still being stored. Also, I don't know exactly what else is being stored in the original SQLite file, I believe it may store some other logs/garbage things that I don't need, so I would prefer just creating an empty one from scratch if it is possible. FWIW, I eventually need to do it inside a Python script with sqlite3 library.

Would anyone please provide me with an example of how this can be done? A set of SQLite queries or a python script that would do the job?

3
  • 1
    probably you can vacuum to get the filesize back to a normal/expected amount: sqlite.org/lang_vacuum.html Commented Jan 22, 2022 at 23:51
  • 3
    that can be done from Python as shown here: stackoverflow.com/a/4713249/42346 Commented Jan 22, 2022 at 23:52
  • @mechanical_meat Thank you! I tried to use it before but did that in the wrong way. Turns out that after DELETE-ing tables, you have to execute connection.commit() first before VACUUM-ing, otherwise it leads to OperationalError. After this change, that worked out for me perfectly. Commented Jan 23, 2022 at 14:10

1 Answer 1

4

You can use Command Line Shell For SQLite

sqlite3 old.db .schema | sqlite3 new.db
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.