๐ SQL Roadmap 2026 โ Part 6
GROUP BY & HAVING โ Analyzing Data by Categories ๐
In Part 5, you learned how aggregate functions answer questions like:
But real-world business questions are usually more specific:
That's where GROUP BY comes in.
1๏ธโฃ What is GROUP BY?
GROUP BY combines rows with the same value into groups so that aggregate functions can calculate a metric for each group.
Basic Syntax
Example:
Instead of getting one total employee count, you get a count for each department.
2๏ธโฃ Why Do We Need GROUP BY?
Without GROUP BY:
Result: 1000
This answers: How many employees are there?
But:
Result:
โข IT | 350
โข Finance | 200
โข HR | 120
โข Sales | 330
Now you can answer: How many employees are in each department?
3๏ธโฃ GROUP BY With COUNT()
This is probably the most common GROUP BY pattern.
4๏ธโฃ GROUP BY With SUM()
Suppose you want revenue by city.
This is a common business KPI.
5๏ธโฃ GROUP BY With AVG()
Calculate average salary by department:
6๏ธโฃ GROUP BY With MIN() and MAX()
You can use multiple aggregate functions.
7๏ธโฃ Multiple Aggregations
You aren't limited to one metric.
This is the foundation of many analytical reports.
8๏ธโฃ GROUP BY Multiple Columns
You can group by more than one column.
Example: Count customers by city and customer segment.
SQL creates a group for each unique combination.
9๏ธโฃ Understanding Multiple GROUP BY Columns
Grouping by
โข Mumbai + Premium
โข Mumbai + Standard
โข Delhi + Premium
The combination matters.
๐ GROUP BY With WHERE
WHERE filters rows before grouping.
Example: Calculate revenue by city for completed orders only.
Conceptually: All Orders โ WHERE Completed โ GROUP BY City โ SUM Revenue
1๏ธโฃ1๏ธโฃ WHERE vs GROUP BY
WHERE Answers: Which rows should be included?
GROUP BY Answers: How should those rows be divided into groups?
1๏ธโฃ2๏ธโฃ What is HAVING?
HAVING filters groups after aggregation.
Example: Find departments with more than 100 employees.
GROUP BY & HAVING โ Analyzing Data by Categories ๐
In Part 5, you learned how aggregate functions answer questions like:
What is the total revenue?
How many customers do we have?
But real-world business questions are usually more specific:
What is the revenue by city?
How many employees are there in each department?
Which products generated the most revenue?
That's where GROUP BY comes in.
1๏ธโฃ What is GROUP BY?
GROUP BY combines rows with the same value into groups so that aggregate functions can calculate a metric for each group.
Basic Syntax
SELECT
column_name,
aggregate_function(column)
FROM table_name
GROUP BY column_name;
Example:
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Instead of getting one total employee count, you get a count for each department.
2๏ธโฃ Why Do We Need GROUP BY?
Without GROUP BY:
SELECT COUNT(*) AS total_employees
FROM employees;
Result: 1000
This answers: How many employees are there?
But:
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Result:
โข IT | 350
โข Finance | 200
โข HR | 120
โข Sales | 330
Now you can answer: How many employees are in each department?
3๏ธโฃ GROUP BY With COUNT()
This is probably the most common GROUP BY pattern.
SELECT
city,
COUNT(*) AS customer_count
FROM customers
GROUP BY city;
4๏ธโฃ GROUP BY With SUM()
Suppose you want revenue by city.
SELECT
city,
SUM(amount) AS total_revenue
FROM orders
GROUP BY city;
This is a common business KPI.
5๏ธโฃ GROUP BY With AVG()
Calculate average salary by department:
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department;
6๏ธโฃ GROUP BY With MIN() and MAX()
You can use multiple aggregate functions.
SELECT
department,
MIN(salary) AS minimum_salary,
MAX(salary) AS maximum_salary,
AVG(salary) AS average_salary
FROM employees
GROUP BY department;
7๏ธโฃ Multiple Aggregations
You aren't limited to one metric.
SELECT
department,
COUNT(*) AS employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS minimum_salary,
MAX(salary) AS maximum_salary
FROM employees
GROUP BY department;
This is the foundation of many analytical reports.
8๏ธโฃ GROUP BY Multiple Columns
You can group by more than one column.
Example: Count customers by city and customer segment.
SELECT
city,
customer_segment,
COUNT(*) AS customer_count
FROM customers
GROUP BY
city,
customer_segment;
SQL creates a group for each unique combination.
9๏ธโฃ Understanding Multiple GROUP BY Columns
Grouping by
GROUP BY city, segment creates groups like:โข Mumbai + Premium
โข Mumbai + Standard
โข Delhi + Premium
The combination matters.
๐ GROUP BY With WHERE
WHERE filters rows before grouping.
Example: Calculate revenue by city for completed orders only.
SELECT
city,
SUM(amount) AS revenue
FROM orders
WHERE order_status = 'Completed'
GROUP BY city;
Conceptually: All Orders โ WHERE Completed โ GROUP BY City โ SUM Revenue
1๏ธโฃ1๏ธโฃ WHERE vs GROUP BY
WHERE Answers: Which rows should be included?
GROUP BY Answers: How should those rows be divided into groups?
1๏ธโฃ2๏ธโฃ What is HAVING?
HAVING filters groups after aggregation.
Example: Find departments with more than 100 employees.
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 100;
1๏ธโฃ3๏ธโฃ WHERE vs HAVING
This is one of the most frequently asked SQL interview questions.
WHERE filters individual rows.
WHERE salary > 500000HAVING filters groups.
HAVING AVG(salary) > 800000Remember:
WHERE โ Filter rows
GROUP BY โ Create groups
HAVING โ Filter groups
1๏ธโฃ4๏ธโฃ Example: WHERE + GROUP BY + HAVING
Requirement: Find departments whose average salary is greater than โน8 lakh, considering only employees earning more than โน5 lakh.
SELECT
department,
AVG(salary) AS average_salary
FROM employees
WHERE salary > 500000
GROUP BY department
HAVING AVG(salary) > 800000;
1๏ธโฃ5๏ธโฃ GROUP BY With COUNT(DISTINCT)
Very useful for customer analytics.
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
1๏ธโฃ6๏ธโฃ GROUP BY With CASE
You can create business categories and then group them.
SELECT
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END AS salary_band,
COUNT(*) AS employee_count
FROM employees
GROUP BY
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END;
1๏ธโฃ7๏ธโฃ GROUP BY Dates
This is extremely important for Data Analysts.
Example: Calculate monthly revenue.
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
1๏ธโฃ8๏ธโฃ Daily Sales
SELECT
order_date,
SUM(amount) AS daily_revenue
FROM orders
GROUP BY order_date
ORDER BY order_date;
1๏ธโฃ9๏ธโฃ Monthly Order Count
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(*) AS order_count
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
2๏ธโฃ0๏ธโฃ Monthly Customer Count
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(DISTINCT customer_id) AS active_customers
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
Notice:
COUNT(*) counts orders, while COUNT(DISTINCT customer_id) counts unique customers.2๏ธโฃ1๏ธโฃ GROUP BY With ORDER BY
Example: Find departments with the highest average salary.
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
ORDER BY average_salary DESC;
2๏ธโฃ2๏ธโฃ GROUP BY + HAVING + ORDER BY
A powerful analytical pattern:
SELECT
customer_id,
SUM(amount) AS total_spend
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 50000
ORDER BY total_spend DESC;
2๏ธโฃ3๏ธโฃ Real-World Example: Top Revenue Categories
Requirement: Find categories generating more than โน10 lakh in revenue.
SELECT
p.category,
SUM(oi.quantity * oi.selling_price) AS revenue
FROM products p
JOIN order_items oi
ON p.product_id = oi.product_id
GROUP BY p.category
HAVING SUM(oi.quantity * oi.selling_price) > 1000000
ORDER BY revenue DESC;
2๏ธโฃ4๏ธโฃ Common GROUP BY Error
SELECT
department,
employee_name,
AVG(salary)
FROM employees
GROUP BY department;
โค2
This is generally invalid because
2๏ธโฃ5๏ธโฃ The Golden Rule of GROUP BY
When using GROUP BY, every selected expression generally needs to be either:
1. Included in GROUP BY
2. Or aggregated
Think: Group columns describe the group; aggregate functions summarize the group.
2๏ธโฃ6๏ธโฃ SQL Query Pattern to Memorize
Example:
๐ง Logical Processing Order
A useful simplified model is:
FROM โ WHERE โ GROUP BY โ HAVING โ SELECT โ ORDER BY โ LIMIT
This helps explain why
๐ผ SQL Interview Questions
Q1. What is GROUP BY?
Groups rows with the same values so aggregate functions can calculate metrics for each group.
Q2. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping, while HAVING filters groups after aggregation.
Q3. Can GROUP BY contain multiple columns?
Yes.
Q4. Can GROUP BY be used without an aggregate function?
Yes, although
Q5. Can you use aggregate functions in WHERE?
Generally no. Use HAVING.
Q6. Why do we use COUNT(DISTINCT customer_id)?
To count unique customers rather than counting every transaction.
๐ฏ Practice Questions
Q1. Count employees in each department.
Q2. Calculate total revenue by product category.
Q3. Calculate average salary by department.
Q4. Find the highest salary in each department.
Q5. Count customers by city.
Q6. Find cities with more than 500 customers.
Q7. Calculate monthly revenue.
Q8. Calculate monthly unique customers.
Q9. Find customers whose total spending is greater than โน50,000.
Q10. Find product categories generating more than โน1 lakh revenue, sorted from highest to lowest.
โ Answers
Answer 1
Answer 2
Answer 3
Answer 4
Answer 5
Answer 6
Answer 7
Answer 8
Answer 9
Answer 10
employee_name is neither grouped, nor aggregated.2๏ธโฃ5๏ธโฃ The Golden Rule of GROUP BY
When using GROUP BY, every selected expression generally needs to be either:
1. Included in GROUP BY
2. Or aggregated
Think: Group columns describe the group; aggregate functions summarize the group.
2๏ธโฃ6๏ธโฃ SQL Query Pattern to Memorize
SELECT
grouping_column,
AGGREGATE_FUNCTION(value_column) AS metric
FROM table_name
WHERE row_condition
GROUP BY grouping_column
HAVING group_condition
ORDER BY metric DESC;
Example:
SELECT
city,
SUM(amount) AS revenue
FROM orders
WHERE order_status = 'Completed'
GROUP BY city
HAVING SUM(amount) > 100000
ORDER BY revenue DESC;
๐ง Logical Processing Order
A useful simplified model is:
FROM โ WHERE โ GROUP BY โ HAVING โ SELECT โ ORDER BY โ LIMIT
This helps explain why
WHERE SUM(amount) > 100000 is not valid. Use HAVING instead.๐ผ SQL Interview Questions
Q1. What is GROUP BY?
Groups rows with the same values so aggregate functions can calculate metrics for each group.
Q2. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping, while HAVING filters groups after aggregation.
Q3. Can GROUP BY contain multiple columns?
Yes.
GROUP BY city, category;Q4. Can GROUP BY be used without an aggregate function?
Yes, although
SELECT DISTINCT is often clearer when the goal is simply to return unique combinations.Q5. Can you use aggregate functions in WHERE?
Generally no. Use HAVING.
Q6. Why do we use COUNT(DISTINCT customer_id)?
To count unique customers rather than counting every transaction.
๐ฏ Practice Questions
Q1. Count employees in each department.
Q2. Calculate total revenue by product category.
Q3. Calculate average salary by department.
Q4. Find the highest salary in each department.
Q5. Count customers by city.
Q6. Find cities with more than 500 customers.
Q7. Calculate monthly revenue.
Q8. Calculate monthly unique customers.
Q9. Find customers whose total spending is greater than โน50,000.
Q10. Find product categories generating more than โน1 lakh revenue, sorted from highest to lowest.
โ Answers
Answer 1
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department;
Answer 2
SELECT category, SUM(amount) AS revenue FROM sales GROUP BY category;
Answer 3
SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY department;
Answer 4
SELECT department, MAX(salary) AS highest_salary FROM employees GROUP BY department;
Answer 5
SELECT city, COUNT(*) AS customer_count FROM customers GROUP BY city;
Answer 6
SELECT city, COUNT(*) AS customer_count
FROM customers GROUP BY city HAVING COUNT(*) > 500;
Answer 7
SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY month;Answer 8
SELECT DATE_TRUNC('month', order_date) AS month, COUNT(DISTINCT customer_id) AS unique_customers FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY month;Answer 9
SELECT customer_id, SUM(amount) AS total_spend FROM orders GROUP BY customer_id HAVING SUM(amount) > 50000 ORDER BY total_spend DESC;
Answer 10
SELECT category, SUM(amount) AS revenue FROM sales GROUP BY category HAVING SUM(amount) > 100000 ORDER BY revenue DESC;
โค1
๐ฅ Mini Challenge
You have orders table with columns:
Find each city's: Completed order count, Unique customers, Total revenue, Average order value. Only include cities where completed revenue is greater than โน10,000. Sort by revenue from highest to lowest.
Solution:
Double Tap โค๏ธ For Part-7
You have orders table with columns:
order_id, customer_id, city, amount, statusFind each city's: Completed order count, Unique customers, Total revenue, Average order value. Only include cities where completed revenue is greater than โน10,000. Sort by revenue from highest to lowest.
Solution:
SELECT
city,
COUNT(*) AS completed_orders,
COUNT(DISTINCT customer_id) AS unique_customers,
SUM(amount) AS revenue,
AVG(amount) AS average_order_value
FROM orders
WHERE status = 'Completed'
GROUP BY city
HAVING SUM(amount) > 10000
ORDER BY revenue DESC;
Double Tap โค๏ธ For Part-7
โค4
๐ ๐๐ฟ๐ฒ๐ฎ๐บ๐ถ๐ป๐ด ๐ผ๐ณ ๐ช๐ผ๐ฟ๐ธ๐ถ๐ป๐ด ๐ฎ๐ ๐ง๐ผ๐ฝ ๐ง๐ฒ๐ฐ๐ต ๐๐ผ๐บ๐ฝ๐ฎ๐ป๐ถ๐ฒ๐? ๐ป๐ฅ
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!
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!
โค5
๐ฅ ๐ ๐ฎ๐๐๐ฒ๐ฟ ๐ฆ๐ค๐ ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ โ ๐๐ฟ๐ผ๐บ ๐๐ฒ๐ด๐ถ๐ป๐ป๐ฒ๐ฟ ๐๐ผ ๐๐ฑ๐๐ฎ๐ป๐ฐ๐ฒ๐ฑ! ๐ป๐
These free learning resources cover everything from database fundamentals to advanced SQL queries, with opportunities to practice real-world problems.
๐ฏ Top FREE SQL Resources:
1๏ธโฃ Introduction to Databases & SQL โ Udemy
2๏ธโฃ Advanced Database & SQL โ Udemy
3๏ธโฃ Learn SQL โ Codecademy
4๏ธโฃ SQL Tutorial โ SQLZoo
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/4gNYHk7
๐ Start from the basics and work your way toward advanced SQL skills!
These free learning resources cover everything from database fundamentals to advanced SQL queries, with opportunities to practice real-world problems.
๐ฏ Top FREE SQL Resources:
1๏ธโฃ Introduction to Databases & SQL โ Udemy
2๏ธโฃ Advanced Database & SQL โ Udemy
3๏ธโฃ Learn SQL โ Codecademy
4๏ธโฃ SQL Tutorial โ SQLZoo
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/4gNYHk7
๐ Start from the basics and work your way toward advanced SQL skills!
๐ SQL Roadmap 2026 โ Part 7
CASE Statements โ Adding Business Logic to SQL ๐ง
In the previous parts, you learned how to:
โข Retrieve data with SELECT
โข Filter data with WHERE
โข Sort results with ORDER BY
โข Summarize data with aggregate functions
โข Group data with GROUP BY
Now it's time to learn how to make SQL think in business categories.
For example:
โข Is this customer High Value, Medium Value, or Low Value?
โข Is this employee's salary High, Medium, or Low?
โข Is this order Small, Medium, or Large?
That's what the CASE expression helps you do.
1๏ธโฃ What is CASE?
CASE allows you to create conditional logic inside SQL.
It's similar to:
โข IF condition
โข THEN result
โข ELSE result
Basic Syntax
2๏ธโฃ Simple CASE Example
Suppose we have employee salaries.
We want to classify employees based on salary.
Result:
3๏ธโฃ How CASE Works
SQL checks conditions from top to bottom.
For:
SQL effectively asks:
โข Is salary >= 1,000,000? YES โ High
โข NO โ Is salary >= 600,000? YES โ Medium
โข NO โ Low
Once a matching WHEN condition is found, SQL returns that result.
4๏ธโฃ Order of WHEN Conditions Matters
Consider:
This is problematic.
Why?
Someone earning โน12 lakh satisfies:
โข salary >= 600000 first.
So SQL labels them:
โข Medium instead of High
Better:
Rule:
โข Put more specific or higher-priority conditions before broader conditions.
5๏ธโฃ CASE With Text Conditions
You can also classify based on text.
Example:
6๏ธโฃ CASE With Multiple Conditions
You can use AND and OR inside WHEN.
Example:
7๏ธโฃ CASE With IN
You can combine CASE with IN.
This is useful for creating business regions.
8๏ธโฃ CASE With BETWEEN
Example:
CASE Statements โ Adding Business Logic to SQL ๐ง
In the previous parts, you learned how to:
โข Retrieve data with SELECT
โข Filter data with WHERE
โข Sort results with ORDER BY
โข Summarize data with aggregate functions
โข Group data with GROUP BY
Now it's time to learn how to make SQL think in business categories.
For example:
โข Is this customer High Value, Medium Value, or Low Value?
โข Is this employee's salary High, Medium, or Low?
โข Is this order Small, Medium, or Large?
That's what the CASE expression helps you do.
1๏ธโฃ What is CASE?
CASE allows you to create conditional logic inside SQL.
It's similar to:
โข IF condition
โข THEN result
โข ELSE result
Basic Syntax
SELECT
column_name,
CASE
WHEN condition THEN result
WHEN condition THEN result
ELSE result
END AS new_column
FROM table_name;
2๏ธโฃ Simple CASE Example
Suppose we have employee salaries.
We want to classify employees based on salary.
SELECT
employee_name,
salary,
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
Result:
employee_name | salary | salary_category
Rahul | 1200000 | High
Priya | 850000 | Medium
Amit | 500000 | Low
3๏ธโฃ How CASE Works
SQL checks conditions from top to bottom.
For:
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END
SQL effectively asks:
โข Is salary >= 1,000,000? YES โ High
โข NO โ Is salary >= 600,000? YES โ Medium
โข NO โ Low
Once a matching WHEN condition is found, SQL returns that result.
4๏ธโฃ Order of WHEN Conditions Matters
Consider:
CASE
WHEN salary >= 600000 THEN 'Medium'
WHEN salary >= 1000000 THEN 'High'
ELSE 'Low'
END
This is problematic.
Why?
Someone earning โน12 lakh satisfies:
โข salary >= 600000 first.
So SQL labels them:
โข Medium instead of High
Better:
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END
Rule:
โข Put more specific or higher-priority conditions before broader conditions.
5๏ธโฃ CASE With Text Conditions
You can also classify based on text.
Example:
SELECT
employee_name,
department,
CASE
WHEN department = 'IT' THEN 'Technology'
WHEN department = 'Finance' THEN 'Corporate'
WHEN department = 'HR' THEN 'Corporate'
ELSE 'Other'
END AS department_group
FROM employees;
6๏ธโฃ CASE With Multiple Conditions
You can use AND and OR inside WHEN.
Example:
SELECT
customer_name,
city,
customer_segment,
CASE
WHEN customer_segment = 'Premium'
AND city = 'Mumbai'
THEN 'Premium Mumbai'
WHEN customer_segment = 'Premium'
THEN 'Other Premium'
ELSE 'Standard'
END AS customer_group
FROM customers;
7๏ธโฃ CASE With IN
You can combine CASE with IN.
SELECT
customer_name,
city,
CASE
WHEN city IN ('Mumbai', 'Pune', 'Nashik')
THEN 'Maharashtra'
WHEN city IN ('Delhi', 'Noida', 'Gurgaon')
THEN 'NCR'
ELSE 'Other'
END AS region
FROM customers;
This is useful for creating business regions.
8๏ธโฃ CASE With BETWEEN
Example:
โค2
SELECT
employee_name,
salary,
CASE
WHEN salary BETWEEN 0 AND 500000
THEN 'Entry Level'
WHEN salary BETWEEN 500001 AND 1000000
THEN 'Mid Level'
ELSE 'Senior Level'
END AS salary_band
FROM employees;
However, for numeric ranges, inequality conditions are often easier to maintain:
CASE
WHEN salary < 500000 THEN 'Entry Level'
WHEN salary < 1000000 THEN 'Mid Level'
ELSE 'Senior Level'
END
Because the conditions are evaluated from top to bottom.
9๏ธโฃ CASE for Customer Segmentation
Customer segmentation is a common analytics use case.
Suppose:
โข total_spend represents total customer spending.
SELECT
customer_id,
customer_name,
total_spend,
CASE
WHEN total_spend >= 100000 THEN 'VIP'
WHEN total_spend >= 50000 THEN 'High Value'
WHEN total_spend >= 10000 THEN 'Medium Value'
ELSE 'Low Value'
END AS customer_segment
FROM customers;
This transforms raw spending into a business classification.
๐ CASE for Order Size
Suppose you want to classify orders.
SELECT
order_id,
amount,
CASE
WHEN amount >= 10000 THEN 'Large'
WHEN amount >= 5000 THEN 'Medium'
ELSE 'Small'
END AS order_size
FROM orders;
Result:
order_id | amount | order_size
101 | 12000 | Large
102 | 7000 | Medium
103 | 2500 | Small
1๏ธโฃ1๏ธโฃ CASE for Order Status
You can simplify several statuses into broader business categories.
SELECT
order_id,
order_status,
CASE
WHEN order_status = 'Completed'
THEN 'Successful'
WHEN order_status = 'Cancelled'
THEN 'Unsuccessful'
ELSE 'Pending'
END AS business_status
FROM orders;
1๏ธโฃ2๏ธโฃ CASE With Dates
You can classify orders based on when they were placed.
SELECT
order_id,
order_date,
CASE
WHEN order_date < '2026-01-01'
THEN 'Previous Year'
ELSE 'Current Year'
END AS order_period
FROM orders;
1๏ธโฃ3๏ธโฃ CASE for Profitability
Suppose you have:
โข selling_price
โข cost_price
You can classify products based on profit.
SELECT
product_name,
selling_price,
cost_price,
selling_price - cost_price AS profit,
CASE
WHEN selling_price - cost_price >= 10000
THEN 'Highly Profitable'
WHEN selling_price - cost_price > 0
THEN 'Profitable'
ELSE 'Loss'
END AS profitability
FROM products;
1๏ธโฃ4๏ธโฃ CASE With Aggregate Functions
This is where CASE becomes extremely powerful.
Suppose you want to count completed orders.
SELECT
SUM(
CASE
WHEN order_status = 'Completed'
THEN 1
ELSE 0
END
) AS completed_orders
FROM orders;
Why does this work?
Each row becomes:
โข Completed โ 1
โข Other โ 0
Then SUM() adds them.
1๏ธโฃ5๏ธโฃ Conditional Counting
You can calculate several metrics at once.
SELECT
COUNT(*) AS total_orders,
SUM(
CASE
WHEN order_status = 'Completed'
THEN 1 ELSE 0
END
) AS completed_orders,
SUM(
CASE
WHEN order_status = 'Cancelled'
THEN 1 ELSE 0
END
) AS cancelled_orders
FROM orders;
This is called conditional aggregation.
It is one of the most useful SQL techniques for dashboard development.
โค1
1๏ธโฃ6๏ธโฃ Calculate Success Rate
You can combine CASE, SUM, and COUNT.
The logic:
โข Completed orders รท Total orders ร 100
1๏ธโฃ7๏ธโฃ Conditional Revenue
Suppose you want only revenue from completed orders.
This is especially useful when you need several conditional metrics in one query.
1๏ธโฃ8๏ธโฃ Multiple Conditional Metrics
You can build an entire KPI summary:
This is very close to the kind of SQL used behind BI dashboards.
1๏ธโฃ9๏ธโฃ CASE With GROUP BY
You can create categories and then aggregate them.
Example:
Result:
2๏ธโฃ0๏ธโฃ CASE + GROUP BY + SUM
You can also calculate revenue by order category.
2๏ธโฃ1๏ธโฃ Simple CASE vs Searched CASE
There are two common forms.
Searched CASE
This is what we've mainly used:
It evaluates conditions.
Simple CASE
Useful when comparing one expression against specific values:
Think:
โข Simple CASE โ Compare one value
โข Searched CASE โ Evaluate different conditions
2๏ธโฃ2๏ธโฃ CASE and NULL
You can explicitly handle NULL.
This is much better than comparing NULL using =.
2๏ธโฃ3๏ธโฃ CASE and COALESCE
Sometimes you want to replace NULL with a default value.
You can combine this with CASE:
You can combine CASE, SUM, and COUNT.
SELECT
ROUND(
100.0 *
SUM(
CASE
WHEN order_status = 'Completed'
THEN 1
ELSE 0
END
) / NULLIF(COUNT(*), 0),
2
) AS completion_rate
FROM orders;
The logic:
โข Completed orders รท Total orders ร 100
1๏ธโฃ7๏ธโฃ Conditional Revenue
Suppose you want only revenue from completed orders.
SELECT
SUM(
CASE
WHEN order_status = 'Completed'
THEN amount
ELSE 0
END
) AS completed_revenue
FROM orders;
This is especially useful when you need several conditional metrics in one query.
1๏ธโฃ8๏ธโฃ Multiple Conditional Metrics
You can build an entire KPI summary:
SELECT
COUNT(*) AS total_orders,
SUM(
CASE
WHEN order_status = 'Completed'
THEN 1 ELSE 0
END
) AS completed_orders,
SUM(
CASE
WHEN order_status = 'Cancelled'
THEN 1 ELSE 0
END
) AS cancelled_orders,
SUM(
CASE
WHEN order_status = 'Completed'
THEN amount ELSE 0
END
) AS completed_revenue,
SUM(
CASE
WHEN order_status = 'Cancelled'
THEN amount ELSE 0
END
) AS cancelled_value
FROM orders;
This is very close to the kind of SQL used behind BI dashboards.
1๏ธโฃ9๏ธโฃ CASE With GROUP BY
You can create categories and then aggregate them.
Example:
SELECT
CASE
WHEN amount >= 10000 THEN 'Large'
WHEN amount >= 5000 THEN 'Medium'
ELSE 'Small'
END AS order_size,
COUNT(*) AS order_count
FROM orders
GROUP BY
CASE
WHEN amount >= 10000 THEN 'Large'
WHEN amount >= 5000 THEN 'Medium'
ELSE 'Small'
END;
Result:
order_size | order_count
Large | 120
Medium | 450
Small | 980
2๏ธโฃ0๏ธโฃ CASE + GROUP BY + SUM
You can also calculate revenue by order category.
SELECT
CASE
WHEN amount >= 10000 THEN 'Large'
WHEN amount >= 5000 THEN 'Medium'
ELSE 'Small'
END AS order_size,
SUM(amount) AS revenue
FROM orders
GROUP BY
CASE
WHEN amount >= 10000 THEN 'Large'
WHEN amount >= 5000 THEN 'Medium'
ELSE 'Small'
END;
2๏ธโฃ1๏ธโฃ Simple CASE vs Searched CASE
There are two common forms.
Searched CASE
This is what we've mainly used:
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END
It evaluates conditions.
Simple CASE
Useful when comparing one expression against specific values:
CASE department
WHEN 'IT' THEN 'Technology'
WHEN 'HR' THEN 'People'
WHEN 'Finance' THEN 'Corporate'
ELSE 'Other'
END
Think:
โข Simple CASE โ Compare one value
โข Searched CASE โ Evaluate different conditions
2๏ธโฃ2๏ธโฃ CASE and NULL
You can explicitly handle NULL.
SELECT
employee_name,
CASE
WHEN manager_id IS NULL
THEN 'No Manager Assigned'
ELSE 'Manager Assigned'
END AS manager_status
FROM employees;
This is much better than comparing NULL using =.
2๏ธโฃ3๏ธโฃ CASE and COALESCE
Sometimes you want to replace NULL with a default value.
SELECT
employee_name,
COALESCE(bonus, 0) AS bonus
FROM employees;
You can combine this with CASE:
SELECT
employee_name,
CASE
WHEN COALESCE(bonus, 0) > 10000
THEN 'High Bonus'
ELSE 'Standard Bonus'
END AS bonus_category
FROM employees;
2๏ธโฃ4๏ธโฃ CASE in Data Cleaning
CASE can also standardize inconsistent values.
Suppose a dataset contains:
โข M
โข Male
โข male
โข MALE
You can standardize them:
This is a practical data-cleaning technique.
2๏ธโฃ5๏ธโฃ CASE for Business Rules
Imagine a company wants to classify customers:
โข Spend โฅ โน100,000 โ VIP
โข Spend โฅ โน50,000 โ High Value
โข Spend โฅ โน10,000 โ Regular
โข Otherwise โ Low Value
SQL:
This is an important Data Analyst mindset:
โข Convert business rules into SQL logic.
๐ง Common CASE Mistakes
โข โ Mistake 1: Forgetting END
โข Wrong:
โข
Correct:
โข
โ Mistake 2: Incorrect condition order
โข Wrong:
โข The second condition won't be reached for salaries above โน1 million because they already satisfy the first condition.
โข
Better:
โข
โ Mistake 3: Forgetting ELSE
โข You can omit ELSE, but if no WHEN condition matches, SQL generally returns NULL.
โข
Better when appropriate:
โข
โ Mistake 4: Confusing CASE with filtering
โข CASE creates or transforms a value.
โข WHERE filters rows.
โข For example:
๐ผ SQL Interview Questions
โข
Q1. What is CASE in SQL? CASE is an expression used to implement conditional logic and return different values based on specified conditions
.
โข
Q2. Can CASE be used with aggregate functions? Yes.
โข Q3. What happens if no WHEN condition matches? If there is an ELSE, its value is returned. Otherwise, the result is generally NULL.
โข Q4. Does CASE stop after the first matching condition? For a searched CASE, SQL returns the result associated with the first matching WHEN condition.
โข Q5. Can CASE be used with GROUP BY? Yes. You can group by a CASE expression or, depending on the SQL dialect, an alias representing that expression.
โข Q6. What is conditional aggregation? Using expressions such as CASE inside aggregate functions to calculate metrics for selected conditions.
๐ฏ Practice Questions
Try solving these yourself first.
โข Q1. Classify employees as: High โ salary >= 1,000,000, Medium โ salary >= 600,000, Low โ everything else
โข Q2. Classify orders as: Large โ amount >= 10,000, Medium โ amount >= 5,000, Small โ everything else
โข Q3. Count completed and cancelled orders using conditional aggregation.
โข Q4. Calculate successful transaction value.
โข Q5. Classify customers as VIP if spending is greater than โน100,000.
โข Q6. Create a column that says Has Manager or No Manager based on manager_id.
โข Q7. Create salary bands and count employees in each band.
โข Q8. Calculate completed revenue and cancelled revenue in the same query.
โ Answers
Answer 1
CASE can also standardize inconsistent values.
Suppose a dataset contains:
โข M
โข Male
โข male
โข MALE
You can standardize them:
SELECT
employee_name,
CASE
WHEN LOWER(gender) = 'm'
OR LOWER(gender) = 'male'
THEN 'Male'
WHEN LOWER(gender) = 'f'
OR LOWER(gender) = 'female'
THEN 'Female'
ELSE 'Unknown'
END AS standardized_gender
FROM employees;
This is a practical data-cleaning technique.
2๏ธโฃ5๏ธโฃ CASE for Business Rules
Imagine a company wants to classify customers:
โข Spend โฅ โน100,000 โ VIP
โข Spend โฅ โน50,000 โ High Value
โข Spend โฅ โน10,000 โ Regular
โข Otherwise โ Low Value
SQL:
SELECT
customer_name,
total_spend,
CASE
WHEN total_spend >= 100000 THEN 'VIP'
WHEN total_spend >= 50000 THEN 'High Value'
WHEN total_spend >= 10000 THEN 'Regular'
ELSE 'Low Value'
END AS customer_segment
FROM customers;
This is an important Data Analyst mindset:
โข Convert business rules into SQL logic.
๐ง Common CASE Mistakes
โข โ Mistake 1: Forgetting END
โข Wrong:
CASE WHEN salary > 500000 THEN 'High'โข
Correct:
CASE WHEN salary > 500000 THEN 'High' ELSE 'Low' ENDโข
โ Mistake 2: Incorrect condition order
โข Wrong:
CASE WHEN salary > 500000 THEN 'Medium' WHEN salary > 1000000 THEN 'High' ENDโข The second condition won't be reached for salaries above โน1 million because they already satisfy the first condition.
โข
Better:
CASE WHEN salary > 1000000 THEN 'High' WHEN salary > 500000 THEN 'Medium' ELSE 'Low' ENDโข
โ Mistake 3: Forgetting ELSE
โข You can omit ELSE, but if no WHEN condition matches, SQL generally returns NULL.
โข
Better when appropriate:
CASE WHEN status = 'Completed' THEN 'Success' WHEN status = 'Cancelled' THEN 'Failure' ELSE 'Other' ENDโข
โ Mistake 4: Confusing CASE with filtering
โข CASE creates or transforms a value.
โข WHERE filters rows.
โข For example:
CASE WHEN salary > 800000 THEN 'High' ELSE 'Low' END doesn't remove rows. It categorizes them.๐ผ SQL Interview Questions
โข
Q1. What is CASE in SQL? CASE is an expression used to implement conditional logic and return different values based on specified conditions
.
โข
Q2. Can CASE be used with aggregate functions? Yes.
SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END)โข Q3. What happens if no WHEN condition matches? If there is an ELSE, its value is returned. Otherwise, the result is generally NULL.
โข Q4. Does CASE stop after the first matching condition? For a searched CASE, SQL returns the result associated with the first matching WHEN condition.
โข Q5. Can CASE be used with GROUP BY? Yes. You can group by a CASE expression or, depending on the SQL dialect, an alias representing that expression.
โข Q6. What is conditional aggregation? Using expressions such as CASE inside aggregate functions to calculate metrics for selected conditions.
๐ฏ Practice Questions
Try solving these yourself first.
โข Q1. Classify employees as: High โ salary >= 1,000,000, Medium โ salary >= 600,000, Low โ everything else
โข Q2. Classify orders as: Large โ amount >= 10,000, Medium โ amount >= 5,000, Small โ everything else
โข Q3. Count completed and cancelled orders using conditional aggregation.
โข Q4. Calculate successful transaction value.
โข Q5. Classify customers as VIP if spending is greater than โน100,000.
โข Q6. Create a column that says Has Manager or No Manager based on manager_id.
โข Q7. Create salary bands and count employees in each band.
โข Q8. Calculate completed revenue and cancelled revenue in the same query.
โ Answers
Answer 1
โค1
SELECT employee_name, salary, CASE WHEN salary >= 1000000 THEN 'High' WHEN salary >= 600000 THEN 'Medium' ELSE 'Low' END AS salary_category FROM employees;
Answer 2
SELECT order_id, amount, CASE WHEN amount >= 10000 THEN 'Large' WHEN amount >= 5000 THEN 'Medium' ELSE 'Small' END AS order_size FROM orders;
Answer 3
SELECT SUM(CASE WHEN order_status = 'Completed' THEN 1 ELSE 0 END) AS completed_orders, SUM(CASE WHEN order_status = 'Cancelled' THEN 1 ELSE 0 END) AS cancelled_orders FROM orders;
Answer 4
SELECT SUM(CASE WHEN transaction_status = 'Success' THEN amount ELSE 0 END) AS successful_transaction_value FROM transactions;
Answer 5
SELECT customer_name, total_spend, CASE WHEN total_spend >= 100000 THEN 'VIP' ELSE 'Regular' END AS customer_category FROM customers;
Answer 6
SELECT employee_name, CASE WHEN manager_id IS NULL THEN 'No Manager' ELSE 'Has Manager' END AS manager_status FROM employees;
Answer 7
SELECT CASE WHEN salary >= 1000000 THEN 'High' WHEN salary >= 600000 THEN 'Medium' ELSE 'Low' END AS salary_band, COUNT(*) AS employee_count FROM employees GROUP BY CASE WHEN salary >= 1000000 THEN 'High' WHEN salary >= 600000 THEN 'Medium' ELSE 'Low' END;
Answer 8
SELECT SUM(CASE WHEN order_status = 'Completed' THEN amount ELSE 0 END) AS completed_revenue, SUM(CASE WHEN order_status = 'Cancelled' THEN amount ELSE 0 END) AS cancelled_revenue FROM orders;
๐ฅ Mini Challenge
Imagine an e-commerce company wants this dashboard:
โข Total Orders
โข Completed Orders
โข Cancelled Orders
โข Completed Revenue
โข Cancelled Revenue
โข Completion Rate
Write one SQL query to calculate all six metrics.
Think about:
โข COUNT(*) โ Total orders
โข SUM(CASE...) โ Conditional counts/revenue
โข COUNT + SUM โ Completion rate
Solution
SELECT
COUNT(*) AS total_orders,
SUM(CASE WHEN order_status = 'Completed' THEN 1 ELSE 0 END) AS completed_orders,
SUM(CASE WHEN order_status = 'Cancelled' THEN 1 ELSE 0 END) AS cancelled_orders,
SUM(CASE WHEN order_status = 'Completed' THEN amount ELSE 0 END) AS completed_revenue,
SUM(CASE WHEN order_status = 'Cancelled' THEN amount ELSE 0 END) AS cancelled_revenue,
ROUND(100.0 * SUM(CASE WHEN order_status = 'Completed' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS completion_rate
FROM orders;
Once you become comfortable with CASE, you'll be able to build much more meaningful analytical queries instead of simply retrieving raw data.
Double Tap โค๏ธ For Part-8
โค7
๐ฃ๐ฎ๐ ๐๐ณ๐๐ฒ๐ฟ ๐ฃ๐น๐ฎ๐ฐ๐ฒ๐บ๐ฒ๐ป๐ โ ๐๐ฒ๐ ๐ฃ๐น๐ฎ๐ฐ๐ฒ๐ฑ ๐๐ป ๐ง๐ผ๐ฝ ๐ง๐ฒ๐ฐ๐ต ๐๐ผ๐บ๐ฝ๐ฎ๐ป๐ถ๐ฒ๐๐
Learn JAVA/MERN Full Stack Development With GenAI.
๐ Placement Highlights:-
๐ฐ โน41 LPA highest salary
๐ โน7.4 LPA average salary
๐ 2,000+ students placed
๐ข 500+ partner companies
๐ ๐๐ฝ๐ฝ๐น๐ ๐ก๐ผ๐ ๐:-
https://pdlink.in/3SuUeuD
โก Take the first step toward your dream tech career today!
Learn JAVA/MERN Full Stack Development With GenAI.
๐ Placement Highlights:-
๐ฐ โน41 LPA highest salary
๐ โน7.4 LPA average salary
๐ 2,000+ students placed
๐ข 500+ partner companies
๐ ๐๐ฝ๐ฝ๐น๐ ๐ก๐ผ๐ ๐:-
https://pdlink.in/3SuUeuD
โก Take the first step toward your dream tech career today!
โค1
๐ ๐๐ฅ๐๐ ๐๐ฒ๐ฟ๐๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป ๐๐ผ๐๐ฟ๐๐ฒ ๐ข๐ป ๐๐๐๐ฟ๐ฒ ๐ ๐ฎ๐ฐ๐ต๐ถ๐ป๐ฒ ๐๐ฒ๐ฎ๐ฟ๐ป๐ถ๐ป๐ด โ๏ธ
โจ Build practical skills in Cloud AI โข Machine Learning โข Data Preparation โข ML Workflows โข Azure Data Services.
๐ฅ Learn โ Practice โ Build Projects โ Strengthen Your Tech Career
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/3UyljxK
๐ Perfect for Students โข Freshers โข Data Science Aspirants โข AI/ML Learners โข Working Professionals
โจ Build practical skills in Cloud AI โข Machine Learning โข Data Preparation โข ML Workflows โข Azure Data Services.
๐ฅ Learn โ Practice โ Build Projects โ Strengthen Your Tech Career
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/3UyljxK
๐ Perfect for Students โข Freshers โข Data Science Aspirants โข AI/ML Learners โข Working Professionals
โค1
๐ SQL Roadmap 2026 โ Part 8
NULL Handling, COALESCE & NULLIF โ Managing Missing Data in SQL
In real-world databases, missing data is extremely common.
Customers may not have a phone number.
Orders may not have a discount.
Employees may not have a resignation date.
Transactions may have missing reference values.
SQL uses NULL to represent an unknown or missing value.
Understanding NULL properly is essential for accurate SQL queries and data analysis.
๐ง 1. What is NULL?
"NULL" means:
ยซThe value is missing, unknown, or not available.ยป
Example:
Bob's phone number is not stored.
It does not necessarily mean:
โข "0"
โข empty string "''"
โข "Unknown"
โข "N/A"
These are different values.
โ ๏ธ 2. NULL Is Not Equal to 0
This finds customers whose credit limit is actually zero.
It will not find customers whose credit limit is missing.
To find missing values:
โ ๏ธ 3. Never Use = NULL
This is incorrect:
It won't correctly identify NULL values.
Use:
And for non-NULL values:
Remember:
๐ข 4. NULL in Calculations
Suppose:
Now:
For order 2, the result may be:
because:
SQL generally cannot determine the result when one operand is unknown.
๐ ๏ธ 5. COALESCE()
It returns the first non-NULL value.
Syntax:
Example:
If "phone" is NULL:
๐ฏ 6. COALESCE with Multiple Values
You can provide several fallback values.
SQL checks in order:
The first non-NULL value is returned.
๐ฐ 7. COALESCE for Financial Calculations
Suppose discounts can be NULL.
Instead of:
Use:
Now a missing discount is treated as zero.
Example:
This is extremely common in analytics.
๐ 8. COALESCE with Aggregations
Suppose there are no matching transactions for a customer.
You may want to display:
instead of NULL.
NULL Handling, COALESCE & NULLIF โ Managing Missing Data in SQL
In real-world databases, missing data is extremely common.
Customers may not have a phone number.
Orders may not have a discount.
Employees may not have a resignation date.
Transactions may have missing reference values.
SQL uses NULL to represent an unknown or missing value.
Understanding NULL properly is essential for accurate SQL queries and data analysis.
๐ง 1. What is NULL?
"NULL" means:
ยซThe value is missing, unknown, or not available.ยป
Example:
customer_id | customer_name | phone
101 | Alice | 9876543210
102 | Bob | NULL
103 | Charlie | 9123456780
Bob's phone number is not stored.
It does not necessarily mean:
โข "0"
โข empty string "''"
โข "Unknown"
โข "N/A"
These are different values.
โ ๏ธ 2. NULL Is Not Equal to 0
SELECT *
FROM customers
WHERE credit_limit = 0;
This finds customers whose credit limit is actually zero.
It will not find customers whose credit limit is missing.
To find missing values:
SELECT *
FROM customers
WHERE credit_limit IS NULL;
โ ๏ธ 3. Never Use = NULL
This is incorrect:
SELECT *
FROM customers
WHERE phone = NULL;
It won't correctly identify NULL values.
Use:
SELECT *
FROM customers
WHERE phone IS NULL;
And for non-NULL values:
SELECT *
FROM customers
WHERE phone IS NOT NULL;
Remember:
= NULL โ
<> NULL โ
IS NULL โ
IS NOT NULL โ
๐ข 4. NULL in Calculations
Suppose:
order_id | price | discount
1 | 1000 | 100
2 | 800 | NULL
Now:
SELECT
price,
discount,
price - discount AS final_price
FROM orders;
For order 2, the result may be:
NULL
because:
800 - NULL = NULL
SQL generally cannot determine the result when one operand is unknown.
๐ ๏ธ 5. COALESCE()
COALESCE() is one of the most important functions for handling NULL values.It returns the first non-NULL value.
Syntax:
COALESCE(value1, value2, value3, ...)
Example:
SELECT
customer_name,
COALESCE(phone, 'Not Available') AS phone
FROM customers;
If "phone" is NULL:
NULL โ Not Available
๐ฏ 6. COALESCE with Multiple Values
You can provide several fallback values.
SELECT
customer_name,
COALESCE(phone, email, 'No Contact Information') AS contact
FROM customers;
SQL checks in order:
phone
โ
โ
No Contact Information
The first non-NULL value is returned.
๐ฐ 7. COALESCE for Financial Calculations
Suppose discounts can be NULL.
Instead of:
SELECT
price - discount AS final_price
FROM orders;
Use:
SELECT
price - COALESCE(discount, 0) AS final_price
FROM orders;
Now a missing discount is treated as zero.
Example:
Price | Discount | Final Price
1000 | 100 | 900
800 | NULL | 800
This is extremely common in analytics.
๐ 8. COALESCE with Aggregations
Suppose there are no matching transactions for a customer.
You may want to display:
0
instead of NULL.
โค2
SELECT
customer_id,
COALESCE(SUM(amount), 0) AS total_spending
FROM transactions
GROUP BY customer_id;
This makes reports easier to interpret.
๐งฎ 9. NULL and COUNT()
These two queries behave differently:
SELECT COUNT(*)
FROM customers;
Counts all rows.
While:
SELECT COUNT(phone)
FROM customers;
Counts only rows where "phone" is not NULL.
Example:
customer | phone
A | 12345
B | NULL
C | 67890
COUNT(*) โ 3
COUNT(phone) โ 2
This difference is frequently tested in interviews.
๐ 10. NULL and SUM(), AVG(), MIN(), MAX()
Most aggregate functions ignore NULL values.
Example:
Salary
50000
60000
NULL
70000
Then:
SELECT AVG(salary)
FROM employees;
The NULL salary is generally ignored.
So the average is calculated using:
50000, 60000, 70000
not four values.
Important:
โข
COUNT(*) counts rows.โข
COUNT(column) ignores NULL.โข
SUM(), AVG(), MIN(), and MAX() generally ignore NULL values.๐ 11. NULL with CASE
NULL can be handled using CASE.
SELECT
customer_name,
CASE
WHEN phone IS NULL THEN 'Missing'
ELSE 'Available'
END AS phone_status
FROM customers;
Result:
customer | phone_status
Alice | Available
Bob | Missing
Charlie | Available
๐งน 12. Handling NULL in Data Cleaning
Suppose customer cities contain missing values.
SELECT
customer_name,
COALESCE(city, 'Unknown') AS city
FROM customers;
This can make reports more readable.
But be careful:
Replacing NULL does not mean the original data wasn't missing.
For analysis, it may still be important to track missingness.
๐งจ 13. NULLIF()
NULLIF() returns NULL when two expressions are equal.Syntax:
NULLIF(value1, value2)
Example:
SELECT NULLIF(10, 10);
Result:
NULL
But:
SELECT NULLIF(10, 5);
Result:
10
๐จ 14. NULLIF() for Division by Zero
This is one of the most useful real-world applications.
Suppose:
SELECT
revenue / orders AS revenue_per_order
FROM sales;
If "orders = 0", some database systems will raise a division-by-zero error.
Use:
SELECT
revenue / NULLIF(orders, 0) AS revenue_per_order
FROM sales;
If:
orders = 0
then:
NULLIF(orders, 0)
returns:
NULL
So the calculation becomes:
revenue / NULL
and returns NULL instead of attempting division by zero.
You can then provide a fallback:
SELECT
COALESCE(
revenue / NULLIF(orders, 0),
0
) AS revenue_per_order
FROM sales;
This combines:
โข NULLIF โ prevent invalid division
โข COALESCE โ provide fallback value
๐ 15. NULL in JOINs
NULL becomes especially important with joins.
Suppose:
customers
contains all customers, while:
orders
contains only customers who placed orders.
Using:
SELECT
c.customer_id,
c.customer_name,
o.order_id
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id;
Customers without orders may have:
order_id = NULL
You can identify them with:
WHERE o.order_id IS NULL;
This is a common technique for finding:
ยซCustomers who have never placed an order.ยป
๐ฆ 16. NULL in GROUP BY
NULL values can also appear as a group.
Example:
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
If some employees have no department, the result can contain a group where:
department = NULL
You can make it more readable:
SELECT
COALESCE(department, 'Unassigned') AS department,
COUNT(*) AS employee_count
FROM employees
GROUP BY COALESCE(department, 'Unassigned');
โ๏ธ 17. NULL and ORDER BY
NULL sorting behavior can differ between database systems.
For example:
SELECT *
FROM employees
ORDER BY salary DESC;
Depending on the database, NULL values may appear at the beginning or end.
Some systems support:
ORDER BY salary DESC NULLS LAST;
Always check the SQL dialect you're using when NULL ordering matters.
๐ง 18. NULL vs Empty String
These are not necessarily the same:
NULL
''
"NULL" means:
ยซNo known value.ยป
An empty string means:
ยซA string exists but contains no characters.ยป
For example:
phone = ''
is different from:
phone IS NULL
This distinction matters during data cleaning.
๐ข 19. Real-World Analytics Example
Imagine an e-commerce dataset:
order_id | revenue | discount | shipping_cost
1 | 2000 | 200 | 100
2 | 1500 | NULL | 80
3 | 3000 | 300 | NULL
Calculate profit safely:
SELECT
order_id,
revenue,
COALESCE(discount, 0) AS discount,
COALESCE(shipping_cost, 0) AS shipping_cost,
revenue
- COALESCE(discount, 0)
- COALESCE(shipping_cost, 0) AS net_revenue
FROM orders;
This prevents missing values from turning the entire calculation into NULL.
๐ฏ 20. Business KPI Example โ Conversion Rate
Suppose:
conversions = 50
visitors = 0
A safe calculation is:
SELECT
COALESCE(
conversions * 100.0 / NULLIF(visitors, 0),
0
) AS conversion_rate
FROM marketing;
The logic is:
NULLIF(visitors, 0)
โ
Prevents division by zero
โ
Returns NULL if visitors = 0
โ
COALESCE(..., 0)
โ
Displays 0 instead of NULL
This pattern is highly useful for KPI dashboards.
โ ๏ธ Common NULL Mistakes
Mistake 1:
WHERE salary = NULL;
โ Incorrect
Use:
WHERE salary IS NULL;
Mistake 2:
Assuming NULL means zero.
NULL โ 0
Mistake 3:
Ignoring NULL during calculations.
price - discount
may produce NULL when discount is NULL.
Consider:
price - COALESCE(discount, 0)
when treating missing discount as zero is appropriate.
Mistake 4:
Using COALESCE blindly.
Replacing every NULL with "0" can distort analysis.
For example:
Missing salary โ 0
does not mean the employee earns zero.
The correct replacement depends on the business meaning of the missing value.
๐ค SQL Interview Questions
Q1. What is NULL?
NULL represents a missing, unknown, or unavailable value.
Q2. How do you check for NULL?
Q3. How do you check for non-NULL values?
Q4. Why doesn't "= NULL" work?
Because NULL represents an unknown value and comparisons with NULL do not evaluate to TRUE in the normal way. SQL provides
Q5. What does COALESCE() do?
It returns the first non-NULL expression.
Q6. What does NULLIF() do?
It returns NULL when two expressions are equal.
Q7. Difference between COUNT(*) and COUNT(column)?
Q8. How can you prevent division by zero?
Q9. Does AVG() normally include NULL values?
No. NULL values are generally ignored when calculating the average.
Q10. What is the difference between NULL and 0?
"0" is an actual numeric value.
"NULL" represents an unknown or missing value.
๐ Practice Questions
Practice 1
Find customers whose email is missing.
Practice 2
Display "Unknown" when a customer's city is NULL.
Practice 3
Calculate final price assuming a missing discount means zero.
Practice 4
Calculate revenue per order without dividing by zero.
Practice 5
Count how many customers have a phone number.
๐งช Mini SQL Challenge
You have a table:
Write a query that returns:
โข
โข revenue
โข discount, treating NULL as 0
โข revenue after discount
โข revenue per order
โข safely handle "orders = 0"
Solution:
Double Tap โค๏ธ For Part-9
Mistake 4:
Using COALESCE blindly.
Replacing every NULL with "0" can distort analysis.
For example:
Missing salary โ 0
does not mean the employee earns zero.
The correct replacement depends on the business meaning of the missing value.
๐ค SQL Interview Questions
Q1. What is NULL?
NULL represents a missing, unknown, or unavailable value.
Q2. How do you check for NULL?
WHERE column_name IS NULL;Q3. How do you check for non-NULL values?
WHERE column_name IS NOT NULL;Q4. Why doesn't "= NULL" work?
Because NULL represents an unknown value and comparisons with NULL do not evaluate to TRUE in the normal way. SQL provides
IS NULL and IS NOT NULL specifically for this purpose.Q5. What does COALESCE() do?
It returns the first non-NULL expression.
COALESCE(phone, email, 'No Contact')Q6. What does NULLIF() do?
It returns NULL when two expressions are equal.
NULLIF(value1, value2)Q7. Difference between COUNT(*) and COUNT(column)?
COUNT(*) counts rows.COUNT(column) counts non-NULL values in that column.Q8. How can you prevent division by zero?
revenue / NULLIF(orders, 0)Q9. Does AVG() normally include NULL values?
No. NULL values are generally ignored when calculating the average.
Q10. What is the difference between NULL and 0?
"0" is an actual numeric value.
"NULL" represents an unknown or missing value.
๐ Practice Questions
Practice 1
Find customers whose email is missing.
SELECT *
FROM customers
WHERE email IS NULL;
Practice 2
Display "Unknown" when a customer's city is NULL.
SELECT
customer_name,
COALESCE(city, 'Unknown') AS city
FROM customers;
Practice 3
Calculate final price assuming a missing discount means zero.
SELECT
price - COALESCE(discount, 0) AS final_price
FROM orders;
Practice 4
Calculate revenue per order without dividing by zero.
SELECT
revenue / NULLIF(order_count, 0) AS revenue_per_order
FROM sales;
Practice 5
Count how many customers have a phone number.
SELECT COUNT(phone) AS customers_with_phone
FROM customers;
๐งช Mini SQL Challenge
You have a table:
sales
sale_id
revenue
discount
orders
Write a query that returns:
โข
sale_idโข revenue
โข discount, treating NULL as 0
โข revenue after discount
โข revenue per order
โข safely handle "orders = 0"
Solution:
SELECT
sale_id,
revenue,
COALESCE(discount, 0) AS discount,
revenue - COALESCE(discount, 0)
AS revenue_after_discount,
COALESCE(
revenue / NULLIF(orders, 0),
0
) AS revenue_per_order
FROM sales;
Double Tap โค๏ธ For Part-9
โค7
๐ ๐ ๐ฎ๐๐๐ฒ๐ฟ ๐๐ป-๐๐ฒ๐บ๐ฎ๐ป๐ฑ ๐ง๐ฒ๐ฐ๐ต ๐ฆ๐ธ๐ถ๐น๐น๐ ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐ถ๐ป ๐ฎ๐ฌ๐ฎ๐ฒ ๐ฅ
Want to upgrade your tech skills without spending money?
Here are some excellent FREE YouTube resources to learn high-demand technologies through tutorials and hands-on practice.
๐ฅ Learn โ Practice โ Build Projects โ Upgrade Your Resume
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/4x3B9hb
๐ฏ Perfect for Students โข Freshers โข Job Seekers โข Working Professionals
Want to upgrade your tech skills without spending money?
Here are some excellent FREE YouTube resources to learn high-demand technologies through tutorials and hands-on practice.
๐ฅ Learn โ Practice โ Build Projects โ Upgrade Your Resume
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/4x3B9hb
๐ฏ Perfect for Students โข Freshers โข Job Seekers โข Working Professionals
Data analytics is not about the the tools you master but about the people you influence.
I see many debates around the best tools such as:
- Excel vs SQL
- Python vs R
- Tableau vs PowerBI
- ChatGPT vs no ChatGPT
The truth is that business doesn't care about how you come up with your insights.
All business cares about is:
- the story line
- how well they can understand it
- your communication style
- the overall feeling after a presentation
These make the difference in being perceived as a great data analyst...
not the tools you may or may not master ๐
I see many debates around the best tools such as:
- Excel vs SQL
- Python vs R
- Tableau vs PowerBI
- ChatGPT vs no ChatGPT
The truth is that business doesn't care about how you come up with your insights.
All business cares about is:
- the story line
- how well they can understand it
- your communication style
- the overall feeling after a presentation
These make the difference in being perceived as a great data analyst...
not the tools you may or may not master ๐
โค2