SQL Cheat Sheet
SQL Cheat Sheet
Some might argue Python and R are equally important, but when
use SQL. Uber, Netflix, Airbnb — the list goes on. Even within
cover SELECT, FROM, WHERE, GROUP
BY, HAVING, ORDER BY and LIMIT.
as follows.
SELECT
COLUMN_NAME(S)
FROM
TABLE_NAME
WHERE
CONDITION
GROUP BY
COLUMN_NAME(S)
HAVING
AGGREGATE_CONDITION
ORDER BY
COLUMN_NAME
LIMIT
What is SQL?
The term relational means that values within each table have a
What is PostgreSQL?
system.
Let’s begin!
SELECT
Specific columns
SELECT
COLUMN_1,
COLUMN_2
FROM
TABLE_NAME
All columns
SELECT *
FROM
TABLE_NAME
DISTINCT Columns
SELECT
DISTINCT(COLUMN_NAME)
FROM
TABLE_NAME
COUNT all rows
SELECT
COUNT(*)
FROM
TABLE_NAME
SELECT
FROM
TABLE_NAME
WHERE
Using the WHERE the clause, you can create conditions to filter
this later)
SELECT *
FROM
TABLE_NAME
WHERE
CONDITION
Conditions
condition is met
missing values
Conditions — Wildcards
LIKE operator is used in a WHERE clause to search for a
the LIKE operator:
multiple characters
FIRSTNAME LIKE ‘B__%’ -- find values that start with “B” and
%b’ -- find values that start with “B” and end with “b”WHERE
FIRSTNAME LIKE ‘[BFL]’ -- find all values that start with ‘B’, ‘F’
GROUP BY
(COUNT, SUM, AVG, MAX, MIN).
SELECT
SUBJECT,
AVG(GRADES)
FROM
STUDENTS
GROUP BY
SUBJECT
the average grades.
SELECT
SUBJECT,
COUNT(*)
FROM
STUDENTS
GROUP BY
SUBJECT
each subject.
HAVING
The HAVING clause is similar to WHERE but is catered
the GROUP BY.
SELECT
SUBJECT,
AVG(GRADES)
FROM
STUDENTS
GROUP BY
SUBJECT
HAVING
AVG(GRADES) >= 90
ORDER BY
Using the ORDER BY function, you can specify how you want
earlier.
SELECT
FROM
STUDENTS
ORDER BY
GRADES DESC
LIMIT
FROM
STUDENTS
ORDER BY
GRADES DESC
LIMIT
the top 3.
Overview
Hopefully, you can use this starter guide for standard SQL syntax
used when querying data from a single table. There is a lot more
tutorials.