You are on page 1of 4

SQL Basics Cheat Sheet

SQL FILTERING THE OUTPUT QUERYING MULTIPLE TABLES


SQL, or Structured Query Language, is a language to talk to COMPARISON OPERATORS INNER JOIN FULL JOIN
databases. It allows you to select specific data and to build
Fetch names of cities that have a rating above 3: JOIN (or explicitly INNER JOIN) returns rows that have FULL JOIN (or explicitly FULL OUTER JOIN) returns all rows
complex reports. Today, SQL is a universal language of data. It is
matching values in both tables. from both tables – if there's no matching row in the second
used in practically all technologies that process data. SELECT name table, NULL s are returned.
FROM city
WHERE rating > 3; SELECT city.name, country.name SELECT city.name, country.name
FROM city FROM city
SAMPLE DATA [INNER] JOIN country FULL [OUTER] JOIN country
COUNTRY ON city.country_id = country.id; ON city.country_id = country.id;
id name population area Fetch names of cities that are neither Berlin nor Madrid: CITY COUNTRY
1 France 66600000 640680
2 Germany 80700000 357000
SELECT name CITY COUNTRY id name country_id id name
FROM city id name country_id id name 1 Paris 1 1 France
... ... ... ...
1 Paris 1 1 France 2 Berlin 2 2 Germany
WHERE name != 'Berlin'
CITY 2 Berlin 2 2 Germany 3 Warsaw 4 NULL NULL
AND name != 'Madrid';
id name country_id population rating 3 Warsaw 4 3 Iceland NULL NULL NULL 3 Iceland
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':

QUERYING SINGLE TABLE SELECT name


FROM city
LEFT JOIN CROSS JOIN
Fetch all columns from the country table: WHERE name LIKE 'P%' LEFT JOIN returns all rows from the left table with CROSS JOIN returns all possible combinations of rows from
OR name LIKE '%s'; corresponding rows from the right table. If there's no both tables. There are two syntaxes available.
SELECT *
matching row, NULL s are returned as values from the second SELECT city.name, country.name
FROM country;
table. FROM city
Fetch id and name columns from the city table: SELECT city.name, country.name CROSS JOIN country;
Fetch names of cities that start with any letter followed by FROM city
SELECT id, name 'ublin' (like Dublin in Ireland or Lublin in Poland): SELECT city.name, country.name
FROM city; LEFT JOIN country FROM city, country;
SELECT name ON city.country_id = country.id; CITY COUNTRY
Fetch city names sorted by the rating column FROM city CITY COUNTRY id name country_id id name
in the default ASCending order: WHERE name LIKE '_ublin'; id name country_id id name 1 Paris 1 1 France
1 Paris 1 1 France 1 Paris 1 2 Germany
SELECT name
2 Berlin 2 2 Germany 2 Berlin 2 1 France
FROM city
3 Warsaw 4 NULL NULL 2 Berlin 2 2 Germany
ORDER BY rating [ASC];
OTHER OPERATORS
Fetch city names sorted by the rating column Fetch names of cities that have a population between
in the DESCending order: 500K and 5M:
SELECT name SELECT name
FROM city FROM city
ORDER BY rating DESC; WHERE population BETWEEN 500000 AND 5000000; RIGHT JOIN NATURAL JOIN
NATURAL JOIN will join tables by all columns with the same
RIGHT JOIN returns all rows from the right table with
name.
corresponding rows from the left table. If there's no
ALIASES Fetch names of cities that don't miss a rating value: matching row, NULL s are returned as values from the left
table.
SELECT city.name, country.name
FROM city
COLUMNS SELECT name
NATURAL JOIN country;
FROM city SELECT city.name, country.name
SELECT name AS city_name WHERE rating IS NOT NULL; CITY COUNTRY
FROM city
FROM city; country_id id name name id
RIGHT JOIN country
6 6 San Marino San Marino 6
ON city.country_id = country.id;
TABLES 7 7 Vatican City Vatican City 7
5 9 Greece Greece 9
SELECT co.name, ci.name Fetch names of cities that are in countries with IDs 1, 4, 7, or 8: CITY COUNTRY
10 11 Monaco Monaco 10
id name country_id id name
FROM city AS ci SELECT name NATURAL JOIN used these columns to match rows:
1 Paris 1 1 France
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. A subquery is a query that is nested inside another query, or inside another subquery. Set operations are used to combine the results of two or more queries into a
It computes summaries (aggregates) for each unique combination of values. There are different types of subqueries. single result. The combined queries must return the same number of columns and
compatible data types. The names of the corresponding columns can be different.

CITY
id name country_id SINGLE VALUE
1 Paris 1 CYCLING SKATING
101 Marseille 1
CITY The simplest subquery returns exactly one column and exactly one row. It can be
country_id count 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 ZG DE 2 DF DE
2 3
103 Hamburg 2 3 WT PL 3 AK PL
104 Munich 2
4 2 SELECT name FROM city
... ... ... ... ... ...
3 Warsaw 4 WHERE rating = (
105 Cracow 4 SELECT rating
FROM city
WHERE name = 'Paris'
UNION
AGGREGATE FUNCTIONS );
UNION combines the results of two result sets and removes duplicates.
•  
avg(expr) − average value for rows within the group
UNION 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:
•  m ax(expr) − maximum value within the group
A subquery can also return multiple columns or multiple rows. Such subqueries can be SELECT name
•  min(expr) − minimum value within the group FROM cycling
used with operators IN, EXISTS, ALL, or ANY.
•  sum(expr) − sum of values within the group WHERE country = 'DE'
This query finds cities in countries that have a population above 20M: UNION / UNION ALL
SELECT name SELECT name
EXAMPLE QUERIES FROM city FROM skating
Find out the number of cities: WHERE country_id IN ( WHERE country = 'DE';
SELECT country_id
SELECT COUNT(*)
FROM country
FROM city;
WHERE population > 20000000
); INTERSECT
Find out the number of cities with non-null ratings: INTERSECT returns only rows that appear in both result sets.
SELECT COUNT(rating) This query displays German cyclists who are also German skaters at the same time:
FROM city; CORRELATED SELECT name
A correlated subquery refers to the tables introduced in the outer query. A correlated FROM cycling
Find out the number of distinctive country values: subquery depends on the outer query. It cannot be run independently from the outer WHERE country = 'DE'
SELECT COUNT(DISTINCT country_id) query. INTERSECT
FROM city; SELECT name
This query finds cities with a population greater than the average population in the
FROM skating
country:
WHERE country = 'DE';
Find out the smallest and the greatest country populations: SELECT *
FROM city main_city
SELECT MIN(population), MAX(population)
WHERE population > (
FROM country;
SELECT AVG(population) EXCEPT
FROM city average_city EXCEPT returns only the rows that appear in the first result set but do not appear
Find out the total population of cities in respective countries: WHERE average_city.country_id = main_city.country_id in the second result set.
SELECT country_id, SUM(population) );
This query displays German cyclists unless they are also German skaters at the
FROM city
This query finds countries that have at least one city: same time:
GROUP BY country_id;
SELECT name SELECT name
FROM country FROM cycling
Find out the average rating for cities in respective countries if the average is above 3.0: WHERE EXISTS ( WHERE country = 'DE'
SELECT country_id, AVG(rating) SELECT * EXCEPT / MINUS
FROM city FROM city SELECT name
GROUP BY country_id WHERE country_id = country.id FROM skating
HAVING AVG(rating) > 3.0; ); WHERE country = 'DE';

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
SQL CHEAT SHEET http://www.sqltutorial.org
QUERYING DATA FROM A TABLE QUERYING FROM MULTIPLE TABLES USING SQL OPERATORS

SELECT c1, c2 FROM t; SELECT c1, c2 SELECT c1, c2 FROM t1


Query data in columns c1, c2 from a table FROM t1 UNION [ALL]
INNER JOIN t2 ON condition; SELECT c1, c2 FROM t2;
SELECT * FROM t; Inner join t1 and t2 Combine rows from two queries
Query all rows and columns from a table
SELECT c1, c2 SELECT c1, c2 FROM t1
SELECT c1, c2 FROM t FROM t1 INTERSECT
WHERE condition; LEFT JOIN t2 ON condition; SELECT c1, c2 FROM t2;
Query data and filter rows with a condition Left join t1 and t1 Return the intersection of two queries

SELECT DISTINCT c1 FROM t SELECT c1, c2


WHERE condition; FROM t1 SELECT c1, c2 FROM t1
Query distinct rows from a table RIGHT JOIN t2 ON condition; MINUS
Right join t1 and t2 SELECT c1, c2 FROM t2;
Subtract a result set from another result set
SELECT c1, c2 FROM t
ORDER BY c1 ASC [DESC]; SELECT c1, c2
Sort the result set in ascending or descending FROM t1 SELECT c1, c2 FROM t1
order FULL OUTER JOIN t2 ON condition; WHERE c1 [NOT] LIKE pattern;
Perform full outer join Query rows using pattern matching %, _
SELECT c1, c2 FROM t
ORDER BY c1 SELECT c1, c2
SELECT c1, c2 FROM t
LIMIT n OFFSET offset; FROM t1
WHERE c1 [NOT] IN value_list;
Skip offset of rows and return the next n rows CROSS JOIN t2;
Query rows in a list
Produce a Cartesian product of rows in tables
SELECT c1, aggregate(c2)
FROM t SELECT c1, c2 SELECT c1, c2 FROM t
GROUP BY c1; FROM t1, t2; WHERE c1 BETWEEN low AND high;
Group rows using an aggregate function Another way to perform cross join Query rows between two values

SELECT c1, aggregate(c2) SELECT c1, c2 SELECT c1, c2 FROM t


FROM t FROM t1 A WHERE c1 IS [NOT] NULL;
GROUP BY c1 INNER JOIN t2 B ON condition; Check if values in a table is NULL or not
HAVING condition; Join t1 to itself using INNER JOIN clause
Filter groups using HAVING clause
SQL CHEAT SHEET http://www.sqltutorial.org
MANAGING TABLES USING SQL CONSTRAINTS MODIFYING DATA

CREATE TABLE t ( CREATE TABLE t( INSERT INTO t(column_list)


id INT PRIMARY KEY, c1 INT, c2 INT, c3 VARCHAR, VALUES(value_list);
name VARCHAR NOT NULL, PRIMARY KEY (c1,c2) Insert one row into a table
price INT DEFAULT 0 );
); Set c1 and c2 as a primary key INSERT INTO t(column_list)
Create a new table with three columns
VALUES (value_list),
CREATE TABLE t1( (value_list), ….;
DROP TABLE t ; c1 INT PRIMARY KEY, Insert multiple rows into a table
Delete the table from the database c2 INT,
FOREIGN KEY (c2) REFERENCES t2(c2) INSERT INTO t1(column_list)
); SELECT column_list
ALTER TABLE t ADD column; Set c2 column as a foreign key FROM t2;
Add a new column to the table
Insert rows from t2 into t1
CREATE TABLE t(
ALTER TABLE t DROP COLUMN c ; c1 INT, c1 INT, UPDATE t
Drop column c from the table UNIQUE(c2,c3) SET c1 = new_value;
); Update new value in the column c1 for all rows
ALTER TABLE t ADD constraint; Make the values in c1 and c2 unique
Add a constraint UPDATE t
CREATE TABLE t( SET c1 = new_value,
c1 INT, c2 INT, c2 = new_value
ALTER TABLE t DROP constraint; WHERE condition;
Drop a constraint CHECK(c1> 0 AND c1 >= c2)
); Update values in the column c1, c2 that match
Ensure c1 > 0 and values in c1 >= c2 the condition

Rename a table from t1 to t2 DELETE FROM t;


CREATE TABLE t( Delete all data in a table
c1 INT PRIMARY KEY,
ALTER TABLE t1 RENAME c1 TO c2 ; c2 VARCHAR NOT NULL
Rename column c1 to c2 ); DELETE FROM t
Set values in c2 column not NULL WHERE condition;
Delete subset of rows in a table
TRUNCATE TABLE t;
Remove all data in a table
SQL CHEAT SHEET http://www.sqltutorial.org
MANAGING VIEWS MANAGING INDEXES MANAGING TRIGGERS

CREATE VIEW v(c1,c2) CREATE INDEX idx_name


CREATE OR MODIFY TRIGGER trigger_name
AS ON t(c1,c2);
WHEN EVENT
SELECT c1, c2 Create an index on c1 and c2 of the table t
ON table_name TRIGGER_TYPE
FROM t;
EXECUTE stored_procedure;
Create a new view that consists of c1 and c2
CREATE UNIQUE INDEX idx_name Create or modify a trigger
ON t(c3,c4);
CREATE VIEW v(c1,c2) Create a unique index on c3, c4 of the table t
WHEN
AS • BEFORE – invoke before the event occurs
SELECT c1, c2 • AFTER – invoke after the event occurs
FROM t; DROP INDEX idx_name;
WITH [CASCADED | LOCAL] CHECK OPTION; Drop an index
Create a new view with check option EVENT
• INSERT – invoke for INSERT
SQL AGGREGATE FUNCTIONS • UPDATE – invoke for UPDATE
CREATE RECURSIVE VIEW v • DELETE – invoke for DELETE
AS AVG returns the average of a list
select-statement -- anchor part
COUNT returns the number of elements of a list
UNION [ALL] TRIGGER_TYPE
select-statement; -- recursive part SUM returns the total of a list • FOR EACH ROW
Create a recursive view • FOR EACH STATEMENT
MAX returns the maximum value in a list

CREATE TEMPORARY VIEW v MIN returns the minimum value in a list CREATE TRIGGER before_insert_person
AS BEFORE INSERT
SELECT c1, c2 ON person FOR EACH ROW
FROM t; EXECUTE stored_procedure;
Create a temporary view Create a trigger invoked before a new row is
inserted into the person table

DROP VIEW view_name


Delete a view DROP TRIGGER trigger_name
Delete a specific trigger

You might also like