Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
132 views

SQL-cheatsheet

SQL-cheatsheet

Uploaded by

ritesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
132 views

SQL-cheatsheet

SQL-cheatsheet

Uploaded by

ritesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

SQL Interview Cheat Sheet DataLemur.

com
SAMPLE DATA AGGREGATION AND GROUPING
customers Table: orders
GROUP BY groups together rows with the same value in specified columns, and then
id name age city country has_subscription order_id cus_id cost computes summaries (aggregates) for each group of values.

1 Adam 58 New York USA TRUE 105 4 300.00


SELECT cus_id,
2 Bella NULL Tijuana Mexico FALSE 106 2 150.00 SUM(cost) as sum_cost,
COUNT(order_id) as count_id,
3 Chetan 36 New Delhi India TRUE 107 1 200.00 MAX(cost) as max_cost, orders
ROUND(AVG(cost),2) as avg_cost
108 2 150.00 FROM orders cus_id sum_cost count_id max_cost avg_cost
orders Table: GROUP BY cus_id
109 1 75.50 ORDER BY cus_id; 1 376.25 3 200.00 125.42
order_id cus_id date cost discount status
110 4 100.00 2 300.00 2 150.00 150.00
101 1 2023-04-05 300.00 0.00 Delivered 4 400.00 2 300.00 200.00
111 1 100.75
102 2 2023-10-02 400.00 0.00 Shipped

103 2 2024-11-19 100.00 25.35 TBD

999 NULL 2027-06-16 1200 0.00 TBD


WINDOW FUNCTIONS
Compute their result based on a sliding window frame,
a set of rows that somehow relate to the current row.

QUERYING TABLES WITH SELECT Unbounded


Preceding

Current Row
Fetch all columns from the customers table: Find the discount percentage for all orders: AGGREGATE RANKING VALUE
AVG() ROW_NUMBER() LAG()
SELECT *
SELECT discount/cost * 100 MAX() RANK() LEAD()
FROM customer;
FROM orders; MIN() DESNE_RANK() FIRST_VALUE() Unbounded
Fetch name and age columns for all customers: Round the discount percentage to 2 decimal places: SUM() PERCENT_RANK() LAST_VALUE() Following
COUNT() NTILE() NTH_VALUE()
SELECT name, age SELECT ROUND(discount/cost * 100, 2)
FROM customers; FROM orders;
PARTITION BY ORDER BY
Sort Output Using ORDER BY Aliases
Divides rows into multiple groups, called partitions, to Specifies the order of rows in each partition to which
Sort customers by age in the default ASCending order: AS is used to rename columns: which the window function is applied. the window function is applied.
SELECT * SELECT cost * 0.04 AS sales_tax SELECT order_id, cus_id, cost,
FROM customers SELECT order_id, cus_id, cost, SUM(cost) OVER (PARTITION BY cus_Id ORDER BY cost ASC)
FROM orders; SUM(cost) OVER (PARTITION BY cus_id) AS sum_cost
ORDER BY age ASC; AS sum_cost
FROM orders; FROM orders;
Sort customers by age in DESCending order (high to low): AS is also used to rename tables:
order_id cus_id cost sum_cost order_id cus_id cost sum_cost
SELECT * SELECT cus.name, cus.age
FROM customers FROM customers AS cus; 107 1 200.00 376.25 109 1 75.50 376.25
ORDER BY age DESC;
109 1 75.50 376.25 111 1 100.75 376.25

FILTERING OUTPUT WITH WHERE 111 1 100.75 376.25 107 1 200.00 376.25

106 2 150.00 300.00


Comparison Operators Filter Text With LIKE 106 2 150.00 300.00
108 2 150.00 300.00 108 2 150.00 300.00
Fetch customers who are over the age of 35: Fetch customers who live in a city that starts with “New”:
SELECT * 105 4 300.00 400.00 110 4 100.00 400.00
FROM customers SELECT *
FROM customers 110 4 100.00 400.00 105 4 300.00 400.00
WHERE age > 35;
WHERE city LIKE ‘New%’;
Fetch customers that live in either USA OR Canada
Fetch customers whose city ends in ‘e’ or the 2nd letter Default Partition: with no PARTITION BY clause, the Default ORDER BY: with no ORDER BY clause, the
AND also have a subscription:
is ‘r’ or the name contains the letter ‘x’ anywhere: entire result set is the partition. order of rows within each partition is arbitrary
SELECT *
FROM customers SELECT *
FROM customers
RANK Window Function Example LAG Year-over-Year Example
WHERE (country = ‘USA’ OR country = ‘Canada’)
AND has_subscription = TRUE; WHERE city LIKE ‘%e’ The RANK() function is used to assign ranks to rows The LAG() function is used to access data from a previous
OR city LIKE ‘_r%’
based on values in the specified column. row in the same result set without needing a self-join. Often
OR city LIKE ‘%x%’;
BETWEEN and IN used for Year-over-Year or Month-over-Month calculations.
order_id cost order_rank
Fetch the status of orders that have a cost NOT and NULLs SELECT order_id, cost,
RANK() OVER ( SELECT YEAR(date) AS year,
105 300.00 1
between 100-200: Fetch customers that are not missing a value for age: ORDER BY cost DESC SUM(cost) AS cur_sales,
SELECT name ) 107 200.00 2 LAG(SUM(cost)) OVER (
SELECT status
FROM customers AS order_rank ORDER BY YEAR(date) year cur_sales last_year_sales
FROM orders
FROM orders; 106 150.00 3
WHERE TotalCost BETWEEN 100 AND 200; WHERE age IS NOT NULL; )
2023 700.00 NULL
108 150.00 3 AS last_year_sales
Fetch customers that aren’t USA minors (no diddy): FROM orders
Fetch customers that live in North America: 2024 300.00 700.00
SELECT name GROUP BY YEAR(date)
SELECT name Practice real Google RANK SQL Interview Question: 2025 450.00 300.00
FROM customers ORDER BY YEAR(date);
FROM customers WHERE NOT (age < 18 AND country = 'USA') datalemur.com/questions/odd-even-measurements
WHERE country IN (‘USA’, ‘Canada’, ‘Mexico’);

COMBINING MULTIPLE TABLES WITH JOINS SUBQUERIES CTEs


A subquery is a query that is nested inside another Common Table Expressions (CTEs) are temporary result sets
INNER JOIN FULL JOIN that you can reference within a query. CTEs improve query
query, or inside another subquery.
JOIN (or explicitly INNER JOIN) returns rows that have FULL JOIN (or explicitly FULL OUTER JOIN) returns all readability and are often used to simplify complex queries by
matching values in both tables. rows from both tables - if there’s no matching row Single Value Subqueries breaking them into smaller, manageable parts.
SELECT orders.order_id, orders.cus_id, in the second table, NULLs are returned.
The simplest subquery returns exactly one column and
customers.id, customers.name
SELECT orders.order_id, orders.cost, This query calculates the total sales per customer and then
FROM orders exactly one row. It can be used with comparison
customers.id, customers.name filters customers with total sales above 350.
INNER JOIN customers
FROM orders operators (=, <, >, <=, or >=)
ON orders.cus_id = customers.id; WITH sum_sales AS (
FULL OUTER JOIN customers
This query finds all orders that cost more than the SELECT cus_id, SUM(cost) AS tot_sales
ON orders.cus_id = customers.id;
order_id cus_id id name average order. FROM orders
SELECT order_id GROUP BY cus_id)
101 1 1 Adam order_id cost id name
FROM orders SELECT cus_id, tot_sales cus_id tot_sales
102 2 2 Bella 101 300 1 Adam WHERE cost > ( FROM sum_sales 4 400.00
102 400 2 Bella SELECT AVG(cost) WHERE tot_sales > 350;
103 2 2 Bella
FROM orders
103 100 2 Bella );
LEFT JOIN 999 1200 NULL NULL Multiple Value Subqueries SET OPERATIONS
LEFT JOIN returns all rows from the left table with NULL NULL 3 Chetan A subquery can also return multiple columns or multiple Set operations are used to combine the results of two or
corresponding rows from the right table. If no matched rows. Such subqueries can be used with operators: more queries/tables into a single result.
row, NULLs are returned as values for the 2nd table. Practice real Meta Full Join SQL Interview Question: IN, EXISTS, ANY, or ALL UNION combines the results and removes duplicates.
datalemur.com/questions/updated-status
SELECT customers.name, orders.date, orders.cost
This query finds all orders made by USA customers: UNION ALL doesn’t remove duplicate rows
FROM customers
LEFT JOIN orders
RIGHT JOIN SELECT order_id
actors singers
FROM orders
ON customers.id = orders.cus_id;
RIGHT JOIN returns all rows from the right table with WHERE cus_id = ANY ( id name country id name country
name date cost corresponding rows from the left table. SELECT id as cus_id
FROM customers 1 Ryan Gosling Canada 1 Drake Canada
If there’s no matching row, NULLs are returned as values
Adam 2023-04-05 300.00 WHERE country = USA);
from the left table. 2 Drake Canada 2 Badshah India

CASE STATEMENTS
Bella 2023-10-02 400.00
SELECT orders.order_id, customers.name 3 Emma Stone USA 3 Justin Bieber Canada
Bella 2024-11-19 100.00 FROM orders
RIGHT JOIN customers id name country
Chetan NULL NULL
ON orders.cus_id = customers.id;
CASE goes through a list of conditions and returns a SELECT name
value when the first condition is met. FROM actors
1 Ryan Gosling Canada
WHERE country = ‘Canada’
CROSS JOIN SELF JOIN If no conditions are true it returns the value in the UNION ALL 2 Drake Canada
ELSE clause. SELECT name
CROSS JOIN returns all possible combinations or rows SELF JOIN is used to join a table with itself to compare 1 Drake Canada
SELECT order_id, cus_id, cost, FROM singers
from both tables. It doesn’t have a join condition! rows within the same table. It’s typically used with an alias WHERE country = ‘Canada’;
CASE 3 Justin Bieber Canada
to differentiate the table instances. WHEN cost > 175 THEN 'luxury'
SELECT orders.order_id, customers.name
SELECT A.cus_id, A.order_id AS ord_1, A.date AS WHEN cost > 100 THEN 'mid-tier'
FROM orders Practice real Amazon UNION SQL Interview Question:
CROSS JOIN customers; date_1, B.order_id AS ord_2, B.date AS date_2 ELSE 'budget' END AS product_type
FROM orders; datalemur.com/questions/prime-warehouse-storage
FROM orders A
JOIN orders B ON A.cus_id = B.cus_id

OTHER SQL COMMANDS


order_id name
AND A.order_id != B.order_id; order_id cus_id cost product_type
101 Adam
107 1 200.00 luxury
cus_id ord_1 date_1 ord_2 date_2 LENGTH(): Returns the length of the provided string.
101 Bella
109 1 75.50 budget CAST(): Converts an expression into the specified data type.
2 102 2023-10-02 103 2024-11-19
101 Chetan 111 1 100.75 mid-tier NOW(): Returns the current date and time.
102 Adam 2 103 2024-11-19 102 2023-10-02 CEILING(): Rounds up to the nearest integer.
106 2 150.00 mid-tier
FLOOR(): Rounds down to the nearest integer.
102 Bella
Practice real Amazon Self-Join SQL Interview Question: 108 2 150.00 mid-tier TRIM(): Removes spaces from both or one side of a string.
102 Chetan datalemur.com/questions/amazon-shopping-spree CONCAT(): Combines multiple strings.
105 4 300.00 luxury
COALESCE(): Returns the first non-NULL value.

Practice 200+ FAANG SQL Interview Questions for FREE: DataLemur.com/questions


Learn SQL with 30 Interactive SQL Lessons for FREE: DataLemur.com/sql-tutorial

You might also like