๐ ๐ถ๐ฐ๐ฟ๐ผ๐๐ผ๐ณ๐ ๐ฎ๐ป๐ฑ ๐๐ถ๐ป๐ธ๐ฒ๐ฑ๐๐ป ๐๐ฅ๐๐ ๐๐ฒ๐ฟ๐๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป๐๐
Want to strengthen your resume with career-focused professional skills? Explore these free learning paths from Microsoft and LinkedIn.
๐ฅ Courses Available:
๐ Project Management
๐ Business Analysis
๐ป System Administration
๐ Data Analysis
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlinks.in/micrlink
๐ก Learn โ Get Certified โ Upgrade Your Resume โ Boost Your Career
Want to strengthen your resume with career-focused professional skills? Explore these free learning paths from Microsoft and LinkedIn.
๐ฅ Courses Available:
๐ Project Management
๐ Business Analysis
๐ป System Administration
๐ Data Analysis
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlinks.in/micrlink
๐ก Learn โ Get Certified โ Upgrade Your Resume โ Boost Your Career
โค2๐1๐1
๐๐ผ๐ผ๐ด๐น๐ฒ ๐๐ฅ๐๐ ๐๐ & ๐ ๐ฎ๐ฐ๐ต๐ถ๐ป๐ฒ ๐๐ฒ๐ฎ๐ฟ๐ป๐ถ๐ป๐ด ๐๐ผ๐๐ฟ๐๐ฒ๐ ๐
Explore Google Cloud learning resources covering AI/ML fundamentals through practical and advanced concepts.
๐ Learn AI โ Practice ML โ Build Skills โ Become Career Ready
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlinks.in/eb6
๐ Learn AI โ Practice ML โ Build Skills โ Become Career Ready
Explore Google Cloud learning resources covering AI/ML fundamentals through practical and advanced concepts.
๐ Learn AI โ Practice ML โ Build Skills โ Become Career Ready
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlinks.in/eb6
๐ Learn AI โ Practice ML โ Build Skills โ Become Career Ready
๐2
๐ Data Analyst Roadmap โ Part 10
๐งน Excel โ Level 9: Power Query for Data Cleaning & Transformation
So far, you've learned how to analyze data using Excel formulas and PivotTables.
But there's a major problem with real-world data:
You might receive a monthly Excel file with:
โข Duplicate records
โข Missing values
โข Incorrect data types
โข Extra spaces
โข Inconsistent names
โข Multiple files
โข Unnecessary columns
โข Data spread across different tables
Cleaning this manually every time is slow and error-prone.
That's where Power Query comes in.
1๏ธโฃ What Is Power Query?
Power Query is a data preparation and transformation tool available in Excel and Power BI.
It allows you to: Connect โ Extract โ Transform โ Load - This is commonly called ETL.
Extract: Get data from a source.
Transform: Clean and reshape the data.
Load: Bring the prepared data into Excel for analysis.
The biggest advantage is repeatability. Instead of cleaning the same file manually every month, you create a transformation process once and refresh it.
2๏ธโฃ Why Should a Data Analyst Learn Power Query?
Imagine your company sends you this file every month:
January.xlsx, February.xlsx, March.xlsx, April.xlsx...
Every file contains 50,000 rows, extra spaces, duplicates, incorrect date formats.
Without Power Query, you repeat the same cleaning every month.
With Power Query: Refresh โ Transformations run again
3๏ธโฃ Where Do You Find Power Query?
In modern Excel: Data โ Get & Transform Data
Options: From Table/Range, From Workbook, From Text/CSV, From Folder, From Web, From Database
4๏ธโฃ Understand the Power Query Workflow
Data Source โ Connect โ Power Query Editor โ Clean โ Transform โ Validate โ Load โ Excel / Data Model โ Analysis
Power Query records the transformation steps.
5๏ธโฃ Import Data from Excel & CSV
Excel: Data โ Get Data โ From File โ From Excel Workbook โ Select sheet โ Open in Power Query Editor
CSV: Data โ From Text/CSV โ Preview delimiter, headers, data types โ Transform Data
6๏ธโฃ Power Query Editor
Left side: Queries
Middle: Data preview
Right side: Applied Steps
Example Applied Steps:
Source โ Changed Type โ Removed Columns โ Filtered Rows โ Removed Duplicates โ Renamed Columns โ Added Custom Column
7๏ธโฃ Changing Data Types
Correct data types are critical.
Order ID โ Whole Number, Order Date โ Date, Sales โ Decimal Number, Customer โ Text
Use the data-type icon to change it.
8๏ธโฃ Remove Duplicates
If Order ID should be unique, select the column and use: Remove Rows โ Remove Duplicates
๐ Important: Understand What a Duplicate Means
Don't automatically delete duplicates.
Ask: > Is this actually a duplicate?
Two records with same customer but different orders = Not a duplicate.
Same order appearing twice = Duplicate.
1๏ธโฃ1๏ธโฃ Remove & Rename Columns
Remove unnecessary columns: Home โ Remove Columns
Rename for clarity: CustNm โ Customer Name, SlsAmt โ Sales
1๏ธโฃ2๏ธโฃ Filter Rows
Filtering in Power Query becomes part of the reusable query.
Example: Keep only orders from 2026, or North region, or Sales > 0
1๏ธโฃ3๏ธโฃ Handle Missing Values
Never blindly replace missing values with zero.
๐งน Excel โ Level 9: Power Query for Data Cleaning & Transformation
So far, you've learned how to analyze data using Excel formulas and PivotTables.
But there's a major problem with real-world data:
The data is often messy.
You might receive a monthly Excel file with:
โข Duplicate records
โข Missing values
โข Incorrect data types
โข Extra spaces
โข Inconsistent names
โข Multiple files
โข Unnecessary columns
โข Data spread across different tables
Cleaning this manually every time is slow and error-prone.
That's where Power Query comes in.
1๏ธโฃ What Is Power Query?
Power Query is a data preparation and transformation tool available in Excel and Power BI.
It allows you to: Connect โ Extract โ Transform โ Load - This is commonly called ETL.
Extract: Get data from a source.
Transform: Clean and reshape the data.
Load: Bring the prepared data into Excel for analysis.
The biggest advantage is repeatability. Instead of cleaning the same file manually every month, you create a transformation process once and refresh it.
2๏ธโฃ Why Should a Data Analyst Learn Power Query?
Imagine your company sends you this file every month:
January.xlsx, February.xlsx, March.xlsx, April.xlsx...
Every file contains 50,000 rows, extra spaces, duplicates, incorrect date formats.
Without Power Query, you repeat the same cleaning every month.
With Power Query: Refresh โ Transformations run again
3๏ธโฃ Where Do You Find Power Query?
In modern Excel: Data โ Get & Transform Data
Options: From Table/Range, From Workbook, From Text/CSV, From Folder, From Web, From Database
4๏ธโฃ Understand the Power Query Workflow
Data Source โ Connect โ Power Query Editor โ Clean โ Transform โ Validate โ Load โ Excel / Data Model โ Analysis
Power Query records the transformation steps.
5๏ธโฃ Import Data from Excel & CSV
Excel: Data โ Get Data โ From File โ From Excel Workbook โ Select sheet โ Open in Power Query Editor
CSV: Data โ From Text/CSV โ Preview delimiter, headers, data types โ Transform Data
6๏ธโฃ Power Query Editor
Left side: Queries
Middle: Data preview
Right side: Applied Steps
Example Applied Steps:
Source โ Changed Type โ Removed Columns โ Filtered Rows โ Removed Duplicates โ Renamed Columns โ Added Custom Column
7๏ธโฃ Changing Data Types
Correct data types are critical.
Order ID โ Whole Number, Order Date โ Date, Sales โ Decimal Number, Customer โ Text
Use the data-type icon to change it.
8๏ธโฃ Remove Duplicates
If Order ID should be unique, select the column and use: Remove Rows โ Remove Duplicates
๐ Important: Understand What a Duplicate Means
Don't automatically delete duplicates.
Ask: > Is this actually a duplicate?
Two records with same customer but different orders = Not a duplicate.
Same order appearing twice = Duplicate.
1๏ธโฃ1๏ธโฃ Remove & Rename Columns
Remove unnecessary columns: Home โ Remove Columns
Rename for clarity: CustNm โ Customer Name, SlsAmt โ Sales
1๏ธโฃ2๏ธโฃ Filter Rows
Filtering in Power Query becomes part of the reusable query.
Example: Keep only orders from 2026, or North region, or Sales > 0
1๏ธโฃ3๏ธโฃ Handle Missing Values
Never blindly replace missing values with zero.
โค2
A missing salary doesn't mean Salary = 0, it means it wasn't provided.
1๏ธโฃ4๏ธโฃ Replace Values
Standardize inconsistent entries:
North, NORTH, north, N โ North
Use: Replace Values
1๏ธโฃ5๏ธโฃ Trim and Clean Text
Transform " John Smith " โ "John Smith"
Trim whitespace, Clean non-printing characters, Change case
1๏ธโฃ6๏ธโฃ Split Columns
John-Smith โ First Name: John, Last Name: Smith
Use: Split Column โ By Delimiter โ "-"
1๏ธโฃ7๏ธโฃ Merge Columns
John + Smith โ John Smith
Use: Merge Columns with space separator
2๏ธโฃ0๏ธโฃ Add Custom Columns
Sales: 100,000, Cost: 70,000 โ Profit = Sales - Cost = 30,000
Profit Margin = Profit / Sales
2๏ธโฃ1๏ธโฃ Conditional Columns
IF Sales >= 100000 THEN "High" ELSE IF Sales >= 50000 THEN "Medium" ELSE "Low"
Similar to Excel's IF()
2๏ธโฃ2๏ธโฃ Merge Queries (The most important concept)
Sales: Product ID, Sales
Products: Product ID, Product, Category
Use: Merge Queries โ Match Product ID โ This is like a JOIN in SQL.
SQL: SELECT * FROM Sales LEFT JOIN Products ON Sales.ProductID = Products.ProductID;
2๏ธโฃ3๏ธโฃ Append Queries
Merge = Add columns by matching keys
Append = Add rows by stacking
Jan (1001, 1002) + Feb (1003, 1004) โ 1001, 1002, 1003, 1004
2๏ธโฃ4๏ธโฃ Group By
Region: North 50K, North 70K โ Group by Region, Sum Sales โ North 120K
Similar to SQL GROUP BY
2๏ธโฃ5๏ธโฃ Pivot and Unpivot
This is critical for reports designed for humans:
Before:
Region | Jan | Feb | Mar
North | 50K | 60K | 70K
After Unpivot:
Region | Month | Sales
North | Jan | 50K
North | Feb | 60K
This structure is much better for analysis.
2๏ธโฃ6๏ธโฃ Applied Steps = Your Superpower
Source โ Changed Type โ Removed Columns โ Trimmed Text โ Removed Duplicates โ Filtered Rows โ Added Profit โ Merged Products
When new data arrives, just Refresh.
๐งช Practical Interview Challenge
Messy file with: Duplicate Order IDs, Extra spaces, Sales as text, Missing regions, Product info in another file
Strong approach:
1. Import into Power Query
2. Set correct data types
3. Trim and clean text
4. Investigate duplicates
5. Handle missing regions per business rules
6. Merge Product lookup table
7. Add Profit column
8. Filter invalid records
9. Review Applied Steps
10. Load cleaned dataset
๐ Key Lesson
Instead of: > "How do I clean this file?"
Think: > "How do I build a repeatable process that cleans this type of data every time?"
That's the difference between manually manipulating spreadsheets and building a professional analytics workflow.
Remember:
Merge = Add columns by matching data
Append = Add rows
Group By = Summarize
Unpivot = Convert columns into rows
Applied Steps = Record your process
Refresh = Run the process again
Double Tap โค๏ธ For Part-11
1๏ธโฃ4๏ธโฃ Replace Values
Standardize inconsistent entries:
North, NORTH, north, N โ North
Use: Replace Values
1๏ธโฃ5๏ธโฃ Trim and Clean Text
Transform " John Smith " โ "John Smith"
Trim whitespace, Clean non-printing characters, Change case
1๏ธโฃ6๏ธโฃ Split Columns
John-Smith โ First Name: John, Last Name: Smith
Use: Split Column โ By Delimiter โ "-"
1๏ธโฃ7๏ธโฃ Merge Columns
John + Smith โ John Smith
Use: Merge Columns with space separator
2๏ธโฃ0๏ธโฃ Add Custom Columns
Sales: 100,000, Cost: 70,000 โ Profit = Sales - Cost = 30,000
Profit Margin = Profit / Sales
2๏ธโฃ1๏ธโฃ Conditional Columns
IF Sales >= 100000 THEN "High" ELSE IF Sales >= 50000 THEN "Medium" ELSE "Low"
Similar to Excel's IF()
2๏ธโฃ2๏ธโฃ Merge Queries (The most important concept)
Sales: Product ID, Sales
Products: Product ID, Product, Category
Use: Merge Queries โ Match Product ID โ This is like a JOIN in SQL.
SQL: SELECT * FROM Sales LEFT JOIN Products ON Sales.ProductID = Products.ProductID;
2๏ธโฃ3๏ธโฃ Append Queries
Merge = Add columns by matching keys
Append = Add rows by stacking
Jan (1001, 1002) + Feb (1003, 1004) โ 1001, 1002, 1003, 1004
2๏ธโฃ4๏ธโฃ Group By
Region: North 50K, North 70K โ Group by Region, Sum Sales โ North 120K
Similar to SQL GROUP BY
2๏ธโฃ5๏ธโฃ Pivot and Unpivot
This is critical for reports designed for humans:
Before:
Region | Jan | Feb | Mar
North | 50K | 60K | 70K
After Unpivot:
Region | Month | Sales
North | Jan | 50K
North | Feb | 60K
This structure is much better for analysis.
2๏ธโฃ6๏ธโฃ Applied Steps = Your Superpower
Source โ Changed Type โ Removed Columns โ Trimmed Text โ Removed Duplicates โ Filtered Rows โ Added Profit โ Merged Products
When new data arrives, just Refresh.
๐งช Practical Interview Challenge
Messy file with: Duplicate Order IDs, Extra spaces, Sales as text, Missing regions, Product info in another file
Strong approach:
1. Import into Power Query
2. Set correct data types
3. Trim and clean text
4. Investigate duplicates
5. Handle missing regions per business rules
6. Merge Product lookup table
7. Add Profit column
8. Filter invalid records
9. Review Applied Steps
10. Load cleaned dataset
๐ Key Lesson
Instead of: > "How do I clean this file?"
Think: > "How do I build a repeatable process that cleans this type of data every time?"
That's the difference between manually manipulating spreadsheets and building a professional analytics workflow.
Remember:
Merge = Add columns by matching data
Append = Add rows
Group By = Summarize
Unpivot = Convert columns into rows
Applied Steps = Record your process
Refresh = Run the process again
Double Tap โค๏ธ For Part-11
โค8๐1
๐ Data Analyst Roadmap โ Part 11
๐๏ธ SQL โ Level 1: SQL Fundamentals & Databases
You've completed the major Excel section of the roadmap.
Now we're moving to one of the most important skills for a Data Analyst: SQL
If Excel helps you analyze spreadsheet-based data, SQL helps you work directly with data stored in databases.
A Data Analyst should be able to use SQL to:
โข Retrieve data
โข Filter records
โข Sort results
โข Summarize information
โข Join tables
โข Find trends
โข Calculate KPIs
โข Investigate business problems
1๏ธโฃ What Is SQL?
SQL stands for: Structured Query Language
It's a language used to communicate with relational databases.
For example, suppose a company stores millions of sales records in a database.
Instead of opening a huge spreadsheet, you can ask the database:
Or:
Or:
SQL allows you to ask these questions directly.
2๏ธโฃ Why Is SQL Important for Data Analysts?
Imagine a company has:
50 million transactions.
Excel isn't the right tool for storing and querying all that information.
The data may be stored in a database such as:
โข PostgreSQL
โข MySQL
โข Microsoft SQL Server
โข Oracle Database
โข Snowflake
โข BigQuery
As a Data Analyst, you may connect to the database and use SQL to extract the data you need.
A typical workflow looks like:
Database
โ
SQL Query
โ
Required Data
โ
Analysis
โ
Dashboard / Report
โ
Business Decision
3๏ธโฃ What Is a Database?
A database is a system used to store and manage data.
For example, an e-commerce company might have:
โข Customers
โข Products
โข Orders
โข Payments
โข Employees
Each represents a different type of information.
Instead of putting everything into one enormous table, relational databases typically organize related information into separate tables.
4๏ธโฃ What Is a Table?
A table is a structured collection of data organized into:
Rows + Columns
For example:
Customers
Customer_ID Customer_Name City
101 John Mumbai
102 Sarah Pune
103 Mike Delhi
Each row represents one customer.
Each column represents an attribute.
This should look familiar from Excel.
5๏ธโฃ Rows vs Columns
Just like Excel:
Row
Represents a record.
Example:
101 | John | Mumbai
represents one customer.
Column
Represents an attribute.
For example:
โข Customer_ID
โข Customer_Name
โข City
A useful rule:
6๏ธโฃ What Is a Primary Key?
A Primary Key uniquely identifies each record in a table.
For example:
Customer_ID Customer_Name
101 John
102 Sarah
103 Mike
Here:
Customer_ID
can be the primary key.
Each customer should have a unique ID.
101 โ John
102 โ Sarah
103 โ Mike
You shouldn't have two different customers with the same primary key.
7๏ธโฃ What Is a Foreign Key?
A Foreign Key is a column used to establish a relationship between tables.
Suppose:
Customers
Customer_ID Customer_Name
101 John
102 Sarah
Orders
Order_ID Customer_ID Sales
5001 101 50,000
5002 102 70,000
5003 101 30,000
Here:
Customers.Customer_ID
is the primary key.
Orders.Customer_ID
can be a foreign key.
๐๏ธ SQL โ Level 1: SQL Fundamentals & Databases
You've completed the major Excel section of the roadmap.
Now we're moving to one of the most important skills for a Data Analyst: SQL
If Excel helps you analyze spreadsheet-based data, SQL helps you work directly with data stored in databases.
A Data Analyst should be able to use SQL to:
โข Retrieve data
โข Filter records
โข Sort results
โข Summarize information
โข Join tables
โข Find trends
โข Calculate KPIs
โข Investigate business problems
1๏ธโฃ What Is SQL?
SQL stands for: Structured Query Language
It's a language used to communicate with relational databases.
For example, suppose a company stores millions of sales records in a database.
Instead of opening a huge spreadsheet, you can ask the database:
"Give me all sales from the North region."
Or:
"What was total revenue last month?"
Or:
"Which 10 products generated the most revenue?"
SQL allows you to ask these questions directly.
2๏ธโฃ Why Is SQL Important for Data Analysts?
Imagine a company has:
50 million transactions.
Excel isn't the right tool for storing and querying all that information.
The data may be stored in a database such as:
โข PostgreSQL
โข MySQL
โข Microsoft SQL Server
โข Oracle Database
โข Snowflake
โข BigQuery
As a Data Analyst, you may connect to the database and use SQL to extract the data you need.
A typical workflow looks like:
Database
โ
SQL Query
โ
Required Data
โ
Analysis
โ
Dashboard / Report
โ
Business Decision
3๏ธโฃ What Is a Database?
A database is a system used to store and manage data.
For example, an e-commerce company might have:
โข Customers
โข Products
โข Orders
โข Payments
โข Employees
Each represents a different type of information.
Instead of putting everything into one enormous table, relational databases typically organize related information into separate tables.
4๏ธโฃ What Is a Table?
A table is a structured collection of data organized into:
Rows + Columns
For example:
Customers
Customer_ID Customer_Name City
101 John Mumbai
102 Sarah Pune
103 Mike Delhi
Each row represents one customer.
Each column represents an attribute.
This should look familiar from Excel.
5๏ธโฃ Rows vs Columns
Just like Excel:
Row
Represents a record.
Example:
101 | John | Mumbai
represents one customer.
Column
Represents an attribute.
For example:
โข Customer_ID
โข Customer_Name
โข City
A useful rule:
One row = one record
One column = one attribute
6๏ธโฃ What Is a Primary Key?
A Primary Key uniquely identifies each record in a table.
For example:
Customer_ID Customer_Name
101 John
102 Sarah
103 Mike
Here:
Customer_ID
can be the primary key.
Each customer should have a unique ID.
101 โ John
102 โ Sarah
103 โ Mike
You shouldn't have two different customers with the same primary key.
7๏ธโฃ What Is a Foreign Key?
A Foreign Key is a column used to establish a relationship between tables.
Suppose:
Customers
Customer_ID Customer_Name
101 John
102 Sarah
Orders
Order_ID Customer_ID Sales
5001 101 50,000
5002 102 70,000
5003 101 30,000
Here:
Customers.Customer_ID
is the primary key.
Orders.Customer_ID
can be a foreign key.
โค2
This allows us to connect orders to customers.
8๏ธโฃ Understanding Relationships
The relationship is:
Customers
Customer_ID
โ
Orders
One customer can have multiple orders.
For example:
John
โ
Order 5001
Order 5003
Order 5010
This is a:
One-to-Many relationship
It's one of the most important database concepts for Data Analysts.
9๏ธโฃ What Is a Relational Database?
A relational database stores data in related tables.
For example:
Customers
โ
Orders
โ
Order Details
โ
Products
Instead of storing the customer's name repeatedly in every order, the database can store:
Customer_ID
and retrieve the customer information through relationships.
This helps reduce unnecessary duplication.
๐ What Is SQL Syntax?
SQL queries generally consist of keywords and expressions.
For example:
SELECT *
FROM Customers;
This asks:
Let me break it down.
SELECT: Specifies what you want to retrieve.
FROM: Specifies the table.
Customers: The table you're querying.
1๏ธโฃ1๏ธโฃ SELECT
SELECT is one of the first SQL commands you need to learn.
Suppose you have:
Employees
Employee_ID Name Department Salary
101 John IT 75,000
102 Sarah HR 60,000
103 Mike Finance 82,000
To retrieve all columns:
SELECT *
FROM Employees;
1๏ธโฃ2๏ธโฃ Selecting Specific Columns
You don't always need every column.
Suppose you only want:
Name and Department
Use:
SELECT Name, Department
FROM Employees;
Result:
Name Department
John IT
Sarah HR
Mike Finance
This is generally better than using SELECT * when you only need specific fields.
1๏ธโฃ3๏ธโฃ Why Avoid SELECT * in Production Queries?
You may see beginners writing:
SELECT *
FROM Employees;
all the time.
It's useful while learning and exploring data.
But in production queries, explicitly selecting the required columns is often better because:
โข It makes the query clearer
โข It avoids retrieving unnecessary data
โข It can reduce data transfer
โข It makes downstream dependencies more predictable
For example:
SELECT Employee_ID, Name, Salary
FROM Employees;
is more intentional.
1๏ธโฃ4๏ธโฃ WHERE
WHERE filters records.
Suppose you want employees from IT.
SELECT *
FROM Employees
WHERE Department = 'IT';
Result:
Employee_ID Name Department Salary
101 John IT 75,000
The database only returns records satisfying the condition.
1๏ธโฃ5๏ธโฃ Filtering Numeric Values
Suppose you want employees earning more than โน70,000.
SELECT *
FROM Employees
WHERE Salary > 70000;
Result:
Employee_ID Name Department Salary
101 John IT 75,000
103 Mike Finance 82,000
1๏ธโฃ6๏ธโฃ Comparison Operators
You should know these operators:
Operator Meaning
= Equal to
<> Not equal to
Examples:
WHERE Salary >= 80000
WHERE Department <> 'HR'
1๏ธโฃ7๏ธโฃ AND
AND requires all conditions to be true.
Suppose you want:
IT employees earning more than โน70,000.
SELECT *
FROM Employees
WHERE Department = 'IT'
AND Salary > 70000;
The record must satisfy both conditions.
Think:
IT
AND
Salary > 70,000
1๏ธโฃ8๏ธโฃ OR
OR requires at least one condition to be true.
Suppose you want:
IT or Finance employees.
8๏ธโฃ Understanding Relationships
The relationship is:
Customers
Customer_ID
โ
Orders
One customer can have multiple orders.
For example:
John
โ
Order 5001
Order 5003
Order 5010
This is a:
One-to-Many relationship
It's one of the most important database concepts for Data Analysts.
9๏ธโฃ What Is a Relational Database?
A relational database stores data in related tables.
For example:
Customers
โ
Orders
โ
Order Details
โ
Products
Instead of storing the customer's name repeatedly in every order, the database can store:
Customer_ID
and retrieve the customer information through relationships.
This helps reduce unnecessary duplication.
๐ What Is SQL Syntax?
SQL queries generally consist of keywords and expressions.
For example:
SELECT *
FROM Customers;
This asks:
Return all columns from the Customers table.
Let me break it down.
SELECT: Specifies what you want to retrieve.
FROM: Specifies the table.
Customers: The table you're querying.
1๏ธโฃ1๏ธโฃ SELECT
SELECT is one of the first SQL commands you need to learn.
Suppose you have:
Employees
Employee_ID Name Department Salary
101 John IT 75,000
102 Sarah HR 60,000
103 Mike Finance 82,000
To retrieve all columns:
SELECT *
FROM Employees;
1๏ธโฃ2๏ธโฃ Selecting Specific Columns
You don't always need every column.
Suppose you only want:
Name and Department
Use:
SELECT Name, Department
FROM Employees;
Result:
Name Department
John IT
Sarah HR
Mike Finance
This is generally better than using SELECT * when you only need specific fields.
1๏ธโฃ3๏ธโฃ Why Avoid SELECT * in Production Queries?
You may see beginners writing:
SELECT *
FROM Employees;
all the time.
It's useful while learning and exploring data.
But in production queries, explicitly selecting the required columns is often better because:
โข It makes the query clearer
โข It avoids retrieving unnecessary data
โข It can reduce data transfer
โข It makes downstream dependencies more predictable
For example:
SELECT Employee_ID, Name, Salary
FROM Employees;
is more intentional.
1๏ธโฃ4๏ธโฃ WHERE
WHERE filters records.
Suppose you want employees from IT.
SELECT *
FROM Employees
WHERE Department = 'IT';
Result:
Employee_ID Name Department Salary
101 John IT 75,000
The database only returns records satisfying the condition.
1๏ธโฃ5๏ธโฃ Filtering Numeric Values
Suppose you want employees earning more than โน70,000.
SELECT *
FROM Employees
WHERE Salary > 70000;
Result:
Employee_ID Name Department Salary
101 John IT 75,000
103 Mike Finance 82,000
1๏ธโฃ6๏ธโฃ Comparison Operators
You should know these operators:
Operator Meaning
= Equal to
<> Not equal to
Greater than
< Less than
= Greater than or equal
<= Less than or equal
Examples:
WHERE Salary >= 80000
WHERE Department <> 'HR'
1๏ธโฃ7๏ธโฃ AND
AND requires all conditions to be true.
Suppose you want:
IT employees earning more than โน70,000.
SELECT *
FROM Employees
WHERE Department = 'IT'
AND Salary > 70000;
The record must satisfy both conditions.
Think:
IT
AND
Salary > 70,000
1๏ธโฃ8๏ธโฃ OR
OR requires at least one condition to be true.
Suppose you want:
IT or Finance employees.
SELECT *
FROM Employees
WHERE Department = 'IT'
OR Department = 'Finance';
Both departments will be included.
1๏ธโฃ9๏ธโฃ IN
When checking multiple values, IN makes your query cleaner.
Instead of:
WHERE Department = 'IT'
OR Department = 'Finance'
OR Department = 'HR'
you can write:
WHERE Department IN ('IT', 'Finance', 'HR');
This is easier to read and maintain.
2๏ธโฃ0๏ธโฃ NOT IN
You can exclude multiple values.
SELECT *
FROM Employees
WHERE Department NOT IN ('HR', 'Finance');
This returns employees who aren't in those departments.
2๏ธโฃ1๏ธโฃ BETWEEN
BETWEEN checks whether a value falls within a range.
For example:
SELECT *
FROM Employees
WHERE Salary BETWEEN 50000 AND 80000;
This returns salaries within the specified range.
For numeric data, this is often useful for:
โข Salary ranges
โข Sales ranges
โข Age ranges
โข Scores
โข Transaction values
2๏ธโฃ2๏ธโฃ LIKE
LIKE is used for pattern matching.
Suppose you want employees whose names start with J.
SELECT *
FROM Employees
WHERE Name LIKE 'J%';
% means:
So this could match:
โข John
โข James
โข Jennifer
2๏ธโฃ3๏ธโฃ LIKE with Wildcards
โข
Starts with J
LIKE 'J%'
โข
Ends with n
LIKE '%n'
โข
Contains "oh"
LIKE '%oh%'
Wildcards are extremely useful when searching text data.
2๏ธโฃ4๏ธโฃ DISTINCT
DISTINCT removes duplicate values from the result.
Suppose your employee table contains:
โข IT
โข HR
โข IT
โข Finance
โข HR
โข IT
Use:
SELECT DISTINCT Department
FROM Employees;
Result:
IT
HR
Finance
This is useful for discovering categories in a dataset.
2๏ธโฃ5๏ธโฃ ORDER BY
ORDER BY sorts your results.
Suppose you want employees with the highest salary first.
SELECT *
FROM Employees
ORDER BY Salary DESC;
DESC means:
Descending
Highest โ Lowest
2๏ธโฃ6๏ธโฃ ASC
ASC means ascending.
SELECT *
FROM Employees
ORDER BY Salary ASC;
Lowest โ Highest
Ascending is generally the default sort direction.
2๏ธโฃ7๏ธโฃ LIMIT / TOP
The syntax depends on the database system.
In systems such as PostgreSQL and MySQL:
SELECT *
FROM Employees
ORDER BY Salary DESC
LIMIT 5;
This returns the top 5 employees by salary.
In SQL Server, you would commonly use:
SELECT TOP 5 *
FROM Employees
ORDER BY Salary DESC;
This is an important point:
2๏ธโฃ8๏ธโฃ Aliases
Aliases give columns or tables temporary names within a query.
For example:
SELECT
Name AS Employee_Name,
Salary AS Annual_Salary
FROM Employees;
The result displays:
Employee_Name Annual_Salary
John 75,000
Sarah 60,000
Aliases make results easier to understand.
2๏ธโฃ9๏ธโฃ SQL Comments
You can add comments to explain your queries.
For example:
-- Get employees earning more than 70,000
SELECT Name, Salary
FROM Employees
WHERE Salary > 70000;
Comments don't affect the query result.
They're useful when queries become complex.
๐งช Practical Interview Challenge
Suppose you have:
Employees
ID Name Department Salary
101 John IT 75,000
102 Sarah HR 60,000
103 Mike Finance 82,000
104 David IT 90,000
105 Alice HR 65,000
Q1. Retrieve all employees.
SELECT *
FROM Employees;
Q2. Retrieve only names and salaries.
SELECT Name, Salary
FROM Employees;
Q3. Find employees earning more than โน70,000.
SELECT *
FROM Employees
WHERE Salary > 70000;
Q4. Find IT employees.
SELECT *
FROM Employees
WHERE Department = 'IT';
Q5. Find IT or Finance employees.
SELECT *
FROM Employees
WHERE Department IN ('IT', 'Finance');
Q6. Sort employees by salary from highest to lowest.
SELECT *
FROM Employees
ORDER BY Salary DESC;
Q7. Find the top 3 highest-paid employees.
PostgreSQL/MySQL:
SELECT *
FROM Employees
ORDER BY Salary DESC
LIMIT 3;
SQL Server:
SELECT TOP 3 *
FROM Employees
ORDER BY Salary DESC;
Q8. List unique departments.
SELECT DISTINCT Department
FROM Employees;
๐ Double Tap โค๏ธ For More
FROM Employees
WHERE Department = 'IT'
OR Department = 'Finance';
Both departments will be included.
1๏ธโฃ9๏ธโฃ IN
When checking multiple values, IN makes your query cleaner.
Instead of:
WHERE Department = 'IT'
OR Department = 'Finance'
OR Department = 'HR'
you can write:
WHERE Department IN ('IT', 'Finance', 'HR');
This is easier to read and maintain.
2๏ธโฃ0๏ธโฃ NOT IN
You can exclude multiple values.
SELECT *
FROM Employees
WHERE Department NOT IN ('HR', 'Finance');
This returns employees who aren't in those departments.
2๏ธโฃ1๏ธโฃ BETWEEN
BETWEEN checks whether a value falls within a range.
For example:
SELECT *
FROM Employees
WHERE Salary BETWEEN 50000 AND 80000;
This returns salaries within the specified range.
For numeric data, this is often useful for:
โข Salary ranges
โข Sales ranges
โข Age ranges
โข Scores
โข Transaction values
2๏ธโฃ2๏ธโฃ LIKE
LIKE is used for pattern matching.
Suppose you want employees whose names start with J.
SELECT *
FROM Employees
WHERE Name LIKE 'J%';
% means:
Any number of characters.
So this could match:
โข John
โข James
โข Jennifer
2๏ธโฃ3๏ธโฃ LIKE with Wildcards
โข
Starts with J
LIKE 'J%'
โข
Ends with n
LIKE '%n'
โข
Contains "oh"
LIKE '%oh%'
Wildcards are extremely useful when searching text data.
2๏ธโฃ4๏ธโฃ DISTINCT
DISTINCT removes duplicate values from the result.
Suppose your employee table contains:
โข IT
โข HR
โข IT
โข Finance
โข HR
โข IT
Use:
SELECT DISTINCT Department
FROM Employees;
Result:
IT
HR
Finance
This is useful for discovering categories in a dataset.
2๏ธโฃ5๏ธโฃ ORDER BY
ORDER BY sorts your results.
Suppose you want employees with the highest salary first.
SELECT *
FROM Employees
ORDER BY Salary DESC;
DESC means:
Descending
Highest โ Lowest
2๏ธโฃ6๏ธโฃ ASC
ASC means ascending.
SELECT *
FROM Employees
ORDER BY Salary ASC;
Lowest โ Highest
Ascending is generally the default sort direction.
2๏ธโฃ7๏ธโฃ LIMIT / TOP
The syntax depends on the database system.
In systems such as PostgreSQL and MySQL:
SELECT *
FROM Employees
ORDER BY Salary DESC
LIMIT 5;
This returns the top 5 employees by salary.
In SQL Server, you would commonly use:
SELECT TOP 5 *
FROM Employees
ORDER BY Salary DESC;
This is an important point:
SQL is a language, but different database systems have slightly different syntax.
2๏ธโฃ8๏ธโฃ Aliases
Aliases give columns or tables temporary names within a query.
For example:
SELECT
Name AS Employee_Name,
Salary AS Annual_Salary
FROM Employees;
The result displays:
Employee_Name Annual_Salary
John 75,000
Sarah 60,000
Aliases make results easier to understand.
2๏ธโฃ9๏ธโฃ SQL Comments
You can add comments to explain your queries.
For example:
-- Get employees earning more than 70,000
SELECT Name, Salary
FROM Employees
WHERE Salary > 70000;
Comments don't affect the query result.
They're useful when queries become complex.
๐งช Practical Interview Challenge
Suppose you have:
Employees
ID Name Department Salary
101 John IT 75,000
102 Sarah HR 60,000
103 Mike Finance 82,000
104 David IT 90,000
105 Alice HR 65,000
Q1. Retrieve all employees.
SELECT *
FROM Employees;
Q2. Retrieve only names and salaries.
SELECT Name, Salary
FROM Employees;
Q3. Find employees earning more than โน70,000.
SELECT *
FROM Employees
WHERE Salary > 70000;
Q4. Find IT employees.
SELECT *
FROM Employees
WHERE Department = 'IT';
Q5. Find IT or Finance employees.
SELECT *
FROM Employees
WHERE Department IN ('IT', 'Finance');
Q6. Sort employees by salary from highest to lowest.
SELECT *
FROM Employees
ORDER BY Salary DESC;
Q7. Find the top 3 highest-paid employees.
PostgreSQL/MySQL:
SELECT *
FROM Employees
ORDER BY Salary DESC
LIMIT 3;
SQL Server:
SELECT TOP 3 *
FROM Employees
ORDER BY Salary DESC;
Q8. List unique departments.
SELECT DISTINCT Department
FROM Employees;
๐ Double Tap โค๏ธ For More
โค20
๐ Data Analyst Roadmap โ Part 12
๐๏ธ SQL โ Level 2: Aggregate Functions, GROUP BY & HAVING
Now that you've learned SQL fundamentals, it's time to move from retrieving individual records to summarizing data.
This is one of the most important SQL skills for Data Analysts.
In real interviews and jobs, you'll frequently be asked questions like:
To answer these questions, you need:
Aggregate Functions + GROUP BY + HAVING
1๏ธโฃ What Are Aggregate Functions?
Aggregate functions perform calculations across multiple rows and return a summarized result.
The most important ones are:
SUM()
COUNT()
AVG()
MIN()
MAX()
Think of them as the SQL equivalent of the basic Excel functions you learned earlier.
2๏ธโฃ SUM()
SUM() calculates the total of a numeric column.
Suppose you have:
Order_ID: 1001, Sales: 50,000
Order_ID: 1002, Sales: 70,000
Order_ID: 1003, Sales: 30,000
Query:
Result:
Total_Sales = 150,000
Business question
Answer โ SUM()
3๏ธโฃ COUNT()
COUNT() counts records.
If there are 10,000 orders:
Total_Orders = 10,000
Why COUNT(*)?
COUNT(*) counts rows.
This is often useful when you want the total number of records.
4๏ธโฃ COUNT(Column)
You can also count values in a specific column.
One important distinction:
COUNT(column) generally doesn't count NULL values.
Whereas:
COUNT(*)
counts rows regardless of whether individual columns contain NULLs.
5๏ธโฃ COUNT(DISTINCT)
Suppose your Orders table contains:
Order 1001 โ Customer 101
Order 1002 โ Customer 102
Order 1003 โ Customer 101
Order 1004 โ Customer 103
There are:
4 orders
but only:
3 unique customers
Use:
Result:
3
This is extremely important in analytics.
6๏ธโฃ AVG()
AVG() calculates the average.
Suppose salaries are:
50,000, 60,000, 70,000
Query:
Result:
60,000
Business questions
Answer โ AVG()
7๏ธโฃ MIN()
MIN() returns the smallest value.
Example result:
35,000
Useful for:
Minimum salary
Lowest sales
Earliest date
Lowest transaction value
8๏ธโฃ MAX()
MAX() returns the largest value.
Result:
150,000
Useful for:
Highest salary
Highest sales
Largest transaction
Latest date
9๏ธโฃ Using Multiple Aggregate Functions
You can use several aggregate functions in one query.
๐๏ธ SQL โ Level 2: Aggregate Functions, GROUP BY & HAVING
Now that you've learned SQL fundamentals, it's time to move from retrieving individual records to summarizing data.
This is one of the most important SQL skills for Data Analysts.
In real interviews and jobs, you'll frequently be asked questions like:
What is the total sales by region?
What is the average salary by department?
How many customers are in each city?
Which products generated more than โน10 lakh in sales?
To answer these questions, you need:
Aggregate Functions + GROUP BY + HAVING
1๏ธโฃ What Are Aggregate Functions?
Aggregate functions perform calculations across multiple rows and return a summarized result.
The most important ones are:
SUM()
COUNT()
AVG()
MIN()
MAX()
Think of them as the SQL equivalent of the basic Excel functions you learned earlier.
2๏ธโฃ SUM()
SUM() calculates the total of a numeric column.
Suppose you have:
Order_ID: 1001, Sales: 50,000
Order_ID: 1002, Sales: 70,000
Order_ID: 1003, Sales: 30,000
Query:
SELECT SUM(Sales) AS Total_Sales
FROM Orders;
Result:
Total_Sales = 150,000
Business question
What is our total revenue?
Answer โ SUM()
3๏ธโฃ COUNT()
COUNT() counts records.
SELECT COUNT(*) AS Total_Orders
FROM Orders;
If there are 10,000 orders:
Total_Orders = 10,000
Why COUNT(*)?
COUNT(*) counts rows.
This is often useful when you want the total number of records.
4๏ธโฃ COUNT(Column)
You can also count values in a specific column.
SELECT COUNT(Customer_ID) AS Customer_Count
FROM Orders;
One important distinction:
COUNT(column) generally doesn't count NULL values.
Whereas:
COUNT(*)
counts rows regardless of whether individual columns contain NULLs.
5๏ธโฃ COUNT(DISTINCT)
Suppose your Orders table contains:
Order 1001 โ Customer 101
Order 1002 โ Customer 102
Order 1003 โ Customer 101
Order 1004 โ Customer 103
There are:
4 orders
but only:
3 unique customers
Use:
SELECT COUNT(DISTINCT Customer_ID) AS Unique_Customers
FROM Orders;
Result:
3
This is extremely important in analytics.
6๏ธโฃ AVG()
AVG() calculates the average.
Suppose salaries are:
50,000, 60,000, 70,000
Query:
SELECT AVG(Salary) AS Average_Salary
FROM Employees;
Result:
60,000
Business questions
What is the average order value?
What is the average employee salary?
What is the average product price?
Answer โ AVG()
7๏ธโฃ MIN()
MIN() returns the smallest value.
SELECT MIN(Salary) AS Minimum_Salary
FROM Employees;
Example result:
35,000
Useful for:
Minimum salary
Lowest sales
Earliest date
Lowest transaction value
8๏ธโฃ MAX()
MAX() returns the largest value.
SELECT MAX(Salary) AS Maximum_Salary
FROM Employees;
Result:
150,000
Useful for:
Highest salary
Highest sales
Largest transaction
Latest date
9๏ธโฃ Using Multiple Aggregate Functions
You can use several aggregate functions in one query.
SELECT
SUM(Sales) AS Total_Sales,
AVG(Sales) AS Average_Sales,
MIN(Sales) AS Minimum_Sales,
MAX(Sales) AS Maximum_Sales,
COUNT(*) AS Total_Orders
FROM Orders;
โค3
The process is:
WHERE โ Filter rows
GROUP BY โ Create groups
SUM โ Calculate totals
HAVING โ Filter groups
This sequence is fundamental to SQL analysis.
1๏ธโฃ9๏ธโฃ ORDER BY with GROUP BY
You can sort aggregated results.
Suppose you want regions with the highest sales first:
Result:
North: 500,000, South: 350,000, West: 200,000, East: 150,000
2๏ธโฃ0๏ธโฃ Top 3 Regions
You can combine:
GROUP BY + ORDER BY + LIMIT
For example, in PostgreSQL/MySQL:
This answers:
2๏ธโฃ1๏ธโฃ GROUP BY Dates
Suppose you have:
Order_Date and Sales
You might want:
The exact date function varies by database system.
For example, in PostgreSQL:
Result:
2024: 8,500,000, 2025: 10,200,000, 2026: 12,400,000
2๏ธโฃ2๏ธโฃ Grouping by Month
In PostgreSQL, you can use:
This creates monthly sales totals.
Different SQL platforms have different date functions, so always check the database you're working with.
2๏ธโฃ3๏ธโฃ Calculate Average Order Value
A common business KPI is:
Average Order Value (AOV)
A simple version is:
If each row represents exactly one order.
If the table can contain multiple rows per order, however, you need to calculate the denominator based on distinct orders:
This distinction is extremely important.
2๏ธโฃ4๏ธโฃ COUNT(DISTINCT) in Real Analytics
Suppose a customer places multiple orders:
Customer 101 โ Orders 5001, 5002
Customer 102 โ Order 5003
Customer 103 โ Orders 5004, 5005
Total orders: 5
Unique customers: 3
Query:
Result: 3
This is commonly used for metrics such as:
Active customers
Unique users
Unique accounts
Distinct orders
Distinct products
2๏ธโฃ5๏ธโฃ Conditional Aggregation
One powerful technique is combining CASE WHEN with aggregate functions.
For example:
This allows you to create customized metrics.
You'll use this technique much more in advanced SQL.
2๏ธโฃ6๏ธโฃ Common SQL Analytical Pattern
A very common query structure is:
For example:
WHERE โ Filter rows
GROUP BY โ Create groups
SUM โ Calculate totals
HAVING โ Filter groups
This sequence is fundamental to SQL analysis.
1๏ธโฃ9๏ธโฃ ORDER BY with GROUP BY
You can sort aggregated results.
Suppose you want regions with the highest sales first:
SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region
ORDER BY Total_Sales DESC;
Result:
North: 500,000, South: 350,000, West: 200,000, East: 150,000
2๏ธโฃ0๏ธโฃ Top 3 Regions
You can combine:
GROUP BY + ORDER BY + LIMIT
For example, in PostgreSQL/MySQL:
SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY Region
ORDER BY Total_Sales DESC
LIMIT 3;
This answers:
"Which three regions generated the most sales?"
2๏ธโฃ1๏ธโฃ GROUP BY Dates
Suppose you have:
Order_Date and Sales
You might want:
Total sales by year.
The exact date function varies by database system.
For example, in PostgreSQL:
SELECT
EXTRACT(YEAR FROM Order_Date) AS Sales_Year,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY EXTRACT(YEAR FROM Order_Date)
ORDER BY Sales_Year;
Result:
2024: 8,500,000, 2025: 10,200,000, 2026: 12,400,000
2๏ธโฃ2๏ธโฃ Grouping by Month
In PostgreSQL, you can use:
SELECT
DATE_TRUNC('month', Order_Date) AS Sales_Month,
SUM(Sales) AS Total_Sales
FROM Orders
GROUP BY DATE_TRUNC('month', Order_Date)
ORDER BY Sales_Month;
This creates monthly sales totals.
Different SQL platforms have different date functions, so always check the database you're working with.
2๏ธโฃ3๏ธโฃ Calculate Average Order Value
A common business KPI is:
Average Order Value (AOV)
A simple version is:
SELECT
SUM(Sales) / COUNT(*) AS Average_Order_Value
FROM Orders;
If each row represents exactly one order.
If the table can contain multiple rows per order, however, you need to calculate the denominator based on distinct orders:
SELECT
SUM(Sales) / COUNT(DISTINCT Order_ID) AS Average_Order_Value
FROM Orders;
This distinction is extremely important.
2๏ธโฃ4๏ธโฃ COUNT(DISTINCT) in Real Analytics
Suppose a customer places multiple orders:
Customer 101 โ Orders 5001, 5002
Customer 102 โ Order 5003
Customer 103 โ Orders 5004, 5005
Total orders: 5
Unique customers: 3
Query:
SELECT COUNT(DISTINCT Customer_ID) AS Unique_Customers
FROM Orders;
Result: 3
This is commonly used for metrics such as:
Active customers
Unique users
Unique accounts
Distinct orders
Distinct products
2๏ธโฃ5๏ธโฃ Conditional Aggregation
One powerful technique is combining CASE WHEN with aggregate functions.
For example:
Count how many orders were above โน50,000.
SELECT
SUM(
CASE
WHEN Sales > 50000 THEN 1
ELSE 0
END
) AS High_Value_Orders
FROM Orders;
This allows you to create customized metrics.
You'll use this technique much more in advanced SQL.
2๏ธโฃ6๏ธโฃ Common SQL Analytical Pattern
A very common query structure is:
SELECT
Dimension,
AGGREGATE_FUNCTION(Metric) AS KPI
FROM Table
WHERE Condition
GROUP BY Dimension
HAVING Aggregate_Condition
ORDER BY KPI DESC;
For example:
SELECT
Region,
SUM(Sales) AS Total_Sales
FROM Orders
WHERE Order_Date >= '2026-01-01'
GROUP BY Region
HAVING SUM(Sales) > 100000
ORDER BY Total_Sales DESC;
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:
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:
Result:
North = 120,000, South = 100,000, West = 80,000
Now you've answered:
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:
Result:
Finance: 90,000, HR: 62,500, IT: 78,500
1๏ธโฃ3๏ธโฃ GROUP BY with COUNT()
Question:
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:
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:
The analytical concept is very similar.
You're grouping records and calculating an aggregate.
1๏ธโฃ6๏ธโฃ HAVING
Now suppose you want:
You can't simply use WHERE on the aggregate result.
You use: HAVING
Result:
North = 120,000
1๏ธโฃ7๏ธโฃ WHERE vs HAVING
This is a very common SQL interview question.
WHERE
Filters individual rows before grouping.
Example:
HAVING
Filters groups after aggregation.
Example:
Remember:
1๏ธโฃ8๏ธโฃ WHERE + GROUP BY + HAVING
You can use all three.
Question:
Conceptually:
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.
Q2. Find average sales.
Q3. Find sales by region.
Q4. Count orders by region.
Q5. Find average sales by category.
Q6. Show only regions with sales greater than โน100,000.
Q7. Sort regions by highest sales.
๐ Double Tap โค๏ธ For More
๐งช 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
โค2๐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.
๐ฅ 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:
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:
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.
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:
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
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
6๏ธโฃ CASE WHEN with AND
You can combine multiple conditions.
Suppose an employee qualifies for a bonus if:
Department = IT
Salary > โน80,000
Both conditions must be true.
7๏ธโฃ CASE WHEN with OR
Suppose employees from IT or Finance should receive a particular classification.
๐๏ธ 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:
This counts only orders where Sales is at least โน100,000.
9๏ธโฃ Conditional SUM
Suppose you want:
Use:
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.
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:
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:
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:
This is incorrect for testing NULL.
Instead, use:
To find non-NULL values:
1๏ธโฃ5๏ธโฃ Find Missing Values
Suppose you want customers whose phone numbers are missing:
This is useful for data-quality analysis.
1๏ธโฃ6๏ธโฃ Count Missing Values
You can use conditional aggregation:
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:
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 = NULLThis is incorrect for testing NULL.
Instead, use:
WHERE Email IS NULLTo find non-NULL values:
WHERE Email IS NOT NULL1๏ธโฃ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.
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:
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:
If Sales = 0:
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.
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:
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:
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:
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:
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:
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) โ NULLSo 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:
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.
Q2. Find orders with missing sales.
Q3. Replace missing sales with zero for display.
Remember: this changes the display/calculation result, not necessarily the underlying data.
Q4. Categorize profitability.
Q5. Count high-value orders.
Q6. Calculate profit margin safely.
๐ Double Tap โค๏ธ For More
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
โค8