0% found this document useful (0 votes)
64 views23 pages

NextLeap SQL Cheat Sheet Compressed

This document is a comprehensive SQL cheat sheet designed for data analysts, covering essential SQL commands, functions, and operations including querying tables, filtering data, and performing joins. It also explains different SQL dialects, data definition language, and provides examples of various SQL functions like mathematical, string, and statistical functions. The cheat sheet serves as a quick reference guide for common SQL tasks and operations.

Uploaded by

Rishabh Mohan
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)
64 views23 pages

NextLeap SQL Cheat Sheet Compressed

This document is a comprehensive SQL cheat sheet designed for data analysts, covering essential SQL commands, functions, and operations including querying tables, filtering data, and performing joins. It also explains different SQL dialects, data definition language, and provides examples of various SQL functions like mathematical, string, and statistical functions. The cheat sheet serves as a quick reference guide for common SQL tasks and operations.

Uploaded by

Rishabh Mohan
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/ 23

SQL Cheat Sheet

NextLeap Data Analyst Fellowship


SQL
SQL, or Structured Query 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, SQL skills are
a must-have as they will regularly be working with data.

Different Dialects of SQL


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

● MySQL ● Oracle SQL ● PostgreSQL


● SQLite ● SQL Server

PostgreSQL is a good place to start as it is close to standard SQL syntax and can be easily adapted to other
dialects.

NextLeap Data Analyst Fellowship


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
SELECT product_id, product_name
the table 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;

NextLeap Data Analyst Fellowship


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 5. 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;

NextLeap Data Analyst Fellowship


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

NextLeap Data Analyst Fellowship


Filtering on Multiple Columns & Missing Data
1. Get all products in the 'Electronics' category 1. Return products where the description is missing
where the price is greater than $100 SELECT *
SELECT * FROM products
FROM products WHERE description IS NULL;
WHERE category = 'Electronics' AND price > 100;
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
SELECT * WHERE description IS NOT NULL;
FROM products
WHERE category = 'Books' OR price < 20;

NextLeap Data Analyst Fellowship


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;
SELECT price - discount AS discounted_price FROM
- Subtraction
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;

NextLeap Data Analyst Fellowship


String Concatenation
Operator Description Example
Concatenates strings in SQL SELECT first_name + ' ' + last_name AS full_name FROM
+
Server. customers;
Concatenates strings in PostGres SELECT first_name || ' ' || last_name AS full_name FROM
||
and Oracle SQL customers;

String Comparison
Operator Description Example
SELECT * FROM products WHERE product_name =
= Checks if two strings are equal.
'Laptop';
Checks if two strings are not SELECT * FROM products WHERE category <>
<> or !=
equal. 'Electronics';
Checks if a string matches a SELECT * FROM products WHERE product_name LIKE
LIKE
pattern using % and _. 'L%';
Checks if a string does not match SELECT * FROM products WHERE product_name NOT
NOT LIKE
a pattern. LIKE 'Sneak%';

NextLeap Data Analyst Fellowship


Logical Operators
Operator Description Example
Returns true if any condition SELECT * FROM products WHERE category = 'Electronics' OR
OR
separated by OR is true. price > 100;
Returns true if all conditions SELECT * FROM products WHERE category = 'Electronics' AND
AND
separated by AND are true. price > 100;
Reverses the meaning of the logical
NOT SELECT * FROM products WHERE NOT category = 'Electronics';
operator that follows it.
Returns true if a value matches any SELECT * FROM products WHERE category IN ('Electronics',
IN
value in a list. 'Clothing');
Returns true if a value is within a SELECT * FROM products WHERE price BETWEEN 100 AND
BETWEEN
range of values. 200;
Returns true if all subquery values SELECT * FROM products WHERE price > ALL (SELECT price
ALL
meet the condition. FROM products WHERE category = 'Electronics');
Returns true if any subquery value SELECT * FROM products WHERE price > ANY (SELECT price
ANY
meets the condition. FROM products WHERE category = 'Electronics');
Returns true if a subquery returns SELECT * FROM products p WHERE EXISTS (SELECT 1 FROM
EXISTS
one or more records. orders o WHERE o.product_id = p.product_id);

NextLeap Data Analyst Fellowship


Null Comparison and Handling
Operator
Description Example
/ Function
IS NULL Checks if a value is NULL. SELECT * FROM products WHERE product_name IS NULL;
SELECT * FROM products WHERE product_name IS NOT
IS NOT NULL Checks if a value is not NULL.
NULL;
Returns the first non-null expression SELECT COALESCE(product_name, 'N/A') AS product_name
COALESCE
in the list. FROM products;

NextLeap Data Analyst Fellowship


Mathematical Functions
Function Description Example
ABS(x) Absolute value of x SELECT ABS(-10); -- Result: 10
Smallest integer greater than or
CEILING(x) SELECT CEILING(5.25); -- Result: 6
equal to x
Largest integer less than or equal to
FLOOR(x) SELECT FLOOR(5.75); -- Result: 5
x
ROUND(x, d) Rounds x to d decimal places SELECT ROUND(5.678, 2); -- Result: 5.68
SQRT(x) Square root of x SELECT SQRT(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

NextLeap Data Analyst Fellowship


String Functions
Functions Description Example
Extracts a specified number of
LEFT() characters from the left side of a SELECT LEFT(product_name, 3) AS short_name FROM products;
string
Extracts a specified number of
SELECT RIGHT(product_name, 3) AS short_name FROM
RIGHT() characters from the right side of a
products;
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;
SELECT SUBSTRING(product_name, 1, 5) AS sub_name FROM
SUBSTRING() Extracts a substring from a string
products;
Removes leading and trailing spaces
TRIM() SELECT TRIM(description) AS trimmed_desc FROM products;
from a string
Finds the position of a substring
POSITION() SELECT POSITION('book' IN description) AS pos FROM products;
within a string

NextLeap Data Analyst Fellowship


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 GROUP p-th percentile of x (discrete)
score) FROM students;
(ORDER BY x)
PERCENTILE_CONT
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY
(p) WITHIN GROUP p-th percentile of x (continuous)
temperature) FROM weather_data;
(ORDER BY x)

NextLeap Data Analyst Fellowship


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
SELECT COUNT(price) whose average is above 3.0
FROM product; SELECT category, AVG(price)
FROM product
3. Count the number of unique category values GROUP BY category
SELECT COUNT(DISTINCT category) HAVING AVG(price) > 3.0;
FROM product;

4. Get the lowest and the highest product price


SELECT MIN(price), MAX(price)
FROM product;

NextLeap Data Analyst Fellowship


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,
product_name VARCHAR(100) NOT NULL, 6. DROP INDEX is used to delete an existing index.
price DECIMAL(10, 2), DROP INDEX idx_product_name;
category_id INT,
FOREIGN KEY (category_id) REFERENCES 7. CREATE VIEW is used to create a virtual table based on the result
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;

NextLeap Data Analyst Fellowship


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
UPDATE products
DELETE command
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');

NextLeap Data Analyst Fellowship


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 3. FULL OUTER JOIN returns all records when there is a
there is no match, the result is NULL from the right match in either left or right table records.
side. SELECT customers.customer_name, orders.order_id
SELECT customers.customer_name, orders.order_id FROM customers
FROM customers FULL OUTER JOIN orders ON customers.customer_id =
LEFT JOIN orders ON customers.customer_id = orders.customer_id;
orders.customer_id;

NextLeap Data Analyst Fellowship


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 CURRENT_DATE; SELECT CAST('2021-12-31 23:59:29+02' AS timestamp);

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

NextLeap Data Analyst Fellowship


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

EXTRACTING PARTS OF DATES GROUPING BY YEAR AND MONTH

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
SQL Server; FROM sales
GROUP BY year, month
NextLeap Data Analyst Fellowship ORDER BY year, month;
Date Time Functions
Function Description Example
Returns the current date (without
CURRENT_DATE SELECT CURRENT_DATE;
time) in the session's time zone.
Returns the current time (without
CURRENT_TIME SELECT CURRENT_TIME;
date) in the session's time zone.
Returns the current date and time
CURRENT_TIMESTAMP (with fractional seconds) in the SELECT CURRENT_TIMESTAMP;
session's time zone.
Returns the current date and time in
LOCALTIMESTAMP SELECT LOCALTIMESTAMP;
the session's time zone.
NOW() Returns the current date and time. SELECT NOW();
Converts a timestamp to a specified SELECT TIMEZONE('America/New_York', TIMESTAMP '2024-07-14
TIMEZONE
time zone. 12:00:00');
Returns the time zone offset of a SELECT TIMEZONE_OFFSET('America/Los_Angeles', TIMESTAMP
TIMEZONE_OFFSET
given timestamp. '2024-07-14 12:00:00');
CURRENT_TIMEZONE Returns the current time zone. SELECT CURRENT_TIMEZONE();

NextLeap Data Analyst Fellowship


Date Time Manipulation Functions
Function Description Example
Extracts a specific part (year, month, day,
DATE_PART hour, minute, second, etc.) from a date or SELECT DATE_PART('year', '2024-07-14');
timestamp.
Similar to DATE_PART, extracts a specific
EXTRACT SELECT EXTRACT(YEAR FROM '2024-07-14');
part of a date or timestamp.
Adds or subtracts a specified interval
DATE_ADD /
(years, months, days, etc.) from a date or SELECT DATE_ADD('2024-07-14', INTERVAL 1 MONTH);
DATE_SUB
timestamp.
Calculates the difference between two
DATE_DIFF SELECT DATE_DIFF('2024-07-14', '2024-06-14');
dates or timestamps.
Truncates a date or timestamp to a SELECT DATE_TRUNC('hour', TIMESTAMP '2024-07-14
DATE_TRUNC
specified precision (hour, day, week, etc.). 12:34:56');
Converts a date or timestamp to a SELECT TO_CHAR(TIMESTAMP '2024-07-14 12:34:56',
TO_CHAR
specific string format. 'YYYY-MM-DD HH24:MI:SS');
Converts a string into a date using a
TO_DATE SELECT TO_DATE('2024-07-14', 'YYYY-MM-DD');
specified format.

NextLeap Data Analyst Fellowship


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'
4. Ranking Functions : Rank products by price:
END AS price_category
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 SELECT date, amount,
WHEN price > 150 THEN 'Premium' SUM(amount) OVER(ORDER BY date) AS running_total
WHEN price > 100 THEN 'Mid-range' FROM sales;
ELSE 'Standard'
END AS price_category, 6. Moving Averages : Calculate a moving average of stock
COUNT(*) AS products prices:
FROM product
SELECT date, price,
GROUP BY price_category; AVG(price) OVER(ORDER BY date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
AS moving_average
NextLeap Data Analyst Fellowship FROM stock_prices;
Some Useful Links
1. NextLeap Data Analytics Fellowship

NextLeap Data Analyst Fellowship

You might also like