SQL Queries Cheatsheet: Querying Single Table Querying Multiple Tables
SQL Queries Cheatsheet: Querying Single Table Querying Multiple Tables
rating > 3;
-- start with a 'P' or end with an 's' -- fetch all countries even if no matching cities exist
city RIGHT (OUTER) JOIN country
name LIKE 'P%' OR name LIKE '%s';
-- have a population between 1M and 5M -- fetch all cities and all countries even if no matching
-- values exist in the other table
population BETWEEN 1000000 AND 5000000; city FULL (OUTER) JOIN country
AGGREGATION/GROUPING CORRELATED
-- cities with population greater than
-- cities with highest rating first -- average population in the country
SELECT name FROM city ORDER BY rating DESC; SELECT * FROM city main_city
WHERE population >
-- number of all cities (SELECT AVG(population)
FROM city average_city
SELECT COUNT(*) FROM city; WHERE average_city.country_id =
main_city.country_id);
-- number of cities with non-null rating
-- countries that have at least one city
SELECT COUNT(rating) FROM city;
SELECT name FROM country
WHERE EXISTS (SELECT * FROM city
-- number of distinctive country values
WHERE country_id = country.id);
SELECT COUNT(DISTINCT country_id)
FROM city;
SINGLE VALUE
-- German cyclers that are also German
-- cities with the same rating as Paris -- skaters at the same time
MULTIPLE VALUES
-- German cyclers unless they are also
-- cities in countries that have -- German skaters at the same time
-- a population above 20M
SELECT name FROM cycling
SELECT name FROM city WHERE country = 'DE'
WHERE country_id IN EXCEPT/MINUS
(SELECT country_id FROM country SELECT name FROM skating
WHERE population > 20000000); WHERE country = 'DE'; EXCEPT