SQL Basics Cheat Sheet Ledger
SQL Basics Cheat Sheet Ledger
ORDER BY rating [ASC]; Fetch names of cities that have a population between 500K
and 5M:
SELECT name
Fetch city names sorted by the rating column in the
FROM city
DESCending order:
WHERE population BETWEEN 500000 AND
SELECT name
5000000; NATURAL JOIN
FROM city
ORDER BY rating DESC; NATURAL JOIN will join tables by all columns with the
RIGHT JOIN same name.
RIGHT JOIN returns all rows from the right table with SELECT city.name, country.name
ALIASES Fetch names of cities that don't miss a rating value:
SELECT name
corresponding rows from the left table. If there's no matching FROM city
row, NULLs are returned as values from the left table. NATURAL JOIN country;
COLUMNS FROM city
SELECT city.name, country.name CITY COUNTRY
SELECT name AS city_name WHERE rating IS NOT NULL;
FROM city country_id id name name id
FROM city; RIGHT JOIN country 6 6 San Marino San Marino 6
ON city.country_id = country.id; 7 7 Vatican City Vatican City 7
id name country_id
1 Paris 1
CITY SINGLE VALUE CYCLING SKATING
101 Marseille 1
country_id count The simplest subquery returns exactly one column and exactly one row. It can be
id name country id name country
102 Lyon 1 used with comparison operators =, <, <=, >, or >=.
1 3 1 YK DE 1 YK DE
2 Berlin 2 This query finds cities with the same rating as Paris:
2 3 SELECT name 2 ZG DE 2 DF DE
103 Hamburg 2
4 2 FROM city
3 WT PL 3 AK PL
104 Munich 2 WHERE rating = (
SELECT rating ... ... ... ... ... ...
3 Warsaw 4
FROM city
105 Cracow 4
WHERE name = 'Paris'
);
UNION
AGGREGATE FUNCTIONS UNION combines the results of two result sets and removes duplicates. UNION
avg(expr) − average value for rows within the group ALL doesn't remove duplicate rows.
count(expr) − count of values for rows within the group
MULTIPLE VALUES This query displays German cyclists together with German skaters:
max(expr) − maximum value within the group
A subquery can also return multiple columns or multiple rows. Such subqueries can SELECT name
min(expr) − minimum value within the group
be used with operators IN, EXISTS, ALL, or ANY. FROM cycling
sum(expr) − sum of values within the group
This query finds cities in countries that have a population above 20M: WHERE country = 'DE'
SELECT name UNION / UNION ALL
FROM city SELECT name
EXAMPLE QUERIES WHERE country_id IN ( FROM skating
Find out the number of cities: SELECT country_id WHERE country = 'DE';
SELECT COUNT(*) FROM country
FROM city; WHERE population > 20000000
);