0% found this document useful (0 votes)
9 views

SQL_Cheat_Sheet_DS

Uploaded by

akcinark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

SQL_Cheat_Sheet_DS

Uploaded by

akcinark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

SQL Cheat Sheet

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.

Different Dialects of SQL


Although SǪL languages all share a basic structure, some specific commands and styles can
differ slightly. Popular dialects include:

● MySQL ● Oracle SQL ● PostgreSQL


● SQLite ● SQL Server

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

1. Get all products in the 'Electronics' category


where the price is greater than $100 1. Return products where the description is missing
SELECT * SELECT *
FROM products FROM products
WHERE category = 'Electronics' AND price > 100; WHERE description IS NULL;

2. Return products where the description is not missing


2. Get all products in the 'Books' category or SELECT *
products priced below $20 FROM products
WHERE description IS NOT NULL;
SELECT *
FROM products
WHERE category = 'Books' OR price < 20;
Comparison & Arithmetic Operators
Operator Description Example
= Equal to SELECT * FROM products WHERE price = 100;
<> or != Not equal to SELECT * FROM products WHERE category != 'Books';
< Less than SELECT * FROM products WHERE price < 50;
> Greater than SELECT * FROM products WHERE price > 50;
<= Less than or equal to SELECT * FROM products WHERE price <= 100;
>= Greater than or equal to SELECT * FROM products WHERE price >= 100;

Operator Description Example


+ Addition SELECT price + tax AS total_price FROM products;
- Subtraction SELECT price - discount AS discounted_price
FROM products;
* Multiplication SELECT price * quantity AS total_cost FROM sales;
/ Division SELECT total_cost / quantity AS unit_price FROM sales;
% Modulus (remainder of a division) SELECT product_id, quantity % 2 AS remainder FROM sales;
String Concatenation
Operator Description Example
+ Concatenates strings in SELECT first_name + ' ' + last_name AS full_name
SǪL Server. FROM customers;
|| Concatenates strings in SELECT first_name || ' ' || last_name AS full_name
PostGres and Oracle SǪL FROM customers;

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

EXP(x) Exponential function e^x SELECT EXP(1); - - Result: 2.718


LOG(x) Natural logarithm of x SELECT LOG(10); - - Result: 2.302
LOG10(x) Base-10 logarithm of x SELECT LOG10(100); - - Result: 2
RAND() Random float between 0 and 1 SELECT RAND(); - - Result: 0.12345 (example)
PI() Value of pi (3.141592653589793) SELECT PI(); - - Result: 3.141592653589793
String Functions
Functions Description Example
Extracts a specified number of
LEFT() characters from the left side of SELECT LEFT(product_name, 3) AS short_name FROM products;
a string
Extracts a specified number of SELECT RIGHT(product_name, 3) AS short_name
RIGHT() characters from the right side of FROM products;
a string
LENGTH() Returns the length of a string SELECT LENGTH(description) AS desc_length FROM products;
UPPER() Converts a string to uppercase SELECT UPPER(product_name) AS upper_name FROM products;
LOWER() Converts a string to lowercase SELECT LOWER(product_name) AS lower_name FROM products;
SUBSTRING() Extracts a substring from a string SELECT SUBSTRING(product_name, 1, 5) AS sub_name
FROM products;
TRIM() Removes leading and trailing spaces SELECT TRIM(description) AS trimmed_desc FROM products;
from a string
POSITION() Finds the position of a SELECT POSITION('book' IN description) AS pos FROM products;
substring within a string
Statistical Functions
Function Description Example
AVG(x) Average value of x SELECT AVG(salary) FROM employees;
SUM(x) Sum of values in x SELECT SUM(sales_amount) FROM orders;
MIN(x) Minimum value in x SELECT MIN(product_price) FROM products;
MAX(x) Maximum value in x SELECT MAX(temperature) FROM weather_data;
COUNT(x) Number of rows where x is not null SELECT COUNT(customer_id) FROM customers;
COUNT(*) Number of rows in the result set SELECT COUNT(*) FROM products;
VAR_POP(x) Population variance of x SELECT VAR_POP(sales_amount) FROM orders;
VAR_SAMP(x) Sample variance of x SELECT VAR_SAMP(sales_amount) FROM orders;
STDDEV_POP(x) Population standard deviation of x SELECT STDDEV_POP(sales_amount) FROM orders;
STDDEV_SAMP(x) Sample standard deviation of x SELECT STDDEV_SAMP(sales_amount) FROM orders;
PERCENTILE_DISC( SELECT PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY
p) WITHIN p - t h percentile of x (discrete) score) FROM students;
GROUP (ORDER
BY x)
PERCENTILE_CONT SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY
(p) WITHIN p - t h percentile of x (continuous) temperature) FROM weather_data;
GROUP (ORDER
BY x)
Grouping and Aggregation
1. Count the number of products 5. Find the total price of products for each category
SELECT COUNT(*) SELECT category, SUM(price)
FROM product; FROM product
GROUP BY category;
2. Count the number of products with non-null
prices 6.Find the average price of products for each category
whose average is above 3.0
SELECT COUNT(price)
FROM product; SELECT category, AVG(price)
FROM product
3. Count the number of unique category values GROUP BY category
HAVING AVG(price) > 3.0;
SELECT COUNT(DISTINCT category)
FROM product;

4. Get the lowest and the highest product price


SELECT MIN(price), MAX(price)
FROM product;
Data Definition Language
1. CREATE TABLE is used to create a new table in 5. CREATE INDEX is used to create an index on a table.
the database CREATE INDEX idx_product_name ON
CREATE TABLE products products(product_name);
( product_id INT PRIMARY
KEY, 6. DROP INDEX is used to delete an existing index.
product_name VARCHAR(100) NOT NULL, DROP INDEX idx_product_name;
price DECIMAL(10, 2),
category_id INT, 7. CREATE VIEW is used to create a virtual table based on the result
FOREIGN KEY (category_id) REFERENCES
categories(category_id) set of a SELECT statement.
); CREATE VIEW expensive_products AS
SELECT * FROM products
2. ALTER TABLE is used to modify an existing table WHERE price > 100;
(e.g., add columns, modify columns, add
constraints). 8. DROP VIEW is used to delete a view from the database.
ALTER TABLE products DROP VIEW expensive_products;
ADD stock_quantity INT;

3. DROP TABLE is used to delete a table and its


data from the database).
DROP TABLE products;
Insert, Update and Delete
1. INSERT command: To insert data into a table 3. UPDATE To update the data in a table, use the UPDATE
INSERT INTO category command.
VALUES - - Update using direct value assignment
(1, 'Home and Kitchen'), UPDATE category
(2, 'Clothing and Apparel'); SET is_active = true, name = 'Office'
WHERE name = 'Ofice';
You may specify the columns to which the data is
added. The remaining columns are filled with - - Update using arithmetic operations
predefined default values or NULLs. UPDATE products
INSERT INTO category (name) SET price = price * 1.1
VALUES ('Electronics'); WHERE category_id = 2;

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.

● Date is expressed using a year, month, and day (YYYY-mm-dd).


● Time is expressed using a 24-hour clock (HH:MM).
● Timestamp includes both date and time, optionally with timezone offset.

CURRENT DATE AND TIME CREATING DATE AND TIME VALUES

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;

Get the timestamp with the current date and time:


SELECT CURRENT_TIMESTAMP; Be explicit with hours in time values to avoid ambiguity:
SELECT CAST('00:15:31.124769' AS time);
Working with Date Time
SORTING CHRONOLOGICALLY COMPARING DATE AND TIME VALUES

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';

GROUPING BY YEAR AND MONTH


EXTRACTING PARTS OF DATES

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;

You might also like