v Store A Query Result - SQL

Store A Query Result

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.

# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False

Create Data

%%sql

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

Create A View

%%sql

-- Create a view called 'Santa Rosa'
CREATE VIEW [Santa Rosa] AS

-- That contains everything
SELECT *

-- From the table called 'criminals'
FROM criminals

-- If the city is 'Santa Rosa'
WHERE city = 'Santa Rosa'
[]

View The View

(I know, I know, stupid title)

%%sql

-- Select everything
SELECT * 

-- From the view called [Santa Rosa]
FROM [Santa Rosa]
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
901 Gordon Ado 32 F Santa Rosa 0
512 Bill Byson 21 M Santa Rosa 0