Sql – How to split table into multiple tables using SQL

sqlsql server

Hi I have this table Cars:

MODEL nvarchar(20)
STYLE nvarchar(20)
ENGINE nvarchar(5)
CAPACITY smallint
MAX_SPEED smallint
PRICE smallmoney
MARKET nvarchar(20)
COMPETITOR nvarchar(20)

And I would like to split it into 3 tables via SQL query:

Cars:

MODEL nvarchar(20)
STYLE nvarchar(20)
MAX_SPEED smallint
PRICE smallmoney

Engine:

ENGINE nvarchar(5)
CAPACITY smallint

Market:

MARKET nvarchar(20)
COMPETITOR nvarchar(20)

So was wandering how this would be done using sql commands, thanks

Best Answer

Easiest way. Select... Into will create new tables:

SELECT DISTINCT
    ENGINE,
    CAPACITY
INTO Engine
FROM CARS


SELECT DISTINCT
    MARKET,
    COMPETITOR
INTO Market
FROM CARS

Then just drop the defunct columns from the original table. Eg

ALTER TABLE Cars DROP COLUMN ENGINE
ALTER TABLE Cars DROP COLUMN CAPACITY
ALTER TABLE Cars DROP COLUMN MARKET
ALTER TABLE Cars DROP COLUMN COMPETITOR

This will do specifically what you are asking. However, I'm not sure that is what you want - there is then no reference from the car to the engine or market details - so information is lost.

If "ENGINE" and "MARKET" define the keys of the new table, I'd suggest leaving those columns on the car table as foreign keys. Eg only DROP Capacity and Competitor.

You may wish to create the primary key on the new tables too. Eg: ALTER TABLE ENGINE ADD CONSTRAINT [PK_Engine] PRIMARY KEY CLUSTERED ENGINE ASC