SQL Basics Cheat Sheet A4
SQL Basics Cheat Sheet A4
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 IN, EXISTS, ALL, 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
Find out the number of cities: WHERE population > 20000000 INTERSECT
SELECT COUNT(*) );
INTERSECT returns only rows that appear in both result sets.
FROM city;
CORRELATED This query displays German cyclists who are also German skaters at the same time:
Find out the number of cities with non-null ratings: SELECT name
A correlated subquery refers to the tables introduced in the outer query. A correlated
SELECT COUNT(rating) FROM cycling
subquery depends on the outer query. It cannot be run independently from the outer
FROM city; WHERE country = 'DE'
query.
INTERSECT
Find out the number of distinctive country values: This query finds cities with a population greater than the average population in the
SELECT name
SELECT COUNT(DISTINCT country_id) country:
FROM skating
FROM city; SELECT *
WHERE country = 'DE';
FROM city main_city
Find out the smallest and the greatest country populations: WHERE population > (
SELECT MIN(population), MAX(population) SELECT AVG(population) EXCEPT
FROM city average_city EXCEPT returns only the rows that appear in the first result set but do not appear in the
FROM country;
WHERE average_city.country_id = main_city.country_id second result set.
Find out the total population of cities in respective countries: );
This query displays German cyclists unless they are also German skaters at the same
SELECT country_id, SUM(population)
time:
FROM city This query finds countries that have at least one city:
SELECT name
GROUP BY country_id; SELECT name
FROM cycling
FROM country
WHERE country = 'DE'
Find out the average rating for cities in respective countries if the average is above 3.0: WHERE EXISTS (
EXCEPT / MINUS
SELECT country_id, AVG(rating) SELECT *
SELECT name
FROM city FROM city
FROM skating
GROUP BY country_id WHERE country_id = country.id
WHERE country = 'DE';
HAVING AVG(rating) > 3.0; );