Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

SQL Basics Cheat Sheet

SQL, or Structured Query Language, is a language to talk to FULL JOIN


databases. It allows you to select specific data and to build FILTERING THE OUTPUT QUERYING MULTIPLE TABLES
FULL JOIN (or explicitly FULL OUTER JOIN) returns all
complex reports. Today, SQL is a universal language of data. COMPARISON OPERATORS INNER JOIN rows from both tables – if there's no matching row in the
It is used in practically all technologies that process data. Fetch names of cities that have a rating above 3: JOIN (or explicitly INNER JOIN) returns rows that have second table, NULLs are returned.
SELECT name matching values in both tables. SELECT city.name, country.name
FROM city SELECT city.name, country.name FROM city
SAMPLE DATA WHERE rating > 3; FROM city FULL [OUTER] JOIN country
COUNTRY [INNER] JOIN country ON city.country_id = country.id;
ON city.country_id = country.id; CITY COUNTRY
id name population area
CITY COUNTRY id name country_id id name
1 France 66600000 640680 Fetch names of cities that are neither Berlin nor Madrid: id name country_id id name 1 Paris 1 1 France
2 Germany 80700000 357000 SELECT name 1 Paris 1 1 France 2 Berlin 2 2 Germany
FROM city 2 Berlin 2 2 Germany
... ... ... ... 3 Warsaw 4 NULL NULL
WHERE name != 'Berlin'
3 Warsaw 4 3 Iceland NULL NULL NULL 3 Iceland
CITY AND name != 'Madrid';
id name country_id population rating
1 Paris 1 2243000 5
2 Berlin 2 3460000 3 TEXT OPERATORS
... ... ... ... ... Fetch names of cities that start with a 'P' or end with an 's':
SELECT name CROSS JOIN
FROM city CROSS JOIN returns all possible combinations of rows from
LEFT JOIN
QUERYING SINGLE TABLE WHERE name LIKE 'P%'
OR name LIKE '%s'; LEFT JOIN returns all rows from the left table with
both tables. There are two syntaxes available.
Fetch all columns from the country table: SELECT city.name, country.name
corresponding rows from the right table. If there's no
SELECT * FROM city
matching row, NULLs are returned as values from the second
FROM country; CROSS JOIN country;
table.
Fetch names of cities that start with any letter followed by SELECT city.name, country.name
SELECT city.name, country.name
Fetch id and name columns from the city table: 'ublin' (like Dublin in Ireland or Lublin in Poland): FROM city
FROM city, country;
SELECT id, name SELECT name LEFT JOIN country
CITY COUNTRY
FROM city; FROM city ON city.country_id = country.id;
id name country_id id name
WHERE name LIKE '_ublin'; CITY COUNTRY
1 Paris 1 1 France
id name country_id id name
Fetch city names sorted by the rating column in the default 1 Paris 1 2 Germany
1 Paris 1 1 France
ASCending order: 2 Berlin 2 1 France
2 Berlin 2 2 Germany
SELECT name 2 Berlin 2 2 Germany
FROM city OTHER OPERATORS 3 Warsaw 4 NULL NULL

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

TABLES Fetch names of cities that are in countries with IDs 1, 4, 7, or


CITY COUNTRY 5 9 Greece Greece 9
id name country_id id name 10 11 Monaco Monaco 10
SELECT co.name, ci.name 8:
1 Paris 1 1 France
FROM city AS ci SELECT name NATURAL JOIN used these columns to match rows:
JOIN country AS co FROM city 2 Berlin 2 2 Germany city.id, city.name, country.id, country.name.
ON ci.country_id = co.id; WHERE country_id IN (1, 4, 7, 8); NULL NULL NULL 3 Iceland NATURAL JOIN is very rarely used in practice.

AGGREGATION AND GROUPING SUBQUERIES SET OPERATIONS


GROUP BY groups together rows that have the same values in specified columns. It A subquery is a query that is nested inside another query, or inside another Set operations are used to combine the results of two or more queries into a single
computes summaries (aggregates) for each unique combination of values. subquery. There are different types of subqueries. result. The combined queries must return the same number of columns and
CITY compatible data types. The names of the corresponding columns can be different.

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
);

Find out the number of cities with non-null ratings:


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

LearnSQL.com is owned by Vertabelo SA


Try out the interactive SQL Basics course at LearnSQL.com, and check out our other SQL courses. vertabelo.com | CC BY-NC-ND Vertabelo SA

You might also like