Search code examples
sqliteforeign-keystemp-tables

Refactor SQLite Table by splitting it in two and link with foreign keys


I'm working on a SQLite Database. The database is already filled, but I want to refactor it. Here is a sample of what I need to do:

I currently have one table:

CREATE TABLE Cars (ID INTEGER PRIMARY KEY,
                   Name VARCHAR(32),
                   TopSpeed FLOAT,                   
                   EngineCap FLOAT);

I want to split this into two tables:

CREATE TABLE Vehicles (ID INTEGER PRIMARY KEY,
                       Name VARCHAR(32),
                       TopSpeed FLOAT); 

CREATE TABLE Cars (ID INTEGER PRIMARY KEY,
                   VehicleID INTEGER CONSTRAINT FK_Cars REFERENCES [Vehicles](ID),                  
                   EngineCap FLOAT);          

I have figured out to create a temporary table with the Cars table contents, and I can fill up the Vehicles table with the contents of the Cars table:

CREATE TEMPORARY TABLE Cars_temp AS SELECT * FROM Cars;

INSERT INTO Vehicles (Name, TopSpeed)
SELECT Name, TopSpeed FROM Cars_temp;

But I am still looking for a way to go over that same selection, while putting the EngineCap field into the new Cars table and somehow extracting the corresponding ID value from the Vehicles table to put into the VehicleID foreign key field on the Cars table.

I'm open for workaround or alternative approaches.

Thanks.


Solution

  • Simple solution without triggers:

    • create VEHICLES_TEMP table including the CAR_ID
    • create your new CARS table without the VEHICLES columns you don't want
    • update CARS with VEHICLE_ID taken from VEHICLES_TEMP (identified by the CAR_ID)
    • create final VEHICLES table without the CAR_ID