Title: Copy Data From One Table To Another
Slug: copy_data_between_tables
Summary: Copy Data From One Table To Another in SQL.
Date: 2016-05-01 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon

Note: This tutorial was written using Catherine Devlin's SQL in Jupyter Notebooks library. If you have not using a Jupyter Notebook, you can ignore the two lines of code below and any line containing %%sql. Furthermore, this tutorial uses SQLite's flavor of SQL, your version might have some differences in syntax.

For more, check out Learning SQL by Alan Beaulieu.


In [1]:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False

Create Table


In [2]:
%%sql

-- Create a table of criminals_1
CREATE TABLE criminals_1 (pid, name, age, sex, city, minor);
INSERT INTO criminals_1 VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1);
INSERT INTO criminals_1 VALUES (234, 'Bill James', 22, 'M', 'Santa Rosa', 0);
INSERT INTO criminals_1 VALUES (632, 'Stacy Miller', 23, 'F', 'Santa Rosa', 0);
INSERT INTO criminals_1 VALUES (621, 'Betty Bob', NULL, 'F', 'Petaluma', 1);
INSERT INTO criminals_1 VALUES (162, 'Jaden Ado', 49, 'M', NULL, 0);
INSERT INTO criminals_1 VALUES (901, 'Gordon Ado', 32, 'F', 'Santa Rosa', 0);
INSERT INTO criminals_1 VALUES (512, 'Bill Byson', 21, 'M', 'Santa Rosa', 0);
INSERT INTO criminals_1 VALUES (411, 'Bob Iton', NULL, 'M', 'San Francisco', 0);


Out[2]:
[]

View Table


In [3]:
%%sql

-- Select all
SELECT *

-- From the table 'criminals_1'
FROM criminals_1


Out[3]:
pid name age sex city minor
412 James Smith 15 M Santa Rosa 1
234 Bill James 22 M Santa Rosa 0
632 Stacy Miller 23 F Santa Rosa 0
621 Betty Bob None F Petaluma 1
162 Jaden Ado 49 M None 0
901 Gordon Ado 32 F Santa Rosa 0
512 Bill Byson 21 M Santa Rosa 0
411 Bob Iton None M San Francisco 0

Create New Empty Table


In [4]:
%%sql

-- Create a table called criminals_2
CREATE TABLE criminals_2 (pid, name, age, sex, city, minor);


Out[4]:
[]

Copy Contents Of First Table Into Empty Table


In [5]:
%%sql

-- Insert into the empty table
INSERT INTO criminals_2

-- Everything
SELECT * 

-- From the first table
FROM criminals_1;


Out[5]:
[]

View Previously Empty Table


In [6]:
%%sql

-- Select everything
SELECT *

-- From the previously empty table
FROM criminals_2


Out[6]:
pid name age sex city minor
412 James Smith 15 M Santa Rosa 1
234 Bill James 22 M Santa Rosa 0
632 Stacy Miller 23 F Santa Rosa 0
621 Betty Bob None F Petaluma 1
162 Jaden Ado 49 M None 0
901 Gordon Ado 32 F Santa Rosa 0
512 Bill Byson 21 M Santa Rosa 0
411 Bob Iton None M San Francisco 0