Data Analytics
111K subscribers
202 photos
2 files
921 links
Perfect channel to learn Data Analytics

Learn SQL, Python, Alteryx, Tableau, Power BI and many more

For Promotions: @coderfun @love_data
Download Telegram
This produces a compact business summary.

For example:

Total_Sales: 15,000,000, Average_Sales: 75,000, Minimum_Sales: 1,000, Maximum_Sales: 500,000, Total_Orders: 200

๐Ÿ”Ÿ Why Do We Need GROUP BY?

Aggregate functions give you an overall summary.

But what if the business asks:



"What are total sales for each region?"



You need to divide the data into groups.

That's what GROUP BY does.

1๏ธโƒฃ1๏ธโƒฃ Basic GROUP BY

Suppose:

North: 50,000 and 70,000 โ†’ Total 120,000

South: 40,000 and 60,000 โ†’ Total 100,000

West: 80,000 โ†’ Total 80,000

Query:

SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region;


Result:

North = 120,000, South = 100,000, West = 80,000

Now you've answered:



"How much did each region sell?"



1๏ธโƒฃ2๏ธโƒฃ GROUP BY Department

Suppose you have:

John - IT - 75,000

Sarah - HR - 60,000

Mike - IT - 82,000

David - Finance - 90,000

Alice - HR - 65,000

Query:

SELECT
Department,
AVG(Salary) AS Average_Salary
FROM Employees
GROUP BY Department;


Result:

Finance: 90,000, HR: 62,500, IT: 78,500

1๏ธโƒฃ3๏ธโƒฃ GROUP BY with COUNT()

Question:



How many employees are in each department?



SELECT
Department,
COUNT(*) AS Employee_Count
FROM Employees
GROUP BY Department;


Result:

IT: 2, HR: 2, Finance: 1

1๏ธโƒฃ4๏ธโƒฃ GROUP BY with Multiple Columns

You can group by more than one column.

Suppose your sales data contains:

North Electronics: 80,000

North Furniture: 40,000

South Electronics: 70,000

South Furniture: 50,000

Query:

SELECT
Region,
Category,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region, Category;


Result:

North Electronics = 80,000, North Furniture = 40,000, South Electronics = 70,000, South Furniture = 50,000

This lets you analyze combinations of dimensions.

1๏ธโƒฃ5๏ธโƒฃ GROUP BY vs PivotTable

This is an important connection.

In Excel:

Region โ†’ Rows

Sales โ†’ Values

In SQL:

SELECT
Region,
SUM(Sales)
FROM Orders
GROUP BY Region;


The analytical concept is very similar.

You're grouping records and calculating an aggregate.

1๏ธโƒฃ6๏ธโƒฃ HAVING

Now suppose you want:



"Show only regions where total sales are greater than โ‚น100,000."



You can't simply use WHERE on the aggregate result.

You use: HAVING

SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region
HAVING SUM(Sales) > 100000;


Result:

North = 120,000

1๏ธโƒฃ7๏ธโƒฃ WHERE vs HAVING

This is a very common SQL interview question.

WHERE

Filters individual rows before grouping.

Example:

SELECT *
FROM Orders
WHERE Region = 'North';


HAVING

Filters groups after aggregation.

Example:

SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region
HAVING SUM(Sales) > 100000;


Remember:



WHERE โ†’ Filter rows

HAVING โ†’ Filter groups



1๏ธโƒฃ8๏ธโƒฃ WHERE + GROUP BY + HAVING

You can use all three.

Question:



Find regions where 2026 sales exceed โ‚น100,000.



Conceptually:

SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
WHERE Order_Date >= '2026-01-01'
AND Order_Date < '2027-01-01'
GROUP BY Region
HAVING SUM(Sales) > 100000;
โค4
Learning this structure will make many analytical SQL problems much easier.

๐Ÿงช Practical Interview Challenge

Suppose you have Orders with:

1001 North Electronics 80,000

1002 North Furniture 40,000

1003 South Electronics 70,000

1004 South Furniture 50,000

1005 North Electronics 60,000

Q1. Find total sales.

SELECT SUM(Sales) AS Total_Sales FROM Orders;


Q2. Find average sales.

SELECT AVG(Sales) AS Average_Sales FROM Orders;


Q3. Find sales by region.

SELECT Region, SUM(Sales) AS Total_Sales FROM Orders GROUP BY Region;


Q4. Count orders by region.

SELECT Region, COUNT(*) AS Order_Count FROM Orders GROUP BY Region;


Q5. Find average sales by category.

SELECT Category, AVG(Sales) AS Average_Sales FROM Orders GROUP BY Category;


Q6. Show only regions with sales greater than โ‚น100,000.

SELECT Region, SUM(Sales) AS Total_Sales FROM Orders GROUP BY Region HAVING SUM(Sales) > 100000;


Q7. Sort regions by highest sales.

SELECT Region, SUM(Sales) AS Total_Sales FROM Orders GROUP BY Region ORDER BY Total_Sales DESC;


๐Ÿ† Double Tap โค๏ธ For More
โค3๐Ÿ‘1
๐—ง๐—ผ๐—ฝ ๐—œ๐—ป-๐——๐—ฒ๐—บ๐—ฎ๐—ป๐—ฑ ๐—ฆ๐—ธ๐—ถ๐—น๐—น๐˜€ ๐˜๐—ผ ๐—™๐˜‚๐˜๐˜‚๐—ฟ๐—ฒ-๐—ฃ๐—ฟ๐—ผ๐—ผ๐—ณ ๐—ฌ๐—ผ๐˜‚๐—ฟ ๐—–๐—ฎ๐—ฟ๐—ฒ๐—ฒ๐—ฟ ๐Ÿ˜

๐Ÿ”ฅ Skills Worth Learning:

โ›“๏ธ Blockchain
โ˜๏ธ Cloud Computing
โ™พ๏ธ DevOps Engineering
๐Ÿค– Artificial Intelligence & Machine Learning
๐Ÿ“Š Data Science & Analytics
๐Ÿ” Cybersecurity
๐ŸŽฏ Leadership & Communication

๐—˜๐—ป๐—ฟ๐—ผ๐—น๐—น ๐—™๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜๐Ÿ‘‡:-

https://pdlinks.in/i89

Donโ€™t just collect certificates โ€” build projects, gain practical experience and showcase your skills on your resume & LinkedIn.
๐Ÿš€ Data Analyst Roadmap โ€” Part 13

๐Ÿ—„๏ธ SQL โ€” Level 3: CASE WHEN, NULL Handling & Conditional Logic

In the previous part, you learned how to summarize data using GROUP BY and aggregate functions.

Now we're going to make SQL more powerful by learning how to create categories, handle missing data, and apply business rules.

These skills are extremely important because real-world datasets are rarely perfect.

You may need to answer questions like:



Which orders are High, Medium, or Low value?

How many customers have missing information?

What should we display when a value is NULL?

How many employees are above their target?



This is where CASE WHEN and NULL-handling functions become essential.

1๏ธโƒฃ What Is CASE WHEN?

CASE WHEN allows SQL to make decisions.

Think of it as the SQL equivalent of Excel's:

IF()

For example:

CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END


SQL evaluates the conditions and returns the appropriate category.

2๏ธโƒฃ Basic CASE WHEN

Suppose you have:

Order_ID | Sales

1001 | 120,000

1002 | 75,000

1003 | 30,000

You want to classify orders.

SELECT
Order_ID,
Sales,
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END AS Sales_Category
FROM Orders;


Result:

Order_ID | Sales | Sales_Category

1001 | 120,000 | High

1002 | 75,000 | Medium

1003 | 30,000 | Low

3๏ธโƒฃ Understand the Evaluation Order

SQL evaluates the WHEN conditions from top to bottom.

For example:

CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END


If Sales = 120000:

Is it โ‰ฅ 100000? โœ…

Return High

Stop evaluating the remaining conditions.

That's why the order of conditions matters.

4๏ธโƒฃ CASE WHEN with Categories

Suppose employees have salaries.

You want:

โ‚น100,000+ โ†’ Senior

โ‚น60,000โ€“99,999 โ†’ Mid-Level

Below โ‚น60,000 โ†’ Junior

SELECT
Name,
Salary,
CASE
WHEN Salary >= 100000 THEN 'Senior'
WHEN Salary >= 60000 THEN 'Mid-Level'
ELSE 'Junior'
END AS Salary_Level
FROM Employees;


This is a common data transformation technique.

5๏ธโƒฃ CASE WHEN with Text Conditions

You can also evaluate text.

Suppose:

Department

IT

HR

Finance

Sales

You want to categorize IT and Finance as:

Business-Critical

and everything else as:

Other

SELECT
Name,
Department,
CASE
WHEN Department IN ('IT', 'Finance')
THEN 'Business-Critical'
ELSE 'Other'
END AS Department_Type
FROM Employees;


6๏ธโƒฃ CASE WHEN with AND

You can combine multiple conditions.

Suppose an employee qualifies for a bonus if:

Department = IT

Salary > โ‚น80,000

SELECT
Name,
Department,
Salary,
CASE
WHEN Department = 'IT'
AND Salary > 80000
THEN 'Bonus Eligible'
ELSE 'Not Eligible'
END AS Bonus_Status
FROM Employees;


Both conditions must be true.

7๏ธโƒฃ CASE WHEN with OR

Suppose employees from IT or Finance should receive a particular classification.

SELECT
Name,
Department,
CASE
WHEN Department = 'IT'
OR Department = 'Finance'
THEN 'Priority'
ELSE 'Standard'
END AS Employee_Type
FROM Employees;
At least one condition must be true.

8๏ธโƒฃ CASE WHEN with Aggregation

Here's where CASE WHEN becomes extremely powerful.

Suppose you want to count high-value orders.

You can write:

SELECT
COUNT(
CASE
WHEN Sales >= 100000 THEN 1
END
) AS High_Value_Orders
FROM Orders;


This counts only orders where Sales is at least โ‚น100,000.

9๏ธโƒฃ Conditional SUM

Suppose you want:



Total sales from high-value orders.



Use:

SELECT
SUM(
CASE
WHEN Sales >= 100000 THEN Sales
ELSE 0
END
) AS High_Value_Sales
FROM Orders;


This calculates sales only for qualifying orders.

This technique is called conditional aggregation.

๐Ÿ”Ÿ Conditional Aggregation by Region

Suppose you want to compare:

North sales

South sales

in the same result.

SELECT
SUM(
CASE
WHEN Region = 'North' THEN Sales
ELSE 0
END
) AS North_Sales,

SUM(
CASE
WHEN Region = 'South' THEN Sales
ELSE 0
END
) AS South_Sales
FROM Orders;


Result:

North_Sales | South_Sales

500,000 | 350,000

This is extremely useful when building analytical reports.

1๏ธโƒฃ1๏ธโƒฃ CASE WHEN with GROUP BY

You can create categories and then aggregate them.

For example:

SELECT
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END AS Sales_Category,
COUNT(*) AS Order_Count
FROM Orders
GROUP BY
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END;


This tells you how many orders belong to each sales category.

1๏ธโƒฃ2๏ธโƒฃ What Is NULL?

NULL represents missing or unknown information.

It is important to understand:



NULL is not the same as zero.



For example:

Salary = 0

means the salary value is explicitly zero.

But:

Salary = NULL

means the value is missing or unknown.

Similarly:

Discount = NULL

doesn't necessarily mean:

Discount = 0

It means:

No value is available.

1๏ธโƒฃ3๏ธโƒฃ NULL Is Not an Empty String

These are different:

NULL

''

' '

0

NULL

Missing/unknown value.

Empty string

A text value containing no characters.

Space

A string containing a space.

Zero

A numeric value equal to zero.

This distinction is extremely important when cleaning data.

1๏ธโƒฃ4๏ธโƒฃ Don't Use = NULL

A common beginner mistake is:

WHERE Email = NULL

This is incorrect for testing NULL.

Instead, use:

WHERE Email IS NULL

To find non-NULL values:

WHERE Email IS NOT NULL

1๏ธโƒฃ5๏ธโƒฃ Find Missing Values

Suppose you want customers whose phone numbers are missing:

SELECT *
FROM Customers
WHERE Phone IS NULL;


This is useful for data-quality analysis.

1๏ธโƒฃ6๏ธโƒฃ Count Missing Values

You can use conditional aggregation:

SELECT
COUNT(*) AS Total_Customers,
COUNT(
CASE
WHEN Phone IS NULL THEN 1
END
) AS Missing_Phone
FROM Customers;


Now you can see:

Total_Customers | Missing_Phone

10,000 | 350

So:

350 customers have missing phone numbers.

1๏ธโƒฃ7๏ธโƒฃ COALESCE()

COALESCE() returns the first non-NULL value.

For example:

SELECT
Customer_Name,
COALESCE(Phone, 'Not Available') AS Phone
FROM Customers;
If Phone is NULL, SQL returns:

Not Available

Otherwise, it returns the actual phone number.

1๏ธโƒฃ8๏ธโƒฃ COALESCE() with Multiple Options

You can provide multiple alternatives.

SELECT
COALESCE(Work_Email, Personal_Email, 'No Email')
AS Contact_Email
FROM Customers;


SQL checks:

1. Work Email

2. Personal Email

3. "No Email"

It returns the first non-NULL value.

This is extremely useful when combining multiple possible sources of information.

1๏ธโƒฃ9๏ธโƒฃ NULLIF()

NULLIF() returns NULL if two expressions are equal.

For example:

NULLIF(Sales, 0)

If Sales is:

0

the result becomes:

NULL

Otherwise, the original Sales value is returned.

2๏ธโƒฃ0๏ธโƒฃ Why NULLIF() Is Useful

Suppose you're calculating:

Profit Margin = Profit / Sales

If Sales is zero:

Profit / Sales

could cause a division-by-zero error.

You can use:

SELECT
Profit / NULLIF(Sales, 0) AS Profit_Margin
FROM Orders;


If Sales = 0:

NULLIF(0,0) โ†’ NULL

So the division doesn't attempt to divide by zero.

This is an important practical technique.

2๏ธโƒฃ1๏ธโƒฃ CASE WHEN + NULL

You can also explicitly handle missing values.

SELECT
Customer_Name,
CASE
WHEN Phone IS NULL THEN 'Missing'
ELSE 'Available'
END AS Phone_Status
FROM Customers;


Result:

Customer_Name | Phone_Status

John | Available

Sarah | Missing

Mike | Available

This is useful for data-quality reports.

2๏ธโƒฃ2๏ธโƒฃ Categorize Customers

Suppose you want to classify customers based on total spending:

โ‚น1,00,000+ โ†’ VIP

โ‚น50,000+ โ†’ Premium

โ‚น20,000+ โ†’ Standard

Below โ‚น20,000 โ†’ Basic

After calculating customer-level sales, you could use:

CASE
WHEN Total_Sales >= 100000 THEN 'VIP'
WHEN Total_Sales >= 50000 THEN 'Premium'
WHEN Total_Sales >= 20000 THEN 'Standard'
ELSE 'Basic'
END


This type of segmentation is widely used in business analytics.

2๏ธโƒฃ3๏ธโƒฃ CASE WHEN for KPI Status

Suppose the target is:

โ‚น10,00,000

and actual sales are stored in Total_Sales.

You could create:

CASE
WHEN Total_Sales >= 1000000 THEN 'Target Achieved'
ELSE 'Below Target'
END


This turns a raw number into a business interpretation.

2๏ธโƒฃ4๏ธโƒฃ CASE WHEN for Profitability

Suppose:

Profit > 0 โ†’ Profitable

Profit = 0 โ†’ Break-even

Profit < 0 โ†’ Loss

Use:

CASE
WHEN Profit > 0 THEN 'Profitable'
WHEN Profit = 0 THEN 'Break-even'
ELSE 'Loss'
END AS Profit_Status


This is a simple but powerful analytical transformation.

2๏ธโƒฃ5๏ธโƒฃ CASE WHEN for Data Cleaning

Suppose your dataset contains:

India

INDIA

india

IN

You can standardize values with a CASE expression:

CASE
WHEN Country IN ('India', 'INDIA', 'india', 'IN')
THEN 'India'
ELSE Country
END AS Standardized_Country


For a small number of known inconsistencies, this can be useful.

For larger or recurring transformations, you may want to handle standardization upstream in your data pipeline.

2๏ธโƒฃ6๏ธโƒฃ A Powerful Interview Pattern

You will frequently encounter queries like:

SELECT
Region,
SUM(Sales) AS Total_Sales,
CASE
WHEN SUM(Sales) >= 1000000
THEN 'Target Achieved'
ELSE 'Below Target'
END AS Target_Status
FROM Orders
GROUP BY Region;
This combines:

GROUP BY

SUM()

CASE WHEN

to create a business-ready result.

2๏ธโƒฃ7๏ธโƒฃ Important SQL Execution Concept

A simplified logical order of SQL processing is:

FROM

โ†“

WHERE

โ†“

GROUP BY

โ†“

HAVING

โ†“

SELECT

โ†“

ORDER BY

This helps explain why SQL behaves differently from how the query appears visually.

For example:

SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region
HAVING SUM(Sales) > 100000
ORDER BY Total_Sales DESC;


Think:

Get data โ†’ filter rows โ†’ group โ†’ calculate โ†’ filter groups โ†’ sort

Understanding SQL's logical processing order will become increasingly important as queries get more complex.

๐Ÿงช Practical Interview Challenge

Suppose you have:

Orders

Order_ID | Region | Sales | Profit

1001 | North | 120,000 | 20,000

1002 | South | 75,000 | 10,000

1003 | North | 30,000 | -5,000

1004 | West | 150,000 | 30,000

1005 | South | NULL | 8,000

Q1. Categorize orders by sales.

SELECT
Order_ID,
Sales,
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END AS Sales_Category
FROM Orders;


Q2. Find orders with missing sales.

SELECT *
FROM Orders
WHERE Sales IS NULL;


Q3. Replace missing sales with zero for display.

SELECT
Order_ID,
COALESCE(Sales, 0) AS Sales
FROM Orders;


Remember: this changes the display/calculation result, not necessarily the underlying data.

Q4. Categorize profitability.

SELECT
Order_ID,
CASE
WHEN Profit > 0 THEN 'Profitable'
WHEN Profit = 0 THEN 'Break-even'
ELSE 'Loss'
END AS Profit_Status
FROM Orders;


Q5. Count high-value orders.

SELECT
COUNT(
CASE
WHEN Sales >= 100000 THEN 1
END
) AS High_Value_Orders
FROM Orders;


Q6. Calculate profit margin safely.

SELECT
Order_ID,
Profit / NULLIF(Sales, 0) AS Profit_Margin
FROM Orders;


๐Ÿ† Double Tap โค๏ธ For More
โค12
๐Ÿš€ ๐—™๐—ฅ๐—˜๐—˜ ๐—š๐—ฒ๐—ป๐—”๐—œ + ๐—–๐—น๐—ฎ๐˜‚๐—ฑ๐—ฒ ๐—ข๐—ป๐—น๐—ถ๐—ป๐—ฒ ๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ๐—ฐ๐—น๐—ฎ๐˜€๐˜€ ๐Ÿ˜

Want to work faster, create better content and save hours every week using AI?

Join this beginner-friendly masterclass and discover how to use ๐Ÿฎ๐Ÿฑ+ powerful AI tools to:

โœ… Automate repetitive tasks
โœ… Create professional content in minutes
โœ… Improve productivity and efficiency
โœ… Save valuable time every week
โœ… Use GenAI and Claude effectively

๐Ÿ’ก No technical knowledge or previous AI experience required!

๐Ÿ”— ๐—ฅ๐—ฒ๐—ด๐—ถ๐˜€๐˜๐—ฒ๐—ฟ ๐—ณ๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜ ๐Ÿ‘‡

https://pdlink.in/46wurp9

โšก Limited slots availableโ€”register now and start working smarter with AI!
โค2
๐Ÿš€ Data Analyst Roadmap โ€” Part 14

๐Ÿ—„๏ธ SQL โ€” Level 4: JOINs

One of the most important SQL skills for a Data Analyst is understanding JOINs.

In real-world databases, information is rarely stored in one giant table. Instead, data is usually split across multiple related tables.

For example:

Customers โ†’ Orders โ†’ Products โ†’ Payments

JOINs allow you to bring related information together.

1๏ธโƒฃ What Is a JOIN?

A JOIN combines rows from two or more tables using a related column.

Suppose you have:

Customers

Customer_ID | Customer_Name | City
101 | John | Pune
102 | Sarah | Mumbai
103 | Mike | Delhi


Orders

Order_ID | Customer_ID | Sales
5001 | 101 | 50,000
5002 | 102 | 70,000
5003 | 101 | 30,000


Both tables have Customer_ID. That common field allows us to connect them.

2๏ธโƒฃ Why Are JOINs Important?

Imagine your manager asks: "Show me each customer's name along with their total sales."

The customer name is in Customers. The sales amount is in Orders. You need to combine the tables. That's a JOIN problem.

3๏ธโƒฃ Basic JOIN Syntax

SELECT
Customers.Customer_Name,
Orders.Sales
FROM Customers
JOIN Orders
ON Customers.Customer_ID = Orders.Customer_ID;


The ON condition tells SQL: How are these two tables related?

4๏ธโƒฃ INNER JOIN

INNER JOIN returns only records where a match exists in both tables.

If Customer 104 exists only in Orders, it won't be returned.

Result after INNER JOIN:

John | 50,000

Sarah | 70,000

5๏ธโƒฃ INNER JOIN โ€” Simple Rule

INNER JOIN = Only matching records

Think: Table A โˆฉ Table B

6๏ธโƒฃ LEFT JOIN

LEFT JOIN returns All rows from the left table plus matching rows from the right table.

Query:

SELECT
Customers.Customer_Name,
Orders.Sales
FROM Customers
LEFT JOIN Orders
ON Customers.Customer_ID = Orders.Customer_ID;


Result:

John | 50,000

Sarah | 70,000

Mike | NULL

Mike doesn't have an order, but because Customers is the left table, Mike remains in the result.

7๏ธโƒฃ Why LEFT JOIN Is Extremely Important

To find customers who have never placed an order:

SELECT c.Customer_ID, c.Customer_Name
FROM Customers c
LEFT JOIN Orders o ON c.Customer_ID = o.Customer_ID
WHERE o.Customer_ID IS NULL;


This is a very common analytical pattern.

8๏ธโƒฃ RIGHT JOIN

RIGHT JOIN is the reverse of LEFT JOIN. It returns All rows from the right table plus matching rows from the left.

9๏ธโƒฃ Do Data Analysts Need RIGHT JOIN?

You should understand it. However, many analysts prefer rewriting a RIGHT JOIN as a LEFT JOIN because LEFT JOIN is often easier to read.

A RIGHT JOIN B can be rewritten as B LEFT JOIN A.

๐Ÿ”Ÿ FULL OUTER JOIN

A FULL OUTER JOIN returns:

โ€ข Matching rows

โ€ข Unmatched rows from the left

โ€ข Unmatched rows from the right

1๏ธโƒฃ1๏ธโƒฃ FULL OUTER JOIN Example

SELECT c.Customer_ID, c.Customer_Name, o.Order_ID
FROM Customers c
FULL OUTER JOIN Orders o ON c.Customer_ID = o.Customer_ID;


Useful for identifying data inconsistencies and missing relationships.

1๏ธโƒฃ2๏ธโƒฃ JOIN Comparison

โ€ข INNER JOIN: Matching rows only

โ€ข LEFT JOIN: All left + matching right

โ€ข RIGHT JOIN: All right + matching left

โ€ข FULL OUTER JOIN: Everything from both

Most important for Data Analysts: INNER JOIN and LEFT JOIN. Master these first.

1๏ธโƒฃ3๏ธโƒฃ JOIN with Multiple Columns

ON A.Product_ID = B.Product_ID
AND A.Region = B.Region


Composite join conditions are common in real-world datasets.

1๏ธโƒฃ4๏ธโƒฃ Joining More Than Two Tables
โค1
SELECT c.Customer_Name, o.Order_ID, p.Product_Name, o.Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
JOIN Products p ON o.Product_ID = p.Product_ID;


1๏ธโƒฃ5๏ธโƒฃ Table Aliases

Customers c, Orders o, Products p

Instead of Customers.Customer_ID, you can write c.Customer_ID. Much easier to read.

1๏ธโƒฃ6๏ธโƒฃ JOIN + GROUP BY

This is one of the most important patterns.

SELECT c.Customer_Name, SUM(o.Sales) AS Total_Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
GROUP BY c.Customer_Name;


JOIN + SUM + GROUP BY is a very common interview question.

1๏ธโƒฃ7๏ธโƒฃ JOIN + WHERE

SELECT c.Customer_Name, o.Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
WHERE c.Department = 'IT';


JOIN connects, WHERE filters.

1๏ธโƒฃ8๏ธโƒฃ JOIN + HAVING

SELECT c.Customer_Name, SUM(o.Sales) AS Total_Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
GROUP BY c.Customer_Name
HAVING SUM(o.Sales) > 100000;


Pattern: JOIN โ†’ GROUP BY โ†’ SUM โ†’ HAVING

1๏ธโƒฃ9๏ธโƒฃ The Most Important LEFT JOIN Pattern

SELECT c.Customer_ID, c.Customer_Name
FROM Customers c
LEFT JOIN Orders o ON c.Customer_ID = o.Customer_ID
WHERE o.Customer_ID IS NULL;


Answers: Which customers have no orders?

General pattern: LEFT JOIN + WHERE right_table.key IS NULL

2๏ธโƒฃ0๏ธโƒฃ JOIN and NULL

After a LEFT JOIN, unmatched columns become NULL. That NULL tells us: No matching order was found.

2๏ธโƒฃ1๏ธโƒฃ Self JOIN

A Self JOIN joins a table to itself. Useful for employee-manager relationships.

SELECT e.Employee_Name AS Employee, m.Employee_Name AS Manager
FROM Employees e
LEFT JOIN Employees m ON e.Manager_ID = m.Employee_ID;


2๏ธโƒฃ2๏ธโƒฃ Many-to-One Relationships

Customers โ†’ Orders is One-to-Many. From Orders perspective, it's Many-to-One. Understanding direction is critical.

2๏ธโƒฃ3๏ธโƒฃ The Duplicate Row Problem

If John has 3 orders, after JOIN John appears 3 times. That's correct, not an error. Always understand relationship cardinality.

2๏ธโƒฃ4๏ธโƒฃ JOIN Multiplication

If a customer has 3 orders and 4 payments, an incorrect join can produce 12 combinations and inflate Sales, Counts, Profit. Always check grain before aggregating.

2๏ธโƒฃ5๏ธโƒฃ What Is Table Grain?

Grain means: What does one row represent?

Customers: One row = one customer

Orders: One row = one order

2๏ธโƒฃ6๏ธโƒฃ JOIN vs UNION

โ€ข JOIN: Combines tables horizontally. Adds columns.

โ€ข UNION: Combines results vertically. Adds rows.

2๏ธโƒฃ7๏ธโƒฃ Practical Business Example

Question: What is total sales by region?

SELECT c.Region, SUM(o.Sales) AS Total_Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
GROUP BY c.Region
ORDER BY Total_Sales DESC;


๐Ÿงช Practical Interview Challenge

Q1. Show customer names with their orders.

SELECT c.Customer_Name, o.Order_ID, o.Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID;


Q2. Show all customers, including those without orders.

SELECT c.Customer_Name, o.Order_ID, o.Sales
FROM Customers c
LEFT JOIN Orders o ON c.Customer_ID = o.Customer_ID;


Q3. Find customers who have never ordered.

SELECT c.Customer_ID, c.Customer_Name
FROM Customers c
LEFT JOIN Orders o ON c.Customer_ID = o.Customer_ID
WHERE o.Customer_ID IS NULL;


Q4. Find total sales per customer.

SELECT c.Customer_Name, SUM(o.Sales) AS Total_Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
GROUP BY c.Customer_Name;
โค1
Q5. Find customers whose total sales exceed โ‚น50,000.

SELECT c.Customer_Name, SUM(o.Sales) AS Total_Sales
FROM Customers c
JOIN Orders o ON c.Customer_ID = o.Customer_ID
GROUP BY c.Customer_Name
HAVING SUM(o.Sales) > 50000;


๐Ÿ† Double Tap โค๏ธ For More
โค9
๐Ÿš€ Data Analyst Roadmap โ€” Part 15

๐Ÿ—„๏ธ SQL โ€” Level 5: Subqueries, CTEs & Derived Tables

You've now learned how to retrieve, filter, aggregate, categorize, and join data.

The next step is learning how to break complex SQL problems into smaller, manageable steps.

The three important concepts in this part are:

โ€ข Subqueries

โ€ข CTEs (Common Table Expressions)

โ€ข Derived Tables

These are heavily used in real-world SQL analysis and interviews.

1๏ธโƒฃ What Is a Subquery?

A subquery is a SQL query inside another SQL query.

Think of it as:



First solve one problem โ†’ then use that result to solve another problem.



For example, suppose you want to find employees earning more than the average salary.

First, calculate the average:

SELECT AVG(Salary)
FROM Employees;


Then use that result to filter employees:

SELECT
Name,
Salary
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
);


The query inside the parentheses is the subquery.

2๏ธโƒฃ Why Use Subqueries?

Without a subquery, you might have to calculate the average separately and manually enter it.

With a subquery, SQL calculates it dynamically.

This is useful for questions such as: Employees earning above average, Products selling above average, Customers spending more than average, Orders larger than the overall average, Finding records based on another query's result

3๏ธโƒฃ How a Subquery Works

Consider:

SELECT
Name,
Salary
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
);


Conceptually: Subquery โ†“ Calculate average salary โ†“ Average Salary โ†“ Main Query โ†“ Find employees above average

The inner query provides a value that the outer query uses.

4๏ธโƒฃ Scalar Subquery

A scalar subquery returns a single value.

For example:

SELECT AVG(Salary)
FROM Employees;


returns one value.

You can use it like:

SELECT
Name,
Salary,
Salary - (
SELECT AVG(Salary)
FROM Employees
) AS Difference_From_Average
FROM Employees;


Now every employee can be compared against the overall average.

5๏ธโƒฃ Subquery with IN

A subquery doesn't always return one value. It can return a list.

Suppose you want customers who have placed at least one order.

SELECT
Customer_ID,
Customer_Name
FROM Customers
WHERE Customer_ID IN (
SELECT Customer_ID
FROM Orders
);


The inner query returns a list of customer IDs. The outer query retrieves matching customers.

6๏ธโƒฃ NOT IN

You can also find records that aren't present in another query.

For example:



Find customers who have never placed an order.



SELECT
Customer_ID,
Customer_Name
FROM Customers
WHERE Customer_ID NOT IN (
SELECT Customer_ID
FROM Orders
);


However, be careful when using NOT IN if the subquery can contain NULL, because NULL semantics can produce unexpected results.

For anti-matching logic, NOT EXISTS or a properly structured LEFT JOIN ... IS NULL is often safer.

7๏ธโƒฃ EXISTS

EXISTS checks whether a matching row exists.

For example:

SELECT
c.Customer_ID,
c.Customer_Name
FROM Customers c
WHERE EXISTS (
SELECT 1
FROM Orders o
WHERE o.Customer_ID = c.Customer_ID
);


This means:



Return customers for whom at least one matching order exists.



You don't need the subquery to return the actual order details. You're simply checking whether a match exists.

8๏ธโƒฃ NOT EXISTS

NOT EXISTS does the opposite.
โค1๐Ÿ‘1
The CTE is often easier to read when the query becomes complex.

A good rule:



Simple calculation โ†’ subquery can be fine.

Multiple logical steps โ†’ CTE is often clearer.



1๏ธโƒฃ7๏ธโƒฃ CTE vs Derived Table

Conceptually, both can create an intermediate result.

Derived Table: Usually appears inside: FROM (...)

CTE: Defined before the main query: WITH Name AS (...)

CTEs generally make multi-step analytical queries easier to organize.

1๏ธโƒฃ8๏ธโƒฃ CTE for Data Filtering

Suppose you only want 2026 orders.

WITH Orders_2026 AS (
SELECT *
FROM Orders
WHERE Order_Date >= '2026-01-01'
AND Order_Date < '2027-01-01'
)

SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders_2026
GROUP BY Region;


This makes the query's logic easy to follow:

First โ†’ select 2026, Then โ†’ analyze by region

1๏ธโƒฃ9๏ธโƒฃ CTE for Business Logic

Suppose you want to classify orders:

WITH Classified_Orders AS (
SELECT
Order_ID,
Sales,
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END AS Sales_Category
FROM Orders
)

SELECT
Sales_Category,
COUNT(*) AS Order_Count
FROM Classified_Orders
GROUP BY Sales_Category;


Now you've separated: Classification from: Aggregation. This is much easier to maintain.

2๏ธโƒฃ0๏ธโƒฃ CTE for Multi-Step Analysis

Imagine the business asks:



Which region has the highest average customer sales?



A CTE can break this into understandable stages.

For example:

WITH Customer_Sales AS (
SELECT
Customer_ID,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Customer_ID
),
Regional_Customer_Sales AS (
SELECT
c.Region,
cs.Customer_ID,
cs.Total_Sales
FROM Customer_Sales cs
JOIN Customers c
ON cs.Customer_ID = c.Customer_ID
)

SELECT
Region,
AVG(Total_Sales) AS Avg_Customer_Sales
FROM Regional_Customer_Sales
GROUP BY Region
ORDER BY Avg_Customer_Sales DESC;


This is much easier to reason about than attempting everything at once.

2๏ธโƒฃ1๏ธโƒฃ CTEs Are Not Permanent Tables

This is important.

A normal table: Customers, Orders, Products is stored in the database.

A CTE: WITH Customer_Sales AS (...) exists only for the duration of that query.

2๏ธโƒฃ2๏ธโƒฃ CTEs and Performance

A common misconception is:



"CTEs are always faster than subqueries."



That's not necessarily true.

A CTE is primarily a query organization/readability tool.

Actual performance depends on: Database engine, Query structure, Indexes, Data volume, Optimizer behavior, Joins, Aggregations

So don't use a CTE simply because you think it automatically makes a query faster. Use it when it makes the logic clearer or otherwise fits your query design.

2๏ธโƒฃ3๏ธโƒฃ Correlated Subquery

A correlated subquery references a column from the outer query.

Example:

SELECT
e.Name,
e.Salary
FROM Employees e
WHERE e.Salary > (
SELECT AVG(e2.Salary)
FROM Employees e2
WHERE e2.Department = e.Department
);
โค1
This asks:



Which employees earn more than the average salary of their own department?



The inner query depends on the current employee's department. This is more advanced than a basic subquery.

2๏ธโƒฃ4๏ธโƒฃ Why Correlated Subqueries Matter

Suppose: IT Average salary = โ‚น80,000, HR Average salary = โ‚น60,000

An employee earning โ‚น75,000: Could be below IT average, Could be above HR average

So comparing everyone to the overall company average isn't enough. A correlated subquery allows you to compare each employee to the relevant group.

2๏ธโƒฃ5๏ธโƒฃ Subquery vs JOIN

Sometimes the same problem can be solved using either a subquery or a JOIN.

For example, finding customers with orders can be done with: WHERE EXISTS (...) or: JOIN Orders ...

Neither is universally better.

The right choice depends on: What result you need, Whether duplicates matter, Query readability, Database optimizer, Data structure

Focus on understanding the logic rather than memorizing one preferred method.

2๏ธโƒฃ6๏ธโƒฃ A Very Common Interview Problem

Question:



Find employees earning more than their department's average salary.



A correlated subquery solution:

SELECT
e.Name,
e.Department,
e.Salary
FROM Employees e
WHERE e.Salary > (
SELECT AVG(e2.Salary)
FROM Employees e2
WHERE e2.Department = e.Department
);


This is an excellent interview question because it tests: Subqueries, Aggregation, Correlation, Business logic

2๏ธโƒฃ7๏ธโƒฃ Another Interview Problem

Question:



Find customers whose total sales are greater than โ‚น1,00,000.



Using a derived table:

SELECT
Customer_ID,
Total_Sales
FROM (
SELECT
Customer_ID,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Customer_ID
) AS Customer_Sales
WHERE Total_Sales > 100000;


Or using a CTE:

WITH Customer_Sales AS (
SELECT
Customer_ID,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Customer_ID
)
SELECT
Customer_ID,
Total_Sales
FROM Customer_Sales
WHERE Total_Sales > 100000;


Both approaches produce the same analytical idea.

๐Ÿงช Practical Interview Challenge

Suppose you have Employees table

Q1. Find employees earning above the overall average.

SELECT
Name,
Salary
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
);


Q2. Find employees earning above their department average.

SELECT
e.Name,
e.Department,
e.Salary
FROM Employees e
WHERE e.Salary > (
SELECT AVG(e2.Salary)
FROM Employees e2
WHERE e2.Department = e.Department
);


Q3. Create a CTE containing average salary by department.

WITH Department_Salary AS (
SELECT
Department,
AVG(Salary) AS Average_Salary
FROM Employees
GROUP BY Department
)
SELECT *
FROM Department_Salary;


Q4. Find departments whose average salary exceeds โ‚น70,000.

WITH Department_Salary AS (
SELECT
Department,
AVG(Salary) AS Average_Salary
FROM Employees
GROUP BY Department
)

SELECT
Department,
Average_Salary
FROM Department_Salary
WHERE Average_Salary > 70000;


Q5. Find customers who have placed at least one order.

SELECT
c.Customer_ID,
c.Customer_Name
FROM Customers c
WHERE EXISTS (
SELECT 1
FROM Orders o
WHERE o.Customer_ID = c.Customer_ID
);


๐Ÿ† Double Tap โค๏ธ For More
โค6
๐Ÿ“Š ๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ ๐—˜๐˜…๐—ฐ๐—ฒ๐—น ๐—™๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜ | ๐Ÿฑ ๐—ฃ๐—ผ๐˜„๐—ฒ๐—ฟ๐—ณ๐˜‚๐—น ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐Ÿš€

๐Ÿ”ฅ Top 5 FREE Excel Courses:

1๏ธโƒฃ Goldman Sachs โ€“ Excel Skills for Business
2๏ธโƒฃ PwC โ€“ Problem Solving with Excel
3๏ธโƒฃ Corporate Finance Institute โ€“ Excel Fundamentals
4๏ธโƒฃ Great Learning โ€“ Excel for Beginners
5๏ธโƒฃ Simplilearn โ€“ Introduction to MS Excel

๐—˜๐—ป๐—ฟ๐—ผ๐—น๐—น ๐—™๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜๐Ÿ‘‡:- 

https://pdlink.in/3UQ8S09

๐Ÿš€ Learn Excel for FREE and upgrade your career skills!
โค3
Scenario based  Interview Questions & Answers for Data Analyst

1. Scenario: You are working on a SQL database that stores customer information. The database has a table called "Orders" that contains order details. Your task is to write a SQL query to retrieve the total number of orders placed by each customer.
  Question:
  - Write a SQL query to find the total number of orders placed by each customer.
Expected Answer:
    SELECT CustomerID, COUNT(*) AS TotalOrders
    FROM Orders
    GROUP BY CustomerID;

2. Scenario: You are working on a SQL database that stores employee information. The database has a table called "Employees" that contains employee details. Your task is to write a SQL query to retrieve the names of all employees who have been with the company for more than 5 years.
  Question:
  - Write a SQL query to find the names of employees who have been with the company for more than 5 years.
Expected Answer:
    SELECT Name
    FROM Employees
    WHERE DATEDIFF(year, HireDate, GETDATE()) > 5;

Power BI Scenario-Based Questions

1. Scenario: You have been given a dataset in Power BI that contains sales data for a company. Your task is to create a report that shows the total sales by product category and region.
    Expected Answer:
    - Load the dataset into Power BI.
    - Create relationships if necessary.
    - Use the "Fields" pane to select the necessary fields (Product Category, Region, Sales).
    - Drag these fields into the "Values" area of a new visualization (e.g., a table or bar chart).
    - Use the "Filters" pane to filter data as needed.
    - Format the visualization to enhance clarity and readability.

2. Scenario: You have been asked to create a Power BI dashboard that displays real-time stock prices for a set of companies. The stock prices are available through an API.
  Expected Answer:
    - Use Power BI Desktop to connect to the API.
    - Go to "Get Data" > "Web" and enter the API URL.
    - Configure the data refresh settings to ensure real-time updates (e.g., setting up a scheduled refresh or using DirectQuery if supported).
    - Create visualizations using the imported data.
    - Publish the report to the Power BI service and set up a data gateway if needed for continuous refresh.

3. Scenario: You have been given a Power BI report that contains multiple visualizations. The report is taking a long time to load and is impacting the performance of the application.
    Expected Answer:
    - Analyze the current performance using Performance Analyzer.
    - Optimize data model by reducing the number of columns and rows, and removing unnecessary calculations.
    - Use aggregated tables to pre-compute results.
    - Simplify DAX calculations.
    - Optimize visualizations by reducing the number of visuals per page and avoiding complex custom visuals.
    - Ensure proper indexing on the data source.

Free SQL Resources: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v

Like if you need more similar content

Hope it helps :)
โค6
๐Ÿš€ ๐—Ÿ๐—ฒ๐˜ƒ๐—ฒ๐—น ๐—จ๐—ฝ ๐—ฌ๐—ผ๐˜‚๐—ฟ ๐—–๐—ฎ๐—ฟ๐—ฒ๐—ฒ๐—ฟ ๐˜„๐—ถ๐˜๐—ต ๐—™๐—ฅ๐—˜๐—˜ ๐— ๐—ถ๐—ฐ๐—ฟ๐—ผ๐˜€๐—ผ๐—ณ๐˜ ๐—Ÿ๐—ฒ๐—ฎ๐—ฟ๐—ป๐—ถ๐—ป๐—ด! ๐Ÿ’ป

Microsoft-focused learning paths can help you strengthen your resume and prepare for in-demand tech and data roles.

๐Ÿ”ฅ Top 5 Courses / Certification Paths:
โœ… Beginner-friendly options
โœ… Build practical, job-ready skills
โœ… Learn Azure, Power BI, Excel & SQL
โœ… Strengthen your resume & career profile

๐—˜๐—ป๐—ฟ๐—ผ๐—น๐—น ๐—™๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜๐Ÿ‘‡:- 

https://pdlink.in/3UNpPs7

๐Ÿ’ซPerfect for students, freshers, data analysts and professionals looking to upgrade their skills.
โค5
๐ŸŽ“ ๐—ง๐—ผ๐—ฝ ๐—–๐—ผ๐—บ๐—ฝ๐—ฎ๐—ป๐—ถ๐—ฒ๐˜€ ๐—ข๐—ณ๐—ณ๐—ฒ๐—ฟ๐—ถ๐—ป๐—ด ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ถ๐—ผ๐—ป ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐Ÿš€

Learn in-demand skills โ€ข Add valuable credentials to your resume

๐Ÿข TATA :- https://pdlink.in/3QiwLvx

๐Ÿ’ป Infosys :- https://pdlink.in/4eBH3Aa

โšก IBM :- https://pdlink.in/45KgqDR

๐Ÿ’ซ Amazon :- https://pdlink.in/47XuBGz

๐ŸŒ Cisco :- https://pdlink.in/4gaeVVV

๐ŸชŸ Microsoft :- https://pdlink.in/4zhGTX6

๐Ÿ“ข Save & share this with your friends โ€” start upskilling for FREE!
๐Ÿš€ Data Analyst Roadmap โ€” Part 16

๐Ÿง  SQL Level 6 โ€” Window Functions

Window functions are one of the most important SQL skills for a Data Analyst.

They allow you to perform calculations across related rows without losing the individual rows.

Instead of collapsing data like GROUP BY, window functions let you analyze each row in the context of other rows.

๐Ÿ”น 1. GROUP BY vs Window Functions

Suppose you have:

Employee | Department | Salary
John | IT | 75,000
Mike | IT | 90,000
Lisa | IT | 90,000
Sarah | HR | 60,000
Alice | HR | 70,000


With GROUP BY:

SELECT Department, AVG(Salary) AS Avg_Salary
FROM Employees
GROUP BY Department;


You get one row per department.

With a window function:

SELECT
Employee,
Department,
Salary,
AVG(Salary) OVER (PARTITION BY Department) AS Avg_Dept_Salary
FROM Employees;


You keep every employee while also seeing their department's average salary.

๐Ÿ‘‰ GROUP BY reduces rows.

๐Ÿ‘‰ Window functions preserve rows.

๐Ÿ”น 2. Understanding OVER()

Every window function uses the OVER() clause.

FUNCTION() OVER (
PARTITION BY column
ORDER BY column
)


The three important concepts are:

โ€ข OVER() โ†’ Defines the window.

โ€ข PARTITION BY โ†’ Divides rows into groups.

โ€ข ORDER BY โ†’ Defines the order inside each group.

๐Ÿ”น 3. ROW_NUMBER()

Assigns a unique sequential number to each row.

SELECT
Employee,
Department,
Salary,
ROW_NUMBER() OVER (
PARTITION BY Department
ORDER BY Salary DESC
) AS Row_Num
FROM Employees;


Result:

Employee | Department | Salary | Row_Num
Mike | IT | 90,000 | 1
Lisa | IT | 90,000 | 2
John | IT | 75,000 | 3
Alice | HR | 70,000 | 1
Sarah | HR | 60,000 | 2


โš ๏ธ If salaries are tied, ROW_NUMBER() still assigns different numbers.

๐Ÿ”น 4. RANK()

Gives the same rank to tied values.

For: 100, 100, 90

RANK() produces: 1, 1, 3

The next rank is skipped.

RANK() OVER (
PARTITION BY Department
ORDER BY Salary DESC
) AS Salary_Rank


๐Ÿ”น 5. DENSE_RANK()

Also gives the same rank to tied values, but doesn't skip the next rank.

For: 100, 100, 90

DENSE_RANK() produces: 1, 1, 2

๐Ÿง  Remember the Difference

For values: 100, 100, 90, 80

Function     | Result
ROW_NUMBER() | 1, 2, 3, 4
RANK() | 1, 1, 3, 4
DENSE_RANK() | 1, 1, 2, 3


This difference is a very common SQL interview topic.

๐Ÿ”น 6. Overall Ranking

Remove PARTITION BY when you want to rank across the entire dataset.

SELECT
Employee,
Salary,
RANK() OVER (
ORDER BY Salary DESC
) AS Overall_Rank
FROM Employees;


๐Ÿ”น 7. Top N Employees Per Department

One of the most useful real-world applications.

WITH Ranked_Employees AS (
SELECT
Employee,
Department,
Salary,
ROW_NUMBER() OVER (
PARTITION BY Department
ORDER BY Salary DESC
) AS rn
FROM Employees
)

SELECT
Employee,
Department,
Salary
FROM Ranked_Employees
WHERE rn <= 2;


This finds the top 2 employees in every department.

This pattern is extremely important:

Window Function โ†’ CTE/Subquery โ†’ Filter

๐Ÿ”น 8. LAG()

LAG() lets you access a value from a previous row.

For monthly sales:

Month | Sales
Jan | 10,000
Feb | 12,000
Mar | 15,000


SELECT
Sales_Month,
Sales,
LAG(Sales) OVER (
ORDER BY Sales_Month
) AS Previous_Month_Sales
FROM Monthly_Sales;
You can then calculate month-over-month change:

SELECT
Sales_Month,
Sales,
Sales - LAG(Sales) OVER (
ORDER BY Sales_Month
) AS Sales_Change
FROM Monthly_Sales;


๐Ÿ”น 9. LEAD()

LEAD() does the opposite.

It allows you to access the next row.

SELECT
Sales_Month,
Sales,
LEAD(Sales) OVER (
ORDER BY Sales_Month
) AS Next_Month_Sales
FROM Monthly_Sales;


Useful for:

โ€ข Comparing future periods

โ€ข Customer activity

โ€ข Event sequences

โ€ข Next purchase analysis

โ€ข Time-based analysis

๐Ÿ”น 10. Running Total

A running total continuously accumulates values.

SELECT
Order_Date,
Sales,
SUM(Sales) OVER (
ORDER BY Order_Date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS Running_Sales
FROM Orders;


Example: 10,000 โ†’ 15,000 โ†’ 22,000 becomes 10,000 โ†’ 25,000 โ†’ 47,000

๐Ÿ”น 11. Running Total by Region

You can combine PARTITION BY with a running total.

SELECT
Region,
Order_Date,
Sales,
SUM(Sales) OVER (
PARTITION BY Region
ORDER BY Order_Date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS Regional_Running_Sales
FROM Orders;


Each region gets its own running total.

๐Ÿ”น 12. Moving Average

A moving average helps identify trends while reducing short-term fluctuations.

SELECT
Sales_Month,
Sales,
AVG(Sales) OVER (
ORDER BY Sales_Month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS Three_Month_Avg
FROM Monthly_Sales;


This calculates a 3-month moving average.

Useful for:

๐Ÿ“ˆ Sales trends,

๐Ÿ“Š Revenue analysis,

๐Ÿ“ฆ Demand forecasting,

๐Ÿ‘ฅ Customer activity

๐Ÿ”น 13. NTILE()

NTILE() divides rows into approximately equal groups.

For example, divide customers into four sales groups:

SELECT
Customer_ID,
Total_Sales,
NTILE(4) OVER (
ORDER BY Total_Sales DESC
) AS Sales_Quartile
FROM Customers;


This can help identify:

โ€ข Top 25% customers

โ€ข Bottom 25% customers

โ€ข Customer segments

โ€ข Performance groups

๐Ÿ”น 14. Removing Duplicates

Window functions are also extremely useful for deduplication.

WITH Ranked_Data AS (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY Customer_ID, Order_Date, Sales
ORDER BY Order_ID
) AS rn
FROM Orders
)

SELECT *
FROM Ranked_Data
WHERE rn = 1;


This keeps the first record from each duplicate group.

๐Ÿ”น 15. Why Window Functions Cannot Usually Be Used Directly in WHERE

This won't generally work:

SELECT
Employee,
RANK() OVER (ORDER BY Salary DESC) AS Salary_Rank
FROM Employees
WHERE Salary_Rank <= 3;


Why?

Because the window calculation happens after the filtering stage.

Instead, use a CTE:

WITH Ranked AS (
SELECT
Employee,
Salary,
RANK() OVER (
ORDER BY Salary DESC
) AS Salary_Rank
FROM Employees
)
SELECT *
FROM Ranked
WHERE Salary_Rank <= 3;


This is another reason CTEs + Window Functions are such a powerful combination.

๐Ÿ’ผ Real-World Data Analyst Applications

Window functions are commonly used for:

โœ… Top N products by category

โœ… Ranking employees by department

โœ… Customer rankings by region

โœ… Month-over-month growth

โœ… Running revenue totals

โœ… Moving averages

โœ… Finding first/previous/next transactions

โœ… Identifying duplicate records

โœ… Customer purchase sequences

โœ… Performance comparisons

๐ŸŽฏ SQL Interview Challenge

Question: Find the top 3 highest-paid employees in every department.

WITH Ranked_Employees AS (
    SELECT
        Employee,
        Department,
        Salary,
        DENSE_RANK() OVER (
            PARTITION BY Department
            ORDER BY Salary DESC
        ) AS Salary_Rank
    FROM Employees
)
SELECT
    Employee,
    Department,
    Salary
FROM Ranked_Employees
WHERE Salary_Rank <= 3;


๐Ÿ† Double Tap โค๏ธ For More
โค10๐Ÿ”ฅ1
๐Ÿš€ ๐——๐—ฟ๐—ฒ๐—ฎ๐—บ๐—ถ๐—ป๐—ด ๐—ผ๐—ณ ๐—ช๐—ผ๐—ฟ๐—ธ๐—ถ๐—ป๐—ด ๐—ฎ๐˜ ๐—ง๐—ผ๐—ฝ ๐—ง๐—ฒ๐—ฐ๐—ต ๐—–๐—ผ๐—บ๐—ฝ๐—ฎ๐—ป๐—ถ๐—ฒ๐˜€? ๐Ÿ’ป๐Ÿ”ฅ

Hereโ€™s a collection of company-specific resources to help you understand their interview and hiring processes.

๐ŸŽฏ Interview Preparation Guides For:

๐ŸŸ  Amazon โ€“ Interviewing Guide
๐Ÿ”ต Google โ€“ Interview Tips
๐ŸชŸ Microsoft โ€“ Hiring & Interview Tips
๐ŸŸข NVIDIA โ€“ Hiring Process
๐Ÿ”ท Meta โ€“ Software Engineering Interview Prep

๐‹๐ข๐ง๐ค ๐Ÿ‘‡:-

https://pdlink.in/4i6HkgN

๐Ÿ“ข Save & share this with your friends โ€” start learning for FREE!
โค3๐Ÿ‘1