This is taken from the Socratica SQL youtube video for SELECT. I have also added in a bit more
SELECT is for choosing columns
FROM is for choosing a database
WHERE is for choosing the rows
ORDER BY is for sorting and sorts on a specified column
# Load in the sql extensions:
%load_ext sql
#% sql sqlite://
! postgres -V
DB_ENGINE='postgresql' # tells ipython-sql that we will use postgreSQL as our database engine
DB_USER='postgres' # id of the user who is logging in
DB_PWD='postgres' # the user's password
DB_ADDR='localhost:5432' # the host and port on which the database engine is listening
DB_NAME='earthquake' # the name of the database
#Construct the connection string
DB_CONNECTION = '{engine}://{user}:{pwd}@{addr}/{name}'.format(engine=DB_ENGINE,
user=DB_USER,
pwd=DB_PWD,
addr=DB_ADDR,
name=DB_NAME)
#Preview the connection string
DB_CONNECTION
%sql $DB_CONNECTION
%%sql
SELECT * FROM earthquake
LIMIT 8;
%%sql
SELECT COUNT(*) FROM earthquake;
%%sql
SELECT magnitude, place, occurred_on FROM earthquake
LIMIT 8;
%%sql
SELECT *
FROM earthquake
WHERE occurred_on >= '2010-1-1' AND occurred_on <= '2010-12-31'
ORDER BY magnitude DESC -- The DESC means descending order
LIMIT 1;
%%sql
SELECT MIN(occurred_on), MAX(occurred_on)
FROM earthquake;
%%sql
SELECT MIN(magnitude), MAX(magnitude)
FROM earthquake;
%%sql
SELECT AVG(magnitude)
FROM earthquake;
%%sql
SELECT DISTINCT cause
FROM earthquake;
%%sql
SELECT COUNT(*)
FROM earthquake
WHERE cause = 'earthquake';
%%sql
SELECT COUNT(*)
FROM earthquake
WHERE cause = 'nuclear explosion';
%%sql
SELECT COUNT(*)
FROM earthquake
WHERE cause = 'explosion';
%%sql
SELECT *
FROM earthquake
WHERE cause = 'explosion';
The above table is actually nuclear explosions and not explosion. This is an example of messy data and needs to be cleaned. Evidence for the explosions being nuclear explosions
eastern Kazakhstan https://en.wikipedia.org/wiki/1973_Soviet_nuclear_tests
Novaya Zemlya, Russia https://en.wikipedia.org/wiki/1975_Soviet_nuclear_tests
Tuamotu Archipelago, French Polynesia region, 1984 and 1985 https://en.wikipedia.org/wiki/1983%E2%80%9385_French_nuclear_tests
DESC
arranges the column in numerical descending order
%%sql
SELECT place, magnitude, occurred_on
FROM earthquake
ORDER BY magnitude DESC
LIMIT 10;
%%sql
SELECT COUNT(*) AS "Aftershocks"
FROM earthquake
WHERE place LIKE '%Honshu%Japan%'
AND occurred_on BETWEEN '2011-03-11' AND '2011-03-18'
AND magnitude >= 6;
#! postgres --help