INSERT .. SELECT

From SQLZOO
Jump to navigation Jump to search

You can use the results of a SELECT statement to insert rows into another table.

INSERT INTO games(yr,city)
  SELECT yr+12, city FROM games;

The table games shows the year and the city hosting the Olympic Games.

games (before)
yrcity
2000Sydney
2004Athens
2008Beijing
games (after)
yrcity
2000Sydney
2004Athens
2008Beijing
2012Sydney
2016Athens
2020Beijing
schema:scott
 DROP TABLE games
 CREATE TABLE games(
  yr INTEGER,
  city VARCHAR(20));
INSERT INTO games VALUES (2000,'Sydney');
INSERT INTO games VALUES (2004,'Athens');
INSERT INTO games VALUES (2008,'Beijing');

The INSERT SELECT statement adds a new row to the table based on a SELECT statement: In this example you run the next three Olympic games in the same three venues:

INSERT INTO games(yr,city)
  SELECT yr+12, city FROM games;
SELECT * FROM games;
INSERT INTO games(yr,city)
  SELECT yr+12, city FROM games;

SELECT * FROM games;

See also

DataWars, Data Science Practice Projects - LogoDataWars: Practice Data Science/Analysis with +100 Real Life Projects