SQL Beginner Cheatsheet

Basic SQL Syntactic Structure

SELECT column_name(s)
FROM table_name
WHERE some_condition
GROUP BY column_na
HAVING some_aggregate_condition
ORDER BY column_name
LIMIT N

SELECT

SELECT *
FROM table_name
SELECT column1, column2, column3
FROM table_name

WHERE

SELECT *
FROM table_name
WHERE some_condition
WHERE first_name = 'PETER'      -- exact match
WHERE first_name != 'PETER' -- everything except PETER
WHERE transaction_amount > 100 -- greater than 100
WHERE transaction_amount < 100 -- less than 100
WHERE user_ID >= 50 -- greater than or equal to 50
WHERE user_ID <= 90 -- less than or equal to 50
LIKE
WHERE product LIKE 'A%' -- values starting with capital A
WHERE product LIKE '%a' -- values ending with lowercase A
WHERE product LIKE '%hair%' -- values containing "hair" in any position
WHERE product ILIKE 'a%A' -- values starting and ending with
'a', note: ILIKE is not case
sensitive
IN
WHERE ranking IN (1,2,3) -- values in the top 3 rankings
WHERE first_name NOT IN ('ROB','BOB') -- exclude both values
BETWEEN
WHERE year BETWEEN 2000 AND 2020 -- values between 2020 and 2020
NOT
WHERE product NOT ILIKE '%a%' -- exclude products that contain 'a'
WHERE user_ID IS NOT NULL -- include rows with non-null userID
IS NULL
WHERE product IS NULL -- include rows with no product names
Multiple Conditions
WHERE FIRSTNAME = 'BOB' AND LASTNAME = 'SMITH' -- both conditions
WHERE FIRSTNAME = 'BOB' OR FIRSTNAME = 'JASON' -- either condition

ORDER BY

SELECT *
FROM transactions
ORDER BY transaction_amount DESC
SELECT *
FROM transactions
ORDER BY transaction_amount, year

LIMIT

SELECT *
FROM transactions
ORDER BY transaction_amount DESC
LIMIT 5

Overview

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store