SQL Cheatsheet
SQL Cheatsheet
SQL Cheatsheet
*
*
*
*
FROM
FROM
FROM
FROM
books;
products;
users;
countries;
Examples:
SELECT
SELECT
SELECT
SELECT
Examples:
SELECT
SELECT
SELECT
SELECT
Examples:
SELECT username AS Username, first_name AS "First Name" FROM users;
SELECT title AS Title, year AS "Year Released" FROM movies;
SELECT name AS Name, description AS Description, price AS "Current Price" FROM
products;
SELECT name Name, description Description, price "Current Price" FROM products;
Equality Operator
Find all rows that a given value matches a column's value.
SELECT <columns> FROM <table> WHERE <column name> = <value>;
Examples:
SELECT
SELECT
SELECT
SELECT
Inequality Operator
Find all rows that a given value doesn't match a column's value.
SELECT <columns> FROM <table> WHERE <column name> != <value>;
SELECT <columns> FROM <table> WHERE <column name> <> <value>;
Relational Operators
There are several relational operators you can use:
<
<=
>
>=
less than
less than or equal to
greater than
greater than or equal to
<columns>
<columns>
<columns>
<columns>
Examples:
FROM
FROM
FROM
FROM
<table>
<table>
<table>
<table>
WHERE
WHERE
WHERE
WHERE
<column
<column
<column
<column
name>
name>
name>
name>
< <value>;
<= <value>;
> <value>;
>= <value>;
SELECT
SELECT
2015;
SELECT
SELECT
Examples:
SELECT username FROM users WHERE last_name = "Chalkley" AND first_name =
"Andrew";
SELECT * FROM products WHERE category = "Games Consoles" AND price < 400;
SELECT * FROM movies WHERE title = "The Matrix" OR title = "The Matrix Reloaded" OR
title = "The Matrix Revolutions";
SELECT country FROM countries WHERE population < 1000000 OR population >
100000000;
Examples:
SELECT
SELECT
SELECT
SELECT
Examples:
SELECT answer FROM answers WHERE id IN (7, 42);
SELECT * FROM products WHERE category NOT IN ("Electronics");
SELECT title FROM courses WHERE topic NOT IN ("SQL", "NoSQL");
Examples:
SELECT * FROM movies WHERE release_year BETWEEN 2000 AND 2010;
SELECT name, description FROM products WHERE price BETWEEN 9.99 AND 19.99;
SELECT name, appointment_date FROM appointments WHERE appointment_date
BETWEEN "2015-01-01" AND "2015-01-07";
Pattern Matching
Placing the percent symbol (%) any where in a string in conjunction with
the LIKE keyword will operate as a wildcard. Meaning it can be substituted
by any number of characters, including zero!
SELECT <columns> FROM <table> WHERE <column> LIKE <pattern>;
Examples:
SELECT
SELECT
SELECT
SELECT
Missing Values
SELECT * FROM <table> WHERE <column> IS NULL;
Examples:
SELECT * FROM people WHERE last_name IS NULL;
SELECT * FROM vhs_rentals WHERE returned_on IS NULL;
SELECT * FROM car_rentals WHERE returned_on IS NULL AND location = "PDX";
To filter out missing values use can use IS NOT NULL.
SELECT * FROM <table> WHERE <column> IS NOT NULL;
Examples
SELECT * FROM people WHERE email IS NOT NULL;
SELECT * FROM addresses WHERE zip_code IS NOT NULL;
Ordering Columns
Ordering by a single column criteria:
SELECT * FROM <table name> ORDER BY <column> [ASC|DESC];
ASC is used to order results in ascending order.
DESC is used to order results in descending order.
Examples:
SELECT
SELECT
SELECT
SELECT
*
*
*
*
FROM
FROM
FROM
FROM
genre ASC,
Limiting Results
SQLite, PostgreSQL and MySQL
To limit the number of results returned, use the LIMIT keyword.
SELECT <columns> FROM <table> LIMIT <# of rows>;
MS SQL
To limit the number of results returned, use the TOP keyword.
SELECT TOP <# of rows> <columns> FROM <table>;
Oracle
To limit the number of results returned, use the ROWNUM keyword in
a WHERE clause.
SELECT <columns> FROM <table> WHERE ROWNUM <= <# of rows>;
Syntax definitions
Examples:
SELECT UPPER("Andrew Chalkley");
SELECT UPPER(name) FROM passport_holders;
Concatenating Strings
SQLite, PostgreSQL and Oracle
Use the concatenation operator ||.
SELECT <value or column> || <value or column> || <value or column> FROM <table>;
MS SQL
Use the concatenation operator +.
SELECT <value or column> + <value or column> + <value or column> FROM <table>;
Counting Results
To count rows you can use the COUNT() function.
SELECT COUNT(*) FROM <table>;
Obtaining Totals
To total up numeric columns use the SUM() function.
SELECT SUM(<numeric column) FROM <table>;
SELECT SUM(<numeric column) AS <alias> FROM <table>
Calculating Averages
To get the average value of a numeric column use the AVG() function.
SELECT AVG(<numeric column>) FROM <table>;
SELECT AVG(<numeric column>) FROM <table> GROUP BY <other column>;
Mathematical Operators
Multiply
Divide
Add
Subtract
MS SQL
To get the current date use: CONVERT(date, GETDATE())
To get the current time use: CONVERT(time, GETDATE())
To get the current date time: GETDATE()
MySQL
Calculating Dates
See documentation sites:
SQLite
MS SQL
PostgreSQL
MySQL
Oracle
Formatting Dates
See documentation sites:
SQLite
MS SQL
PostgreSQL
MySQL
Oracle
SQL JOINs
JOINs merge related data from multiple tables together in to result set.
The two most common types of joins are:
INNER JOIN
OUTER JOIN
INNER JOINs
INNER JOINs return rows that match from both tables.
SELECT <columns> FROM <table 1>
INNER JOIN <table 2> ON <table 1>.<column> = <table 2>.<column>;
SELECT <columns> FROM <table 1> AS <table 1 alias>
INNER JOIN <table 2> AS <table 2 alias> ON <table 1 alias>.<column> = <table 2
alias>.<column>;
Examples:
SELECT product_name, category FROM products
INNER JOIN product_categories ON products.category_id = product_categories.id;
SELECT products.product_name, product_categories.category FROM products
INNER JOIN product_categories ON products.category_id = product_categories.id;
SELECT p.product_name, c.category FROM products AS p
INNER JOIN product_categories AS c ON p.category_id = c.id;
Examples:
SELECT users.full_name, sales.amount, products.name FROM sales
INNER JOIN users ON users.id = sales.user_id
INNER JOIN products ON products.id = sales.product_id;
OUTER JOINs
There are 3 types of OUTER JOINs:
LEFT OUTER JOIN - JOINs all matching data and all non-matching
rows from the left table in the query
RIGHT OUTER JOIN - JOINs all matching data and all non-matching
rows from the right table in the query
FULL OUTER JOIN - JOINs all matching data and then all nonmatching rows from both tables.
Example
If you wanted to get the product count for every category, even categories
without products, an OUTER JOIN is the best solution. The following two
examples will yield the same results, however one is an
SELECT categories.name, COUNT(products.id) AS "Product Count" FROM categories
LEFT OUTER JOIN products ON categories.id = products.category_id;
SELECT categories.name, COUNT(products.id) AS "Products Count" FROM products
RIGHT OUTER JOIN categories ON categories.id = products.category_id;
Set Operations
Set operations merge data in to one set based on column definitions and
the data contained within each column.
The four set operations are:
UNION
UNION ALL
INTERSECT
EXCEPT
UNION Examples
Unions return all distinct values from both data sets with no duplicates.
Get a list of unique restaurants from both north and south malls.
SELECT store FROM mall_south WHERE type = "restaurant"
UNION
SELECT store FROM mall_north WHERE type = "restaurant";
Get a list of unique classes taught in two schools. Order them by their
class name.
SELECT evening_class FROM school_1 UNION SELECT evening_class FROM school_2
ORDER BY evening_class ASC;
UNION ALL
Union all returns all values from both data sets with duplicates.
Get a list of all names for boys and girls and order them by name.
SELECT boy_name AS name FROM boy_baby_names
UNION ALL
SELECT girl_name AS name FROM girl_baby_names
ORDER by name;
INTERSECT
Returns only values that in both data sets.
Get list of classes offered in both schools.
SELECT evening_class FROM school_1 INTERSECT SELECT evening_class FROM school_2
ORDER BY evening_class ASC;
EXCEPT
Returns data from the first data set that's not in the second.
Get a list of local stores in a mall.
SELECT store FROM mall
EXCEPT
SELECT store FROM all_stores WHERE type = "national"
Subqueries
Subqueries are queries within queries. A subquery can also be called
an inner query with the "parent" query being called the outer query.
Examples:
Get a list of user's names and emails for users who have spent over 100
dollars in a single transaction.
SELECT name, email FROM users
WHERE id IN (SELECT DISTINCT(user_id) FROM sales WHERE saleAmount > 100);
// OR
SELECT name, email FROM users
INNER JOIN (SELECT DISTINCT(user_id) FROM sales WHERE saleAmount > 100) AS
best_customers
ON best_customers.user_id = users.id
Get a list of user's names and emails for users who have spent over 1000
dollars in total.
SELECT name, email FROM users WHERE id IN (SELECT user_id FROM sales WHERE
SUM(saleAmount) > 1000 GROUP BY user_id);
// OR
SELECT name, email, total FROM users
INNER JOIN (SELECT user_id, SUM(saleAmount) AS total FROM sales WHERE total >
1000 GROUP BY user_id) AS ultimate_customers
ON ultimate_customers.user_id = users.id;