SQL Basics Cheat Sheet
SQL Basics Cheat Sheet
MULTIPLE VALUES This query displays German cyclists together with German skaters:
AGGREGATE FUNCTIONS A subquery can also return multiple columns or multiple rows. Such subqueries can be SELECT name
avg(expr) − average value for rows within the group used with operators INEXISTSALL
, , , or ANY. FROM cycling
count(expr) − count of values for rows within the group This query finds cities in countries that have a population above 20M: WHERE country = 'DE'
max(expr) − maximum value within the group SELECT name UNION / UNION ALL
min(expr) − minimum value within the group FROM city SELECT name
sum(expr) − sum of values within the group WHERE country_id IN ( FROM skating
SELECT country_id WHERE country = 'DE';
EXAMPLE QUERIES FROM country
INTERSECT
Find out the number of cities: WHERE population > 20000000
SELECT COUNT(*) ); INTERSECT returns only rows that appear in both result sets.
FROM city;
This query displays German cyclists who are also German skaters at the same time:
Find out the number of cities with non-null ratings: CORRELATED
SELECT COUNT(rating) SELECT name
A correlated subquery refers to the tables introduced in the outer query. A correlated
FROM city; FROM cycling
subquery depends on the outer query. It cannot be run independently from the outer
Find out the number of distinctive country values: WHERE country = 'DE'
quer y.
SELECT COUNT(DISTINCT country_id) INTERSECT
This query finds cities with a population greater than the average population in the
FROM city; SELECT name
country:
FROM skating
Find out the smallest and the greatest country populations: SELECT *
SELECT MIN(population), MAX(population) WHERE country = 'DE';
FROM city main_city
FROM country; WHERE population > ( EXCEPT
Find out the total population of cities in respective countries: SELECT AVG(population) FROM city average_city WHERE EXCEPT returns only the rows that appear in the first result set but do not appear in the
SELECT country_id, SUM(population) average_city.country_id = main_city.country_id second result set.
FROM city
GROUP BY country_id; This query displays German cyclists unless they are also German skaters at the same
);
time:
Find out the average rating for cities in respective countries if the average is above 3.0: SELECT name
SELECT country_id, AVG(rating) This query finds countries that have at least one city: FROM cycling
FROM city SELECT name WHERE country = 'DE'
GROUP BY country_id FROM country EXCEPT / MINUS
HAVING AVG(rating) > 3.0; WHERE EXISTS ( SELECT name
SELECT * FROM skating
FROM city WHERE country = 'DE';
WHERE country_id = country.id
);