Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy table structure to new table in sqlite3

Is there an easy way to copy an existing table structure to a new one? (dont need the data, only the structure -> like id INTEGER, name varchar(20) ...)

Thx

like image 768
leon22 Avatar asked Oct 04 '12 15:10

leon22


People also ask

How do you clone a table from a table in SQL?

Step 1 − Get the complete structure about the table. Step 2 − Rename this table and create another table. Step 3 − After executing step 2, you will clone a table in your database.


2 Answers

You could use a command like this:

CREATE TABLE copied AS SELECT * FROM mytable WHERE 0 

but due to SQLite's dynamic typing, most type information would be lost.

If you need just a table that behaves like the original, i.e., has the same number and names of columns, and can store the same values, this is enough.

If you really need the type information exactly like the original, you can read the original SQL CREATE TABLE statement from the sqlite_master table, like this:

SELECT sql FROM sqlite_master WHERE type='table' AND name='mytable' 
like image 158
CL. Avatar answered Sep 23 '22 00:09

CL.


SQLite cannot clone table with PK, defaults and indices.

Hacking by another tool is necessary.

In shell, replace the table name by sed.

sqlite3 dbfile '.schema oldtable' | sed '1s/oldtable/newtable/' | sqlite3 dbfile 

And you can check new table.

sqlite3 dbfile '.schema newtable' 

Primary key, defaults and indices will be reserved.

I hope this command can help you.

like image 29
Raymond Wu Avatar answered Sep 24 '22 00:09

Raymond Wu