SQL_Cheat_Sheet_DS
SQL_Cheat_Sheet_DS
SQL
SǪL, or Structured Ǫuery Language, is a way we talk to databases. It's like a tool that helps us ask for
specific information and put together detailed reports. For Data Analysts, SǪL skills are a must-have as
they will regularly be working with data.
PostgreSǪL is a good place to start as it is close to standard SǪL syntax and can be easily adapted to other
dialects.
Querying Tables
1. Get all the columns from a table 5. Get the product_id, product_name, ordered by
SELECT * FROM quantity in stock
product; SELECT product_id, product_name
FROM product
2. Get the product_name column from the table ORDER BY quantity_in_stock ASC;
SELECT product_name
FROM product; 6.Get the product_id, product_name, ordered by
quantity in stock in descending order
3.Get the product_name and price columns from
the table SELECT product_id, product_name
FROM product
SELECT product_name, price ORDER BY quantity_in_stock DESC;
FROM product;
7. Get a unique list of product categories
4. Get the first 5 rows
SELECT DISTINCT category
SELECT * FROM product;
FROM product
LIMIT 5;
Filtering on Numeric Columns
1. Get all the products where price is more or equal to 4. Get all the products where price is lower or equal to
$50 $50
SELECT * SELECT *
FROM product FROM product
WHERE price >= 50; WHERE price <= 50;
2. Get all the products where price is more than $50 5. Get all the products where price is lower than $50
SELECT * SELECT *
FROM product FROM product
WHERE price > 50; WHERE price < 50;
3. Get all the products where price is exactly equal to 6. Get all the products where price is between $30 and
$50 $60
SELECT * SELECT *
FROM product FROM product
WHERE price = 50; WHERE price BETWEEN 30 AND 60;
Filtering on Text Columns
1. Get all the products with category 4. Fetch names of products that start with a 'P' or end
'Electronics' with an 's':
SELECT * SELECT name
FROM product FROM product
WHERE category = 'Electronics'; WHERE name LIKE 'P%' OR name LIKE '%s';
2. Get the products from the USA and France 5. Fetch names of products that start with any letter
SELECT * followed by 'rain' (like 'train' or 'grain')
FROM product SELECT name
WHERE origin_country IN ('USA', 'France'); FROM product
WHERE name LIKE '_rain';
3. Fetch names of products that are not
watches:
SELECT name
FROM product
WHERE name != 'watch';
Filtering on Multiple Columns & Missing Data
String Comparison
Operator Description Example
= Checks if two strings are equal. SELECT * FROM products WHERE product_name
= 'Laptop';
<> or != Checks if two strings are SELECT * FROM products WHERE category
not equal. <> 'Electronics';
LIKE Checks if a string matches a SELECT * FROM products WHERE product_name LIKE
pattern using % and _. 'L%';
NOT LIKE Checks if a string does not SELECT * FROM products WHERE product_name
match a pattern. NOT LIKE 'Sneak%';
Logical Operators
Operator Description Example
OR Returns true if any SELECT * FROM products WHERE category = 'Electronics'
condition separated by OR OR price > 100;
is true.
AND Returns true if all SELECT * FROM products WHERE category = 'Electronics'
conditions separated by AND price > 100;
AND are true.
NOT Reverses the meaning of the logical SELECT * FROM products WHERE NOT category = 'Electronics';
operator that follows it.
IN Returns true if a value matches SELECT * FROM products WHERE category IN
any value in a list. ('Electronics', 'Clothing');
BETWEEN Returns true if a value is within a SELECT * FROM products WHERE price BETWEEN 100 AND
range of values. 200;
ALL Returns true if all subquery SELECT * FROM products WHERE price > ALL (SELECT
values meet the condition. price FROM products WHERE category = 'Electronics');
ANY Returns true if any subquery SELECT * FROM products WHERE price > ANY (SELECT
value meets the condition. price FROM products WHERE category = 'Electronics');
EXISTS Returns true if a subquery returns SELECT * FROM products p WHERE EXISTS (SELECT 1FROM
one or more records. orders o WHERE o.product_id = p.product_id);
Null Comparison and Handling
Operator Description Example
/ Function
IS NULL Checks if a value is NULL. SELECT * FROM products WHERE product_name IS NULL;
IS NOT NULL Checks if a value is not NULL. SELECT * FROM products WHERE product_name IS
NOT NULL;
COALESCE Returns the first non-null expression SELECT COALESCE(product_name, 'N/A') AS product_name
in the list. FROM products;
Mathematical Functions
Function Description Example
ABS(x) Absolute value of x SELECT ABS(-10); - - Result: 10
CEILING(x) Smallest integer greater than SELECT CEILING(5.25); - - Result: 6
or equal to x
FLOOR(x) Largest integer less than or equal to SELECT FLOOR(5.75); - - Result: 5
x
ROUND(x, d) Rounds x to d decimal places SELECT ROUND(5.678, 2); - - Result: 5.68
SǪRT(x) Square root of x SELECT SǪRT(25); - - Result: 5
POWER(x, y) x raised to the power of y SELECT POWER(2, 3); - - Result: 8
2. DELETE: To delete data from a table, use the - - Update using subquery
DELETE command UPDATE products
SET category_id = (SELECT category_id FROM categories
DELETE FROM category WHERE category_name = 'Electronics')
WHERE category_id = (SELECT category_id FROM categories
WHERE name IS NULL; WHERE category_name = 'Computers');
Joins
1. INNER JOIN returns records that have matching 3. RIGHT JOIN returns all records from the right table and the
values in both tables matched records from the left table. If there is no match, the
SELECT orders.order_id, customers.customer_name result is NULL from the left side.
FROM orders SELECT orders.order_id, customers.customer_name
INNER JOIN customers ON orders.customer_id = FROM orders
customers.customer_id; RIGHT JOIN customers ON orders.customer_id =
customers.customer_id;
2. LEFT JOIN returns all records from the left table
and the matched records from the right table. If 4. FULL OUTER JOIN returns all records when there is a match in
there is no match, the result is NULL from the right either left or right table records.
side. SELECT customers.customer_name, orders.order_id FROM
SELECT customers.customer_name, orders.order_id customers
FROM customers FULL OUTER JOIN orders ON customers.customer_id =
LEFT JOIN orders ON customers.customer_id = orders.customer_id;
orders.customer_id;
Date & Time
There are 3 main time-related types: date, time, and timestamp.
Find out what time it is: To create a date, time, or timestamp, write the value as a
SELECT CURRENT_TIME; string and cast it to the proper type.
SELECT CAST('2021-12-31' AS date);
Get today's date: SELECT CAST('15:31' AS time);
SELECT CAST('2021-12-31 23:59:29+02' AS timestamp);
SELECT CURRENT_DATE;
Using ORDER BY on date and time columns sorts rows Use comparison operators <, <=, >, >=, and = to compare date
chronologically from the oldest to the most recent: and time values:
SELECT order_date, product, quantity SELECT order_date, product, quantity
FROM sales FROM sales
ORDER BY order_date; ORDER BY order_date; - - Find sales made in July 2023:
Use DESC to sort from the most recent to the oldest --Find customers who registered in July 2023:
SELECT order_date, product, quantity SELECT order_date, product_name, quantity
FROM sales FROM sales
ORDER BY order_date DESC; WHERE order_date >= '2023-07-01'
AND order_date < '2023-08-01';
Use EXTRACT() or DATEPART() to get specific parts of a Find the count of sales by month:
date: SELECT EXTRACT(YEAR FROM order_date) AS year,
SELECT EXTRACT(YEAR FROM order_date) FROM sales; EXTRACT(MONTH FROM order_date) AS month,
SELECT DATEPART(YEAR, order_date) FROM sales; - - For COUNT(*) AS count
SǪL Server; FROM sales
GROUP BY year, month
ORDER BY year, month;
Date Time Functions
Function Description Example
CURRENT_DATE Returns the current date SELECT CURRENT_DATE;
(without time) in the session's
time zone.
CURRENT_TIME Returns the current time SELECT CURRENT_TIME;
(without date) in the session's
time zone.
Returns the current date and time
CURRENT_TIMESTAMP (with fractional seconds) in SELECT CURRENT_TIMESTAMP;
the session's time zone.
LOCALTIMESTAMP Returns the current date and time SELECT LOCALTIMESTAMP;
in the session's time zone.
NOW() Returns the current date and time. SELECT NOW();
TIMEZONE Converts a timestamp to a SELECT TIMEZONE('America/New_York', TIMESTAMP
specified time zone. '2024-07-14 12:00:00');
TIMEZONE_OFFSET Returns the time zone offset of a SELECT TIMEZONE_OFFSET('America/Los_Angeles', TIMESTAMP
given timestamp. '2024-07-14 12:00:00');
CURRENT_TIMEZONE Returns the current time zone. SELECT CURRENT_TIMEZONE();
Date Time Manipulation Functions
Function Description Example
Extracts a specific part (year, month, day,
DATE_PART hour, minute, second, etc.) from a date SELECT DATE_PART('year', '2024-07-14');
or timestamp.
EXTRACT Similar to DATE_PART, extracts a SELECT EXTRACT(YEAR FROM '2024-07-14');
specific part of a date or timestamp.
DATE_ADD Adds or subtracts a specified interval
/ (years, months, days, etc.) from a date SELECT DATE_ADD('2024-07-14', INTERVAL 1 MONTH);
DATE_SUB or timestamp.
DATE_DIFF Calculates the difference between SELECT DATE_DIFF('2024-07-14', '2024-06-14');
two dates or timestamps.
DATE_TRUNC Truncates a date or timestamp to a SELECT DATE_TRUNC('hour', TIMESTAMP '2024-07-14
specified precision (hour, day, week, etc.). 12:34:56');
TO_CHAR Converts a date or timestamp to SELECT TO_CHAR(TIMESTAMP '2024-07-14
a specific string format. 12:34:56', 'YYYY-MM-DD HH24:MI:SS');
TO_DATE Converts a string into a date using a SELECT TO_DATE('2024-07-14', 'YYYY-MM-DD');
specified format.
Data Manipulation
1. CASE WHEN lets you pass conditions and returns 3. Window functions compute their results based on a sliding
values based on those conditions: window frame, useful for analytics
SELECT name, SELECT product, brand, profit,
CASE (100.0 * profit / SUM(profit) OVER(PARTITION BY brand)) AS
WHEN price > 150 THEN 'Premium' percent_total
WHEN price > 100 THEN 'Mid-range' FROM sales;
ELSE 'Standard'
END AS price_category 4. Ranking Functions : Rank products by price:
FROM product;
SELECT RANK() OVER(ORDER BY price),
name
2. Use CASE WHEN with GROUP BY to compute FROM product;
categorized statistics:
5. Running Total : Calculate a running total of sales amounts:
SELECT CASE
WHEN price > 150 THEN 'Premium' SELECT date, amount,
SUM(amount) OVER(ORDER BY date) AS running_total
WHEN price > 100 THEN 'Mid-range'
FROM sales;
ELSE 'Standard'
END AS price_category,
COUNT(*) AS products 6. Moving Averages : Calculate a moving average of stock
FROM product prices:
GROUP BY price_category; SELECT date, price,
AVG(price) OVER(ORDER BY date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
AS moving_average
FROM stock_prices;