π Summary
β
β Aggregate functions (
β
β
Tomorrow, we will learn about SQL Joins (INNER JOIN, LEFT JOIN, etc.) to combine data from multiple tables! π
π‘ Like & Comment if you're ready for Day 7! πβ€οΈ
β
GROUP BY β Groups rows by a column. β Aggregate functions (
SUM, AVG, COUNT, etc.) summarize each group. β
HAVING filters groups after aggregation. β
WHERE filters before grouping. Tomorrow, we will learn about SQL Joins (INNER JOIN, LEFT JOIN, etc.) to combine data from multiple tables! π
π‘ Like & Comment if you're ready for Day 7! πβ€οΈ
Day 7: SQL Hands-On Practice β Strengthening Your Basics π―
Congratulations! π You've completed the first 6 days of SQL learning! Now, before moving forward to more complex topics, it's important to review, practice, and solidify what we've learned so far.
Today, we will:
βοΈ Revise the key SQL concepts covered this week.
βοΈ Practice with real SQL queries.
βοΈ Solve challenges on SQL platforms like HackerRank, LeetCode, and W3Schools.
---
π Quick Revision of Week 1 Topics
Letβs quickly go over what we learned in the past 6 days.
πΉ Day 1: Introduction to SQL & Databases
- SQL (Structured Query Language) is used to store, retrieve, and manage data in databases.
- Popular database systems: MySQL, PostgreSQL, SQL Server.
- SQL operates on tables that store data in rows and columns.
πΉ Day 2: SQL Data Types & Basic Queries
- SQL supports different data types:
-
-
-
-
- Basic queries:
-
-
πΉ Day 3: Filtering Data with `WHERE`
- The
- Comparison operators:
- Logical operators:
Filters students where `Age` is greater than 18.
πΉ Day 4: Sorting & Limiting Data
-
-
-
πΉ Finds the top 3 students with the highest grades.
πΉ Day 5: Aggregate Functions
-
πΉ Counts how many students got Grade A.
πΉ Day 6: Grouping Data with `GROUP BY` & `HAVING`
-
-
πΉ Finds grades where the average fees paid is greater than 1000.
---
π― Hands-On Practice: Solve These SQL Problems
Problem 1: Find the Total Fees Paid by Each Grade
πΉ Expected Output:
| Grade | Total_Fees |
|-------|-----------|
| A | 1900 |
| B | 2300 |
| C | NULL |
Task: Run this query and check if your database returns the correct results.
---
Problem 2: List Students Who Are 18 Years or Older
Expected Output: All students aged 18 or older.
---
Problem 3: Count How Many Students Are in Each Grade
Expected Output:
| Grade | Student_Count |
|-------|--------------|
| A | 2 |
| B | 2 |
| C | 1 |
---
Problem 4: Get the Top 2 Youngest Students
Expected Output: The 2 youngest students.
---
Problem 5: Find the Maximum Fees Paid by Any Student
πΉ Expected Output: The highest fee paid.
---
π Platforms to Practice SQL
If you donβt have SQL installed, you can practice online for free on these platforms:
| Platform | Features |
|--------------|-------------|
| [HackerRank](https://www.hackerrank.com/domains/sql) | Beginner to advanced SQL challenges |
| [LeetCode SQL](https://leetcode.com/problemset/database/) | Real-world SQL interview questions |
| [W3Schools SQL](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all) | Interactive SQL editor |
---
π Your Tasks for Today
β Revise all SQL topics from Day 1 β Day 6.
β Write and run the 5 practice queries above.
β Solve at least 3 SQL challenges on HackerRank, LeetCode, or W3Schools.
β Comment "Done β " if you've completed today's tasks!
Congratulations! π You've completed the first 6 days of SQL learning! Now, before moving forward to more complex topics, it's important to review, practice, and solidify what we've learned so far.
Today, we will:
βοΈ Revise the key SQL concepts covered this week.
βοΈ Practice with real SQL queries.
βοΈ Solve challenges on SQL platforms like HackerRank, LeetCode, and W3Schools.
---
π Quick Revision of Week 1 Topics
Letβs quickly go over what we learned in the past 6 days.
πΉ Day 1: Introduction to SQL & Databases
- SQL (Structured Query Language) is used to store, retrieve, and manage data in databases.
- Popular database systems: MySQL, PostgreSQL, SQL Server.
- SQL operates on tables that store data in rows and columns.
πΉ Day 2: SQL Data Types & Basic Queries
- SQL supports different data types:
-
INT (integer numbers) -
VARCHAR(n) (text) -
DATE (dates) -
DECIMAL(p,s) (for precise numbers like currency). - Basic queries:
SELECT column1, column2 FROM table_name;
-
SELECT retrieves specific columns. -
FROM specifies the table.πΉ Day 3: Filtering Data with `WHERE`
- The
WHERE clause filters rows based on conditions.- Comparison operators:
=, >, <, >=, <=, !=- Logical operators:
AND, OR, NOTSELECT * FROM Students WHERE Age > 18;
Filters students where `Age` is greater than 18.
πΉ Day 4: Sorting & Limiting Data
-
ORDER BY sorts data in ascending (`ASC`) or descending (`DESC`) order.-
LIMIT restricts the number of rows.-
DISTINCT removes duplicates.SELECT Name, Grade FROM Students ORDER BY Grade DESC LIMIT 3;
πΉ Finds the top 3 students with the highest grades.
πΉ Day 5: Aggregate Functions
-
COUNT(), SUM(), AVG(), MIN(), MAX() summarize data.SELECT COUNT(*) FROM Students WHERE Grade = 'A';
πΉ Counts how many students got Grade A.
πΉ Day 6: Grouping Data with `GROUP BY` & `HAVING`
-
GROUP BY groups rows based on a column.-
HAVING filters groups (used instead of WHERE for aggregated data).SELECT Grade, AVG(Fees_Paid) FROM Students GROUP BY Grade HAVING AVG(Fees_Paid) > 1000;
πΉ Finds grades where the average fees paid is greater than 1000.
---
π― Hands-On Practice: Solve These SQL Problems
Problem 1: Find the Total Fees Paid by Each Grade
SELECT Grade, SUM(Fees_Paid) AS Total_Fees
FROM Students
GROUP BY Grade;
πΉ Expected Output:
| Grade | Total_Fees |
|-------|-----------|
| A | 1900 |
| B | 2300 |
| C | NULL |
Task: Run this query and check if your database returns the correct results.
---
Problem 2: List Students Who Are 18 Years or Older
SELECT Name, Age FROM Students WHERE Age >= 18;
Expected Output: All students aged 18 or older.
---
Problem 3: Count How Many Students Are in Each Grade
SELECT Grade, COUNT(*) AS Student_Count
FROM Students
GROUP BY Grade;
Expected Output:
| Grade | Student_Count |
|-------|--------------|
| A | 2 |
| B | 2 |
| C | 1 |
---
Problem 4: Get the Top 2 Youngest Students
SELECT Name, Age FROM Students ORDER BY Age ASC LIMIT 2;
Expected Output: The 2 youngest students.
---
Problem 5: Find the Maximum Fees Paid by Any Student
SELECT MAX(Fees_Paid) AS Max_Fees FROM Students;
πΉ Expected Output: The highest fee paid.
---
π Platforms to Practice SQL
If you donβt have SQL installed, you can practice online for free on these platforms:
| Platform | Features |
|--------------|-------------|
| [HackerRank](https://www.hackerrank.com/domains/sql) | Beginner to advanced SQL challenges |
| [LeetCode SQL](https://leetcode.com/problemset/database/) | Real-world SQL interview questions |
| [W3Schools SQL](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all) | Interactive SQL editor |
---
π Your Tasks for Today
β Revise all SQL topics from Day 1 β Day 6.
β Write and run the 5 practice queries above.
β Solve at least 3 SQL challenges on HackerRank, LeetCode, or W3Schools.
β Comment "Done β " if you've completed today's tasks!
π3
Tomorrow, we move on to SQL Joins (INNER JOIN, LEFT JOIN, etc.) β a crucial topic for combining multiple tables! π
Like β€οΈ and Share if you're excited for Day 8! π
Like β€οΈ and Share if you're excited for Day 8! π
HackerRank
Solve Programming Questions | HackerRank
A special-purpose language designed for managing data held in a relational database.
β€1
Day 8: SQL JOINS β Combining Data from Multiple Tables π
Welcome to Week 2 of your SQL journey! π
So far, we have learned how to retrieve, filter, sort, and aggregate data from a single table. But in real-world databases, data is stored across multiple tables to maintain efficiency and reduce redundancy.
π‘ How do we fetch related data from multiple tables?
π Using SQL JOINS!
Today, we will cover:
βοΈ What are JOINS?
βοΈ Types of JOINS (Focusing on INNER JOIN & LEFT JOIN today).
βοΈ Real-life examples with simple explanations.
βοΈ Hands-on SQL queries.
---
π What are SQL JOINS?
A JOIN is used to combine rows from two or more tables based on a related column.
Imagine you have:
- Students Table (Stores student details).
- Courses Table (Stores course details).
If you want to find which student is enrolled in which course, you need to JOIN these two tables on a common column (e.g.,
---
πΉ Types of SQL JOINS
1οΈβ£ INNER JOIN β Returns only matching records from both tables.
2οΈβ£ LEFT JOIN β Returns all records from the left table and matching records from the right table.
3οΈβ£ RIGHT JOIN β Returns all records from the right table and matching records from the left table.
4οΈβ£ FULL JOIN β Returns all records from both tables (matching and non-matching).
---
πΉ Understanding INNER JOIN (Most Common JOIN)
π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | | |
πΉ David has no course assigned (NULL value in Course_ID).
πΉ To get only students who are enrolled in a course, we use
πΉ Output:
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
π David is not included because he has no matching Course_ID.
---
πΉ Understanding LEFT JOIN
πΉ LEFT JOIN returns ALL records from the left table (Students) and matching records from the right table (Courses).
πΉ If there is no match, NULL is returned.
πΉ Output (Now including David too):
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
π David is included, but Course_Name is NULL because there is no matching Course_ID.
---
π― Hands-On Practice: Solve These SQL Problems
1οΈβ£ Find all students who are enrolled in a course (Use
2οΈβ£ Find all students, even those without courses (Use
3οΈβ£ Find courses that have students enrolled (Use
π Your Tasks for Today
β Revise INNER JOIN & LEFT JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore RIGHT JOIN, FULL JOIN, and SELF JOIN!
π Like β€οΈ and Share if youβre excited for Day 9! π
Welcome to Week 2 of your SQL journey! π
So far, we have learned how to retrieve, filter, sort, and aggregate data from a single table. But in real-world databases, data is stored across multiple tables to maintain efficiency and reduce redundancy.
π‘ How do we fetch related data from multiple tables?
π Using SQL JOINS!
Today, we will cover:
βοΈ What are JOINS?
βοΈ Types of JOINS (Focusing on INNER JOIN & LEFT JOIN today).
βοΈ Real-life examples with simple explanations.
βοΈ Hands-on SQL queries.
---
π What are SQL JOINS?
A JOIN is used to combine rows from two or more tables based on a related column.
Imagine you have:
- Students Table (Stores student details).
- Courses Table (Stores course details).
If you want to find which student is enrolled in which course, you need to JOIN these two tables on a common column (e.g.,
Student_ID). ---
πΉ Types of SQL JOINS
1οΈβ£ INNER JOIN β Returns only matching records from both tables.
2οΈβ£ LEFT JOIN β Returns all records from the left table and matching records from the right table.
3οΈβ£ RIGHT JOIN β Returns all records from the right table and matching records from the left table.
4οΈβ£ FULL JOIN β Returns all records from both tables (matching and non-matching).
---
πΉ Understanding INNER JOIN (Most Common JOIN)
INNER JOIN returns only the matching records from both tables. π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | | |
πΉ David has no course assigned (NULL value in Course_ID).
πΉ To get only students who are enrolled in a course, we use
INNER JOIN.SELECT Students.Name, Courses.Course_Name
FROM Students
INNER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output:
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
π David is not included because he has no matching Course_ID.
---
πΉ Understanding LEFT JOIN
πΉ LEFT JOIN returns ALL records from the left table (Students) and matching records from the right table (Courses).
πΉ If there is no match, NULL is returned.
SELECT Students.Name, Courses.Course_Name
FROM Students
LEFT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output (Now including David too):
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
π David is included, but Course_Name is NULL because there is no matching Course_ID.
---
π― Hands-On Practice: Solve These SQL Problems
1οΈβ£ Find all students who are enrolled in a course (Use
INNER JOIN). SELECT Students.Name, Courses.Course_Name
FROM Students
INNER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
2οΈβ£ Find all students, even those without courses (Use
LEFT JOIN). SELECT Students.Name, Courses.Course_Name
FROM Students
LEFT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
3οΈβ£ Find courses that have students enrolled (Use
INNER JOIN with Course as the left table). SELECT Courses.Course_Name, Students.Name
FROM Courses
INNER JOIN Students
ON Students.Course_ID = Courses.Course_ID;
π Your Tasks for Today
β Revise INNER JOIN & LEFT JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore RIGHT JOIN, FULL JOIN, and SELF JOIN!
π Like β€οΈ and Share if youβre excited for Day 9! π
β€4π2
Day 9: SQL JOINS Continued β RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN π
Welcome back! Yesterday, we learned about INNER JOIN and LEFT JOIN, which help us combine data from multiple tables. Today, weβll continue exploring more SQL JOINS, including:
βοΈ RIGHT JOIN β Opposite of LEFT JOIN
βοΈ FULL OUTER JOIN β Returns all records from both tables
βοΈ SELF JOIN β Joining a table with itself
By the end of todayβs lesson, youβll have a strong understanding of how to combine data across tables efficiently.
---
π Recap of JOINS
πΉ INNER JOIN β Returns only matching records from both tables.
πΉ LEFT JOIN β Returns all records from the left table, with matching records from the right table.
Now, letβs move on to RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
---
πΉ RIGHT JOIN β The Opposite of LEFT JOIN
πΉ RIGHT JOIN (or RIGHT OUTER JOIN) returns:
β All records from the right table
β Matching records from the left table
β If thereβs no match, the left table will show
π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | C104 | JavaScript |
πΉ C104 (JavaScript) has no students enrolled.
π RIGHT JOIN Query:
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| NULL | JavaScript |
π JavaScript is included, but no student is enrolled (NULL in Name column).
π Key Takeaway:
Use RIGHT JOIN when you want all data from the right table and matching data from the left.
---
πΉ FULL OUTER JOIN β All Data from Both Tables
πΉ FULL OUTER JOIN returns:
β All records from both tables
β If thereβs no match,
π FULL OUTER JOIN Query:
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
| NULL | JavaScript |
π David (who has no course) and JavaScript (which has no students) are both included.
π Key Takeaway:
Use FULL OUTER JOIN when you need all data from both tables, even if thereβs no match.
βοΈ Note: Not all databases support
---
πΉ SELF JOIN β When a Table Joins Itself
πΉ Sometimes, a table contains hierarchical or related data within itself.
πΉ A SELF JOIN allows a table to join with itself to compare data in different rows.
π― Example: Employee Hierarchy
| Employee_ID | Name | Manager_ID |
|------------|--------|------------|
| 1 | Alice | NULL |
| 2 | Bob | 1 |
| 3 | Charlie| 1 |
| 4 | David | 2 |
πΉ Here, Bob and Charlie report to Alice, and David reports to Bob.
π SELF JOIN Query to Find Employee-Manager Relationship:
πΉ Output
| Employee | Manager |
|----------|---------|
| Alice | NULL |
| Bob | Alice |
| Charlie | Alice |
| David | Bob |
π Alice has no manager (NULL), Bob & Charlie report to Alice, and David reports to Bob.
Welcome back! Yesterday, we learned about INNER JOIN and LEFT JOIN, which help us combine data from multiple tables. Today, weβll continue exploring more SQL JOINS, including:
βοΈ RIGHT JOIN β Opposite of LEFT JOIN
βοΈ FULL OUTER JOIN β Returns all records from both tables
βοΈ SELF JOIN β Joining a table with itself
By the end of todayβs lesson, youβll have a strong understanding of how to combine data across tables efficiently.
---
π Recap of JOINS
πΉ INNER JOIN β Returns only matching records from both tables.
πΉ LEFT JOIN β Returns all records from the left table, with matching records from the right table.
Now, letβs move on to RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
---
πΉ RIGHT JOIN β The Opposite of LEFT JOIN
πΉ RIGHT JOIN (or RIGHT OUTER JOIN) returns:
β All records from the right table
β Matching records from the left table
β If thereβs no match, the left table will show
NULL values π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | C104 | JavaScript |
πΉ C104 (JavaScript) has no students enrolled.
π RIGHT JOIN Query:
SELECT Students.Name, Courses.Course_Name
FROM Students
RIGHT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| NULL | JavaScript |
π JavaScript is included, but no student is enrolled (NULL in Name column).
π Key Takeaway:
Use RIGHT JOIN when you want all data from the right table and matching data from the left.
---
πΉ FULL OUTER JOIN β All Data from Both Tables
πΉ FULL OUTER JOIN returns:
β All records from both tables
β If thereβs no match,
NULL values will be filled π FULL OUTER JOIN Query:
SELECT Students.Name, Courses.Course_Name
FROM Students
FULL OUTER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
| NULL | JavaScript |
π David (who has no course) and JavaScript (which has no students) are both included.
π Key Takeaway:
Use FULL OUTER JOIN when you need all data from both tables, even if thereβs no match.
βοΈ Note: Not all databases support
FULL OUTER JOIN. If yours doesnβt, you can simulate it using `UNION`:SELECT Students.Name, Courses.Course_Name
FROM Students
LEFT JOIN Courses ON Students.Course_ID = Courses.Course_ID
UNION
SELECT Students.Name, Courses.Course_Name
FROM Students
RIGHT JOIN Courses ON Students.Course_ID = Courses.Course_ID;
---
πΉ SELF JOIN β When a Table Joins Itself
πΉ Sometimes, a table contains hierarchical or related data within itself.
πΉ A SELF JOIN allows a table to join with itself to compare data in different rows.
π― Example: Employee Hierarchy
| Employee_ID | Name | Manager_ID |
|------------|--------|------------|
| 1 | Alice | NULL |
| 2 | Bob | 1 |
| 3 | Charlie| 1 |
| 4 | David | 2 |
πΉ Here, Bob and Charlie report to Alice, and David reports to Bob.
π SELF JOIN Query to Find Employee-Manager Relationship:
SELECT E1.Name AS Employee, E2.Name AS Manager
FROM Employees E1
LEFT JOIN Employees E2
ON E1.Manager_ID = E2.Employee_ID;
πΉ Output
| Employee | Manager |
|----------|---------|
| Alice | NULL |
| Bob | Alice |
| Charlie | Alice |
| David | Bob |
π Alice has no manager (NULL), Bob & Charlie report to Alice, and David reports to Bob.
π2
π Key Takeaway:
Use SELF JOIN when working with hierarchical data like employees and managers, product categories, etc.
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Get all students and their courses using RIGHT JOIN.
2οΈβ£ List all students and all courses, even if there is no match (FULL OUTER JOIN).
3οΈβ£ Find employee-manager relationships using SELF JOIN.
---
π Your Tasks for Today
β Revise RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore NULL values and how to handle them in SQL!
π Like β€οΈ and Share if youβre excited for Day 10! π
Use SELF JOIN when working with hierarchical data like employees and managers, product categories, etc.
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Get all students and their courses using RIGHT JOIN.
SELECT Students.Name, Courses.Course_Name
FROM Students
RIGHT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
2οΈβ£ List all students and all courses, even if there is no match (FULL OUTER JOIN).
SELECT Students.Name, Courses.Course_Name
FROM Students
FULL OUTER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
3οΈβ£ Find employee-manager relationships using SELF JOIN.
SELECT E1.Name AS Employee, E2.Name AS Manager
FROM Employees E1
LEFT JOIN Employees E2
ON E1.Manager_ID = E2.Employee_ID;
---
π Your Tasks for Today
β Revise RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore NULL values and how to handle them in SQL!
π Like β€οΈ and Share if youβre excited for Day 10! π
β€2
Day 10: Working with NULL Values & Using CASE Statements in SQL
Welcome back! Today, weβre going to cover two important SQL topics:
βοΈ NULL values β What they are and how to handle them.
βοΈ CASE statements β A powerful way to apply conditional logic in SQL.
By the end of todayβs lesson, youβll understand how to deal with missing data (
---
π What is NULL in SQL?
πΉ In SQL, NULL means "missing" or "unknown" data.
πΉ It is not the same as
πΉ When a column has
π― Example: Employee Salaries
| Employee_ID | Name | Salary |
|------------|--------|--------|
| 1 | Alice | 50000 |
| 2 | Bob | NULL |
| 3 | Charlie| 60000 |
| 4 | David | NULL |
Bob and David have NULL salaries, meaning we donβt know their salary yet.
---
πΉ How to Handle NULL Values in SQL
1οΈβ£ Checking for NULL using `IS NULL` and `IS NOT NULL`
π Find employees whose salary is missing:
πΉ Output:
| Name |
|-------|
| Bob |
| David |
π Find employees whose salary is known:
πΉ Output:
| Name | Salary |
|--------|--------|
| Alice | 50000 |
| Charlie| 60000 |
π Important: You cannot check
---
2οΈβ£ Replacing NULL Values Using `COALESCE()`
πΉ COALESCE() replaces `NULL` with a default value.
π Example: Replace NULL salaries with "Not Assigned"
πΉ Output:
| Name | Salary |
|---------|-------------|
| Alice | 50000 |
| Bob | Not Assigned |
| Charlie | 60000 |
| David | Not Assigned |
π‘ `COALESCE()` takes multiple values and returns the first non-NULL value.
---
3οΈβ£ Handling NULL in Aggregations
πΉ Aggregate functions (SUM, AVG, COUNT, etc.) automatically ignore NULLs.
π Find total salary of all employees:
πΉ Output:
| Total_Salary |
|-------------|
| 110000 |
π NULL salaries are ignored in SUM.
π Find average salary (excluding NULL values):
πΉ Output:
| Avg_Salary |
|-----------|
| 55000 |
πΉ If you want to include NULL as 0 in calculations, use
πΉ Output:
| Avg_Salary |
|-----------|
| 36666.67 |
Now, let's move on to CASE statements.
---
πΉ Using CASE Statements in SQL
πΉ
πΉ It allows you to return different values based on conditions.
π― Example: Categorizing Employees by Salary
πΉ Output:
| Name | Salary | Salary_Category |
|---------|--------|----------------|
| Alice | 50000 | Medium Salary |
| Bob | NULL | Low Salary |
| Charlie | 60000 | High Salary |
| David | NULL | Low Salary |
π NULL values are treated as `ELSE` conditions unless handled separately.
π Handling NULL separately in CASE:
πΉ Now, NULL values are labeled as "Salary Not Available".
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find all employees whose salary is NULL.
2οΈβ£ Replace NULL salaries with 0.
Welcome back! Today, weβre going to cover two important SQL topics:
βοΈ NULL values β What they are and how to handle them.
βοΈ CASE statements β A powerful way to apply conditional logic in SQL.
By the end of todayβs lesson, youβll understand how to deal with missing data (
NULL) and how to write conditional logic directly in SQL queries. ---
π What is NULL in SQL?
πΉ In SQL, NULL means "missing" or "unknown" data.
πΉ It is not the same as
0 or an empty string (""). πΉ When a column has
NULL, it means no value has been assigned yet. π― Example: Employee Salaries
| Employee_ID | Name | Salary |
|------------|--------|--------|
| 1 | Alice | 50000 |
| 2 | Bob | NULL |
| 3 | Charlie| 60000 |
| 4 | David | NULL |
Bob and David have NULL salaries, meaning we donβt know their salary yet.
---
πΉ How to Handle NULL Values in SQL
1οΈβ£ Checking for NULL using `IS NULL` and `IS NOT NULL`
π Find employees whose salary is missing:
SELECT Name
FROM Employees
WHERE Salary IS NULL;
πΉ Output:
| Name |
|-------|
| Bob |
| David |
π Find employees whose salary is known:
SELECT Name, Salary
FROM Employees
WHERE Salary IS NOT NULL;
πΉ Output:
| Name | Salary |
|--------|--------|
| Alice | 50000 |
| Charlie| 60000 |
π Important: You cannot check
NULL with = NULL or != NULL. Always use IS NULL or IS NOT NULL.---
2οΈβ£ Replacing NULL Values Using `COALESCE()`
πΉ COALESCE() replaces `NULL` with a default value.
π Example: Replace NULL salaries with "Not Assigned"
SELECT Name, COALESCE(Salary, 'Not Assigned') AS Salary
FROM Employees;
πΉ Output:
| Name | Salary |
|---------|-------------|
| Alice | 50000 |
| Bob | Not Assigned |
| Charlie | 60000 |
| David | Not Assigned |
π‘ `COALESCE()` takes multiple values and returns the first non-NULL value.
---
3οΈβ£ Handling NULL in Aggregations
πΉ Aggregate functions (SUM, AVG, COUNT, etc.) automatically ignore NULLs.
π Find total salary of all employees:
SELECT SUM(Salary) AS Total_Salary
FROM Employees;
πΉ Output:
| Total_Salary |
|-------------|
| 110000 |
π NULL salaries are ignored in SUM.
π Find average salary (excluding NULL values):
SELECT AVG(Salary) AS Avg_Salary
FROM Employees;
πΉ Output:
| Avg_Salary |
|-----------|
| 55000 |
πΉ If you want to include NULL as 0 in calculations, use
COALESCE(Salary, 0): SELECT AVG(COALESCE(Salary, 0)) AS Avg_Salary
FROM Employees;
πΉ Output:
| Avg_Salary |
|-----------|
| 36666.67 |
Now, let's move on to CASE statements.
---
πΉ Using CASE Statements in SQL
πΉ
CASE is like an IF-ELSE statement in SQL. πΉ It allows you to return different values based on conditions.
π― Example: Categorizing Employees by Salary
SELECT Name, Salary,
CASE
WHEN Salary >= 60000 THEN 'High Salary'
WHEN Salary >= 40000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS Salary_Category
FROM Employees;
πΉ Output:
| Name | Salary | Salary_Category |
|---------|--------|----------------|
| Alice | 50000 | Medium Salary |
| Bob | NULL | Low Salary |
| Charlie | 60000 | High Salary |
| David | NULL | Low Salary |
π NULL values are treated as `ELSE` conditions unless handled separately.
π Handling NULL separately in CASE:
SELECT Name,
CASE
WHEN Salary IS NULL THEN 'Salary Not Available'
WHEN Salary >= 60000 THEN 'High Salary'
WHEN Salary >= 40000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS Salary_Category
FROM Employees;
πΉ Now, NULL values are labeled as "Salary Not Available".
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find all employees whose salary is NULL.
SELECT Name FROM Employees WHERE Salary IS NULL;
2οΈβ£ Replace NULL salaries with 0.
SELECT Name, COALESCE(Salary, 0) AS Salary FROM Employees;
π4
3οΈβ£ Find employees categorized by salary range.
π Your Tasks for Today
β Practice `IS NULL`, `COALESCE()`, and `CASE` statements.
β Run the example queries in SQL.
β Solve at least 2 SQL problems from LeetCode.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, weβll dive into subqueries and correlated subqueries!
π Like β€οΈ and Share if you're excited for Day 11! π
SELECT Name,
CASE
WHEN Salary >= 70000 THEN 'High Salary'
WHEN Salary >= 50000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS Salary_Category
FROM Employees;
π Your Tasks for Today
β Practice `IS NULL`, `COALESCE()`, and `CASE` statements.
β Run the example queries in SQL.
β Solve at least 2 SQL problems from LeetCode.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, weβll dive into subqueries and correlated subqueries!
π Like β€οΈ and Share if you're excited for Day 11! π
β€4
As I was having Uni exam, therefore, will continue this series from tomorrow.
Happy Learning!!
Happy Learning!!
π7
Let's continue our learning!!
Day 11: Understanding Subqueries and Correlated Subqueries in SQL
Welcome back! Today, we are going to explore an advanced yet essential SQL concept: Subqueries and Correlated Subqueries.
By the end of todayβs session, you will understand:
βοΈ What subqueries are and how they work.
βοΈ The difference between subqueries and correlated subqueries.
βοΈ When and how to use them in SQL queries.
---
π What is a Subquery in SQL?
A subquery is a query inside another query.
- It is also called a nested query.
- It helps fetch data from multiple tables in a structured way.
- The result of the subquery is used in the main query.
π Basic Syntax of a Subquery
- The inner query (subquery) runs first.
- The outer query then uses the subqueryβs result.
---
πΉ Example 1: Find Employees Who Earn More Than the Average Salary
π― Problem Statement:
We want to find employees whose salaries are higher than the average salary of all employees.
π SQL Query:
π How it Works?
1. Subquery:
- Finds the average salary from the
2. Main Query:
- Selects employees whose salaries are greater than this average.
β Example Output:
| Name | Salary |
|---------|--------|
| Charlie | 60000 |
---
πΉ Example 2: Find Customers Who Placed Orders
π― Problem Statement:
We want to find customers who have placed at least one order.
π SQL Query:
π How it Works?
1. Subquery:
- Finds unique customers who placed orders.
2. Main Query:
- Selects those customers from the
β Example Output:
| CustomerID | CustomerName |
|-----------|--------------|
| 101 | Alice |
| 102 | Bob |
---
π Types of Subqueries in SQL
There are three types of subqueries:
1οΈβ£ Single-Row Subquery: Returns one value.
2οΈβ£ Multi-Row Subquery: Returns multiple values.
3οΈβ£ Multi-Column Subquery: Returns multiple columns.
πΉ Single-Row Subquery Example
Find employees whose salaries are equal to the highest salary.
β Returns one row because MAX(Salary) is a single value.
---
πΉ Multi-Row Subquery Example
Find all employees who work in departments located in New York.
β The subquery returns multiple DepartmentIDs, so we use
---
πΉ Multi-Column Subquery Example
Find employees whose department and location match the highest-paid employee.
β The subquery returns two columns, so we use a tuple (DepartmentID, Location).
---
π What is a Correlated Subquery?
A correlated subquery is different from a regular subquery:
β The subquery depends on the outer query.
β The subquery runs once for each row in the main query.
β It is usually used with
---
πΉ Example 3: Correlated Subquery
π― Problem Statement:
Find employees who earn more than the average salary of their own department.
π SQL Query:
π How it Works?
1. The subquery depends on the outer query.
2. It calculates the average salary per department.
3. The main query checks if each employee's salary is higher than their departmentβs average.
Day 11: Understanding Subqueries and Correlated Subqueries in SQL
Welcome back! Today, we are going to explore an advanced yet essential SQL concept: Subqueries and Correlated Subqueries.
By the end of todayβs session, you will understand:
βοΈ What subqueries are and how they work.
βοΈ The difference between subqueries and correlated subqueries.
βοΈ When and how to use them in SQL queries.
---
π What is a Subquery in SQL?
A subquery is a query inside another query.
- It is also called a nested query.
- It helps fetch data from multiple tables in a structured way.
- The result of the subquery is used in the main query.
π Basic Syntax of a Subquery
SELECT column1, column2
FROM main_table
WHERE column_name OPERATOR (
SELECT column_name FROM sub_table WHERE condition
);
- The inner query (subquery) runs first.
- The outer query then uses the subqueryβs result.
---
πΉ Example 1: Find Employees Who Earn More Than the Average Salary
π― Problem Statement:
We want to find employees whose salaries are higher than the average salary of all employees.
π SQL Query:
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
π How it Works?
1. Subquery:
SELECT AVG(Salary) FROM Employees; - Finds the average salary from the
Employees table. 2. Main Query:
- Selects employees whose salaries are greater than this average.
β Example Output:
| Name | Salary |
|---------|--------|
| Charlie | 60000 |
---
πΉ Example 2: Find Customers Who Placed Orders
π― Problem Statement:
We want to find customers who have placed at least one order.
π SQL Query:
SELECT CustomerID, CustomerName
FROM Customers
WHERE CustomerID IN (SELECT DISTINCT CustomerID FROM Orders);
π How it Works?
1. Subquery:
SELECT DISTINCT CustomerID FROM Orders; - Finds unique customers who placed orders.
2. Main Query:
- Selects those customers from the
Customers table. β Example Output:
| CustomerID | CustomerName |
|-----------|--------------|
| 101 | Alice |
| 102 | Bob |
---
π Types of Subqueries in SQL
There are three types of subqueries:
1οΈβ£ Single-Row Subquery: Returns one value.
2οΈβ£ Multi-Row Subquery: Returns multiple values.
3οΈβ£ Multi-Column Subquery: Returns multiple columns.
πΉ Single-Row Subquery Example
Find employees whose salaries are equal to the highest salary.
SELECT Name, Salary
FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees);
β Returns one row because MAX(Salary) is a single value.
---
πΉ Multi-Row Subquery Example
Find all employees who work in departments located in New York.
SELECT Name, DepartmentID
FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Location = 'New York');
β The subquery returns multiple DepartmentIDs, so we use
IN.---
πΉ Multi-Column Subquery Example
Find employees whose department and location match the highest-paid employee.
SELECT Name, DepartmentID, Location
FROM Employees
WHERE (DepartmentID, Location) =
(SELECT DepartmentID, Location FROM Employees ORDER BY Salary DESC LIMIT 1);
β The subquery returns two columns, so we use a tuple (DepartmentID, Location).
---
π What is a Correlated Subquery?
A correlated subquery is different from a regular subquery:
β The subquery depends on the outer query.
β The subquery runs once for each row in the main query.
β It is usually used with
EXISTS, NOT EXISTS, or WHERE clauses. ---
πΉ Example 3: Correlated Subquery
π― Problem Statement:
Find employees who earn more than the average salary of their own department.
π SQL Query:
SELECT e1.Name, e1.DepartmentID, e1.Salary
FROM Employees e1
WHERE Salary > (
SELECT AVG(e2.Salary)
FROM Employees e2
WHERE e1.DepartmentID = e2.DepartmentID
);
π How it Works?
1. The subquery depends on the outer query.
2. It calculates the average salary per department.
3. The main query checks if each employee's salary is higher than their departmentβs average.
π4β€1
β
Example Output:
| Name | DepartmentID | Salary |
|---------|-------------|--------|
| Alice | 101 | 50000 |
| Charlie | 102 | 60000 |
---
π Difference Between Subquery and Correlated Subquery
| Feature | Subquery | Correlated Subquery |
|---------|----------|--------------------|
| Runs | Runs once | Runs once per row in main query |
| Dependent on Outer Query? | No | Yes |
| Performance | Faster | Slower |
| Example Usage | Find employees with salary above average | Find employees earning above their departmentβs average |
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find all employees who have the same salary as Bob.
2οΈβ£ Find all orders placed in 2024 by customers who live in New York.
3οΈβ£ Find employees whose salary is higher than the average salary in their department.
---
π Your Tasks for Today
β Practice at least 3 subquery-based problems.
β Try writing a correlated subquery.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore JOINS and their types in SQL!
π Like β€οΈ and Share if you're excited for Day 12! π
| Name | DepartmentID | Salary |
|---------|-------------|--------|
| Alice | 101 | 50000 |
| Charlie | 102 | 60000 |
---
π Difference Between Subquery and Correlated Subquery
| Feature | Subquery | Correlated Subquery |
|---------|----------|--------------------|
| Runs | Runs once | Runs once per row in main query |
| Dependent on Outer Query? | No | Yes |
| Performance | Faster | Slower |
| Example Usage | Find employees with salary above average | Find employees earning above their departmentβs average |
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find all employees who have the same salary as Bob.
SELECT Name FROM Employees WHERE Salary =
(SELECT Salary FROM Employees WHERE Name = 'Bob');
2οΈβ£ Find all orders placed in 2024 by customers who live in New York.
SELECT OrderID FROM Orders
WHERE CustomerID IN (SELECT CustomerID FROM Customers WHERE City = 'New York')
AND OrderDate BETWEEN '2024-01-01' AND '2024-12-31';
3οΈβ£ Find employees whose salary is higher than the average salary in their department.
SELECT Name, Salary FROM Employees e1
WHERE Salary > (SELECT AVG(Salary) FROM Employees e2 WHERE e1.DepartmentID = e2.DepartmentID);
---
π Your Tasks for Today
β Practice at least 3 subquery-based problems.
β Try writing a correlated subquery.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore JOINS and their types in SQL!
π Like β€οΈ and Share if you're excited for Day 12! π
β€3
Day 12: Understanding SQL JOINS (Beginner to Advanced)
Welcome to Day 12 of your SQL learning journey! π Today, we are diving deep into one of the most important concepts in SQL β JOINS.
By the end of todayβs session, you will understand:
βοΈ What JOINS are and why we use them
βοΈ Types of SQL JOINS and their differences
βοΈ How to use JOINS in real-world scenarios
βοΈ Practical SQL examples for each type of JOIN
---
# π What is a JOIN in SQL?
A JOIN in SQL is used to combine data from multiple tables based on a common column.
π Why Do We Need JOINS?
- Databases store data in multiple tables to maintain efficiency.
- To retrieve meaningful information, we need to combine data from different tables.
- JOINS help us link related records in different tables.
π Basic Syntax of a JOIN
-
-
---
π Types of SQL JOINS
There are four main types of JOINS in SQL:
| Type of JOIN | Returns |
|-------------|---------|
| INNER JOIN | Only matching rows from both tables |
| LEFT JOIN (or LEFT OUTER JOIN) | All rows from the left table + matching rows from the right table |
| RIGHT JOIN (or RIGHT OUTER JOIN) | All rows from the right table + matching rows from the left table |
| FULL JOIN (or FULL OUTER JOIN) | All rows from both tables (matches + non-matches) |
Letβs explore each type with real-world examples!
---
πΉ INNER JOIN (Most Common JOIN)
π― Problem Statement:
Find the names of customers who placed orders.
π SQL Query:
π How it Works?
- The
- If a customer has not placed an order, they will not appear in the result.
β Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
---
πΉ LEFT JOIN (LEFT OUTER JOIN)
π― Problem Statement:
Find all customers, even those who have not placed any orders.
π SQL Query:
π How it Works?
- Returns all customers from the
- If a customer has not placed an order, the
β Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
| 103 | Charlie | NULL | β (No orders)
---
πΉ RIGHT JOIN (RIGHT OUTER JOIN)
π― Problem Statement:
Find all orders, even those placed by non-existing customers.
π SQL Query:
π How it Works?
- Returns all orders from the
- If an order has no matching customer,
β Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
| NULL | NULL | 5003 | β (Order placed by a deleted customer)
---
πΉ FULL JOIN (FULL OUTER JOIN)
π― Problem Statement:
Find all customers and all orders, even if there is no match.
π SQL Query:
π How it Works?
- Returns all customers and all orders, including non-matching records.
Welcome to Day 12 of your SQL learning journey! π Today, we are diving deep into one of the most important concepts in SQL β JOINS.
By the end of todayβs session, you will understand:
βοΈ What JOINS are and why we use them
βοΈ Types of SQL JOINS and their differences
βοΈ How to use JOINS in real-world scenarios
βοΈ Practical SQL examples for each type of JOIN
---
# π What is a JOIN in SQL?
A JOIN in SQL is used to combine data from multiple tables based on a common column.
π Why Do We Need JOINS?
- Databases store data in multiple tables to maintain efficiency.
- To retrieve meaningful information, we need to combine data from different tables.
- JOINS help us link related records in different tables.
π Basic Syntax of a JOIN
SELECT columns
FROM table1
JOIN table2
ON table1.common_column = table2.common_column;
-
JOIN tells SQL to combine data from both tables. -
ON specifies the matching condition. ---
π Types of SQL JOINS
There are four main types of JOINS in SQL:
| Type of JOIN | Returns |
|-------------|---------|
| INNER JOIN | Only matching rows from both tables |
| LEFT JOIN (or LEFT OUTER JOIN) | All rows from the left table + matching rows from the right table |
| RIGHT JOIN (or RIGHT OUTER JOIN) | All rows from the right table + matching rows from the left table |
| FULL JOIN (or FULL OUTER JOIN) | All rows from both tables (matches + non-matches) |
Letβs explore each type with real-world examples!
---
πΉ INNER JOIN (Most Common JOIN)
π― Problem Statement:
Find the names of customers who placed orders.
π SQL Query:
SELECT Customers.CustomerID, Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
π How it Works?
- The
INNER JOIN returns only rows where there is a match in both tables. - If a customer has not placed an order, they will not appear in the result.
β Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
---
πΉ LEFT JOIN (LEFT OUTER JOIN)
π― Problem Statement:
Find all customers, even those who have not placed any orders.
π SQL Query:
SELECT Customers.CustomerID, Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
π How it Works?
- Returns all customers from the
Customers table. - If a customer has not placed an order, the
OrderID will be NULL. β Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
| 103 | Charlie | NULL | β (No orders)
---
πΉ RIGHT JOIN (RIGHT OUTER JOIN)
π― Problem Statement:
Find all orders, even those placed by non-existing customers.
π SQL Query:
SELECT Customers.CustomerID, Customers.CustomerName, Orders.OrderID
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
π How it Works?
- Returns all orders from the
Orders table. - If an order has no matching customer,
CustomerName will be NULL. β Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
| NULL | NULL | 5003 | β (Order placed by a deleted customer)
---
πΉ FULL JOIN (FULL OUTER JOIN)
π― Problem Statement:
Find all customers and all orders, even if there is no match.
π SQL Query:
SELECT Customers.CustomerID, Customers.CustomerName, Orders.OrderID
FROM Customers
FULL JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
π How it Works?
- Returns all customers and all orders, including non-matching records.
π1
β
Example Output:
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
| 103 | Charlie | NULL | β (No orders)
| NULL | NULL | 5003 | β (Order placed by a deleted customer)
---
π Difference Between JOINs
| JOIN Type | Returns |
|----------|---------|
| INNER JOIN | Only matching records |
| LEFT JOIN | All records from the left table + matches from the right |
| RIGHT JOIN | All records from the right table + matches from the left |
| FULL JOIN | All records from both tables |
---
πΉ CROSS JOIN (Bonus JOIN!)
π― Problem Statement:
Find all possible customer and product combinations.
π SQL Query:
π How it Works?
- Returns every possible combination of
β Example Output:
| CustomerName | ProductName |
|-------------|--------------|
| Alice | Laptop |
| Alice | Mobile |
| Bob | Laptop |
| Bob | Mobile |
π¨ Warning:
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find customers who have placed at least one order.
2οΈβ£ Find all employees and their department names.
3οΈβ£ Find all products that have never been ordered.
---
π Your Tasks for Today
β Practice at least 3 JOIN queries
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore GROUP BY, HAVING, and Aggregate Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 13! π
| CustomerID | CustomerName | OrderID |
|-----------|--------------|----------|
| 101 | Alice | 5001 |
| 102 | Bob | 5002 |
| 103 | Charlie | NULL | β (No orders)
| NULL | NULL | 5003 | β (Order placed by a deleted customer)
---
π Difference Between JOINs
| JOIN Type | Returns |
|----------|---------|
| INNER JOIN | Only matching records |
| LEFT JOIN | All records from the left table + matches from the right |
| RIGHT JOIN | All records from the right table + matches from the left |
| FULL JOIN | All records from both tables |
---
πΉ CROSS JOIN (Bonus JOIN!)
π― Problem Statement:
Find all possible customer and product combinations.
π SQL Query:
SELECT Customers.CustomerName, Products.ProductName
FROM Customers
CROSS JOIN Products;
π How it Works?
- Returns every possible combination of
Customers and Products. β Example Output:
| CustomerName | ProductName |
|-------------|--------------|
| Alice | Laptop |
| Alice | Mobile |
| Bob | Laptop |
| Bob | Mobile |
π¨ Warning:
CROSS JOIN creates a huge number of rows! ---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find customers who have placed at least one order.
SELECT Customers.CustomerName
FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
2οΈβ£ Find all employees and their department names.
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
3οΈβ£ Find all products that have never been ordered.
SELECT Products.ProductName
FROM Products
LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Orders.OrderID IS NULL;
---
π Your Tasks for Today
β Practice at least 3 JOIN queries
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore GROUP BY, HAVING, and Aggregate Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 13! π
β€3
Day 13: Date and Time Functions in SQL
Welcome to Day 13 of your SQL learning journey! π Today, we will explore Date and Time functions in SQL.
By the end of this session, you will understand:
βοΈ Why Date & Time functions are important
βοΈ Common Date & Time functions: NOW, CURDATE, DATEDIFF, DATEADD
βοΈ How to use them with practical examples
---
π Why Do We Need Date & Time Functions?
Many databases store date and time-related information, such as:
- Birthdays, order dates, or event schedules π
- Tracking when records were created or updated β³
- Performing calculations like age, time difference, and future dates
SQL provides built-in Date and Time functions to handle such operations efficiently.
---
πΉ 1. NOW() β Get the Current Date & Time
The
π SQL Query:
β Example Output:
| CurrentDateTime |
|-------------------------|
| 2025-02-18 14:30:00 |
π How It Works?
- Retrieves the exact timestamp when the query is executed.
- Useful for logging user activity, order timestamps, or event tracking.
---
πΉ 2. CURDATE() β Get the Current Date (Without Time)
The
π SQL Query:
β Example Output:
| TodayDate |
|------------|
| 2025-02-18 |
π How It Works?
- Retrieves only the date (without time).
- Useful for birthday reminders, daily reports, and scheduling.
---
πΉ 3. DATEDIFF() β Find the Difference Between Two Dates
The
π― Problem Statement:
Find how many days are left until New Yearβs Day 2026.
π SQL Query:
β Example Output:
| DaysUntilNewYear |
|------------------|
| 317 |
π How It Works?
- Subtracts the second date (
- Returns the number of days between them.
- Useful for calculating deadlines, project durations, and upcoming events.
---
πΉ 4. DATEADD() β Add or Subtract Days from a Date
The
π SQL Query (Adding 30 Days to Todayβs Date):
β Example Output:
| FutureDate |
|------------|
| 2025-03-20 |
π SQL Query (Subtracting 7 Days from Todayβs Date):
β Example Output:
| LastWeek |
|------------|
| 2025-02-11 |
π How It Works?
-
- Useful for calculating due dates, scheduling tasks, and checking expiry dates.
---
π Combining Date Functions in Real-Life Scenarios
πΉ Example 1: Find Employees Who Joined More Than 5 Years Ago
β Finds employees hired **more than 5 years ago (5Γ365 = 1825 days).
---
πΉ Example 2: Get the Date 6 Months from Today
β Useful for project deadlines, warranty periods, and subscription renewals.
---
πΉ Example 3: Find Orders Placed in the Last 7 Days
β Finds orders from the past week for reporting and analysis.
---
π Summary Table: Date & Time Functions
| Function | Description | Example Output |
|----------|------------|---------------|
| NOW() | Current date & time |
| CURDATE() | Current date only |
| DATEDIFF() | Difference between two dates |
| DATEADD() | Add/subtract days from a date |
---
π Your Tasks for Today
β Try out the queries on your SQL editor.
β Comment "Done β " once you complete todayβs practice!
Welcome to Day 13 of your SQL learning journey! π Today, we will explore Date and Time functions in SQL.
By the end of this session, you will understand:
βοΈ Why Date & Time functions are important
βοΈ Common Date & Time functions: NOW, CURDATE, DATEDIFF, DATEADD
βοΈ How to use them with practical examples
---
π Why Do We Need Date & Time Functions?
Many databases store date and time-related information, such as:
- Birthdays, order dates, or event schedules π
- Tracking when records were created or updated β³
- Performing calculations like age, time difference, and future dates
SQL provides built-in Date and Time functions to handle such operations efficiently.
---
πΉ 1. NOW() β Get the Current Date & Time
The
NOW() function returns the current date and time in the format YYYY-MM-DD HH:MI:SS. π SQL Query:
SELECT NOW() AS CurrentDateTime;
β Example Output:
| CurrentDateTime |
|-------------------------|
| 2025-02-18 14:30:00 |
π How It Works?
- Retrieves the exact timestamp when the query is executed.
- Useful for logging user activity, order timestamps, or event tracking.
---
πΉ 2. CURDATE() β Get the Current Date (Without Time)
The
CURDATE() function returns the current date in the format YYYY-MM-DD, without the time. π SQL Query:
SELECT CURDATE() AS TodayDate;
β Example Output:
| TodayDate |
|------------|
| 2025-02-18 |
π How It Works?
- Retrieves only the date (without time).
- Useful for birthday reminders, daily reports, and scheduling.
---
πΉ 3. DATEDIFF() β Find the Difference Between Two Dates
The
DATEDIFF() function calculates the difference (in days) between two dates. π― Problem Statement:
Find how many days are left until New Yearβs Day 2026.
π SQL Query:
SELECT DATEDIFF('2026-01-01', CURDATE()) AS DaysUntilNewYear;β Example Output:
| DaysUntilNewYear |
|------------------|
| 317 |
π How It Works?
- Subtracts the second date (
CURDATE()) from the first date (2026-01-01). - Returns the number of days between them.
- Useful for calculating deadlines, project durations, and upcoming events.
---
πΉ 4. DATEADD() β Add or Subtract Days from a Date
The
DATEADD() function adds or subtracts a specific number of days, months, or years from a given date. π SQL Query (Adding 30 Days to Todayβs Date):
SELECT DATE_ADD(CURDATE(), INTERVAL 30 DAY) AS FutureDate;
β Example Output:
| FutureDate |
|------------|
| 2025-03-20 |
π SQL Query (Subtracting 7 Days from Todayβs Date):
SELECT DATE_ADD(CURDATE(), INTERVAL -7 DAY) AS LastWeek;
β Example Output:
| LastWeek |
|------------|
| 2025-02-11 |
π How It Works?
-
INTERVAL X DAY adds/subtracts X days from the given date. - Useful for calculating due dates, scheduling tasks, and checking expiry dates.
---
π Combining Date Functions in Real-Life Scenarios
πΉ Example 1: Find Employees Who Joined More Than 5 Years Ago
SELECT EmployeeName, HireDate
FROM Employees
WHERE DATEDIFF(CURDATE(), HireDate) > 1825;
β Finds employees hired **more than 5 years ago (5Γ365 = 1825 days).
---
πΉ Example 2: Get the Date 6 Months from Today
SELECT DATE_ADD(CURDATE(), INTERVAL 6 MONTH) AS SixMonthsLater;
β Useful for project deadlines, warranty periods, and subscription renewals.
---
πΉ Example 3: Find Orders Placed in the Last 7 Days
SELECT OrderID, OrderDate
FROM Orders
WHERE OrderDate >= DATE_ADD(CURDATE(), INTERVAL -7 DAY);
β Finds orders from the past week for reporting and analysis.
---
π Summary Table: Date & Time Functions
| Function | Description | Example Output |
|----------|------------|---------------|
| NOW() | Current date & time |
2025-02-18 14:30:00 || CURDATE() | Current date only |
2025-02-18 || DATEDIFF() | Difference between two dates |
317 || DATEADD() | Add/subtract days from a date |
2025-03-20 |---
π Your Tasks for Today
β Try out the queries on your SQL editor.
β Comment "Done β " once you complete todayβs practice!
π3
Tomorrow, we will explore Advanced String Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 14! π
π Like β€οΈ and Share if you're excited for Day 14! π
Day 14: Combining Results in SQL β UNION, UNION ALL, INTERSECT, EXCEPT
Welcome to Day 14 of your SQL learning journey! π Today, we will learn how to combine results from multiple queries using SQL set operations:
βοΈ
βοΈ
βοΈ
βοΈ
These operations are useful when working with data from multiple tables. Letβs break them down one by one.
---
π Why Do We Need Set Operators?
Imagine you have two tables:
πΉ Table 1: Customers in the USA
| CustomerID | Name | Country |
|------------|------|---------|
| 1 | Alice | USA |
| 2 | Bob | USA |
| 3 | Charlie | USA |
πΉ Table 2: Customers in Canada
| CustomerID | Name | Country |
|------------|------|---------|
| 4 | David | Canada |
| 5 | Alice | Canada |
| 6 | Emma | Canada |
Now, let's say you want to:
- Get a list of all customers from both tables.
- Find customers who are present in both the USA and Canada tables.
- Find customers who are only in the USA but not in Canada.
We can solve these problems using
---
πΉ 1. UNION β Combine Results and Remove Duplicates
The
π SQL Query:
β Example Output:
| Name | Country |
|---------|---------|
| Alice | USA |
| Bob | USA |
| Charlie | USA |
| David | Canada |
| Emma | Canada |
π How It Works?
- Combines the records from both tables.
- Removes duplicates (Notice Alice appears only once).
- Useful when merging data from multiple sources without duplicates.
---
πΉ 2. UNION ALL β Combine Results Without Removing Duplicates
The
π SQL Query:
β Example Output:
| Name | Country |
|---------|---------|
| Alice | USA |
| Bob | USA |
| Charlie | USA |
| David | Canada |
| Alice | Canada |
| Emma | Canada |
π How It Works?
- Similar to
- Faster than
- Useful when you want to keep all records, even duplicates.
---
πΉ 3. INTERSECT β Find Common Records in Both Queries
The
π SQL Query:
β Example Output:
| Name | Country |
|------|---------|
| Alice | USA |
π How It Works?
- Finds common values in both queries.
- Useful when you need to find customers, products, or employees that exist in both lists.
---
πΉ 4. EXCEPT β Find Records Present in One Query But Not in the Other
The
π SQL Query (Find customers who are in the USA but not in Canada):
β Example Output:
| Name | Country |
|---------|---------|
| Bob | USA |
| Charlie | USA |
π How It Works?
- Returns records only present in the first query, but not in the second query.
- Useful for finding unique records that do not exist in another dataset.
---
Welcome to Day 14 of your SQL learning journey! π Today, we will learn how to combine results from multiple queries using SQL set operations:
βοΈ
UNION β Combines results and removes duplicates βοΈ
UNION ALL β Combines results without removing duplicates βοΈ
INTERSECT β Returns common records between two queries βοΈ
EXCEPT β Returns records present in one query but not in the other These operations are useful when working with data from multiple tables. Letβs break them down one by one.
---
π Why Do We Need Set Operators?
Imagine you have two tables:
πΉ Table 1: Customers in the USA
| CustomerID | Name | Country |
|------------|------|---------|
| 1 | Alice | USA |
| 2 | Bob | USA |
| 3 | Charlie | USA |
πΉ Table 2: Customers in Canada
| CustomerID | Name | Country |
|------------|------|---------|
| 4 | David | Canada |
| 5 | Alice | Canada |
| 6 | Emma | Canada |
Now, let's say you want to:
- Get a list of all customers from both tables.
- Find customers who are present in both the USA and Canada tables.
- Find customers who are only in the USA but not in Canada.
We can solve these problems using
UNION, UNION ALL, INTERSECT, and EXCEPT! ---
πΉ 1. UNION β Combine Results and Remove Duplicates
The
UNION operator combines the results of two queries and removes duplicate records. π SQL Query:
SELECT Name, Country FROM USA_Customers
UNION
SELECT Name, Country FROM Canada_Customers;
β Example Output:
| Name | Country |
|---------|---------|
| Alice | USA |
| Bob | USA |
| Charlie | USA |
| David | Canada |
| Emma | Canada |
π How It Works?
- Combines the records from both tables.
- Removes duplicates (Notice Alice appears only once).
- Useful when merging data from multiple sources without duplicates.
---
πΉ 2. UNION ALL β Combine Results Without Removing Duplicates
The
UNION ALL operator combines the results of two queries but keeps duplicate records. π SQL Query:
SELECT Name, Country FROM USA_Customers
UNION ALL
SELECT Name, Country FROM Canada_Customers;
β Example Output:
| Name | Country |
|---------|---------|
| Alice | USA |
| Bob | USA |
| Charlie | USA |
| David | Canada |
| Alice | Canada |
| Emma | Canada |
π How It Works?
- Similar to
UNION, but does not remove duplicates (Alice appears twice). - Faster than
UNION because it doesnβt check for duplicates. - Useful when you want to keep all records, even duplicates.
---
πΉ 3. INTERSECT β Find Common Records in Both Queries
The
INTERSECT operator returns only the common records present in both queries. π SQL Query:
SELECT Name, Country FROM USA_Customers
INTERSECT
SELECT Name, Country FROM Canada_Customers;
β Example Output:
| Name | Country |
|------|---------|
| Alice | USA |
π How It Works?
- Finds common values in both queries.
- Useful when you need to find customers, products, or employees that exist in both lists.
---
πΉ 4. EXCEPT β Find Records Present in One Query But Not in the Other
The
EXCEPT operator returns records from the first query that are NOT in the second query. π SQL Query (Find customers who are in the USA but not in Canada):
SELECT Name, Country FROM USA_Customers
EXCEPT
SELECT Name, Country FROM Canada_Customers;
β Example Output:
| Name | Country |
|---------|---------|
| Bob | USA |
| Charlie | USA |
π How It Works?
- Returns records only present in the first query, but not in the second query.
- Useful for finding unique records that do not exist in another dataset.
---
π1
π Summary Table: SQL Set Operators
| Operator | Description | Removes Duplicates? |
|-----------|------------|---------------------|
| UNION | Combines results from two queries | β Yes |
| UNION ALL | Combines results, including duplicates | β No |
| INTERSECT | Returns only common records | β Yes |
| EXCEPT | Returns records in the first query but not in the second | β Yes |
---
π Real-Life Use Cases of Set Operators
πΉ Merging Employee Data
Find all employees from multiple company branches without duplicates.
πΉ Finding Common Customers
Identify customers who bought from both Amazon and Flipkart.
πΉ Detecting Unused Emails
Find email addresses in the registration list that havenβt been used to place an order.
---
π Your Tasks for Today
β Try out the queries on your SQL editor.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Views and Indexes in SQL!
π Like β€οΈ and Share if you're excited for Day 15! π
| Operator | Description | Removes Duplicates? |
|-----------|------------|---------------------|
| UNION | Combines results from two queries | β Yes |
| UNION ALL | Combines results, including duplicates | β No |
| INTERSECT | Returns only common records | β Yes |
| EXCEPT | Returns records in the first query but not in the second | β Yes |
---
π Real-Life Use Cases of Set Operators
πΉ Merging Employee Data
Find all employees from multiple company branches without duplicates.
SELECT EmployeeID, Name FROM BranchA
UNION
SELECT EmployeeID, Name FROM BranchB;
πΉ Finding Common Customers
Identify customers who bought from both Amazon and Flipkart.
SELECT CustomerID FROM AmazonOrders
INTERSECT
SELECT CustomerID FROM FlipkartOrders;
πΉ Detecting Unused Emails
Find email addresses in the registration list that havenβt been used to place an order.
SELECT Email FROM Registrations
EXCEPT
SELECT Email FROM Orders;
---
π Your Tasks for Today
β Try out the queries on your SQL editor.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Views and Indexes in SQL!
π Like β€οΈ and Share if you're excited for Day 15! π
β€4π1
Day 15: Common Table Expressions (CTEs) β WITH Clause and Recursive Queries
Welcome to Day 15 of your SQL learning journey! π Today, we will dive into Common Table Expressions (CTEs), an advanced SQL concept that makes queries easier to read and write.
π What is a CTE?
A Common Table Expression (CTE) is a temporary result set that you can reference within a
β CTEs make complex queries simpler and more readable
β They help break down large queries into smaller parts
β CTEs are similar to temporary tables but exist only during query execution
---
πΉ 1. The WITH Clause β Creating a Simple CTE
The
π Basic Syntax of CTE
-
- The
π Example: Using CTE to Simplify Queries
Imagine we have a Sales table:
| OrderID | Customer | Amount | OrderDate |
|---------|---------|--------|------------|
| 1 | Alice | 500 | 2024-01-05 |
| 2 | Bob | 700 | 2024-02-10 |
| 3 | Charlie | 300 | 2024-02-15 |
| 4 | Alice | 800 | 2024-03-01 |
We want to find customers who spent more than $600 in total.
Instead of writing a complex query, we use a CTE:
β Output:
| Customer | TotalAmount |
|---------|------------|
| Alice | 1300 |
| Bob | 700 |
π How It Works?
- The CTE TotalSales calculates the total spending per customer.
- The final query filters customers with TotalAmount > 600.
- Without a CTE, this would require a nested subquery, making it harder to read!
---
πΉ 2. Recursive CTEs β Handling Hierarchical Data
A recursive CTE is a special type of CTE that refers to itself. It is useful for handling hierarchical data like:
β Employee-Manager relationships
β Category-Subcategory structures
β Family trees
π Example: Employee Hierarchy
Imagine a CompanyEmployees table:
| EmployeeID | Name | ManagerID |
|-----------|--------|----------|
| 1 | CEO | NULL |
| 2 | Alice | 1 |
| 3 | Bob | 1 |
| 4 | Charlie | 2 |
| 5 | David | 2 |
Here, the CEO (EmployeeID 1) manages Alice and Bob, while Alice manages Charlie and David.
π Recursive CTE to Find Employee Hierarchy
β Output:
| EmployeeID | Name | ManagerID | Level |
|-----------|--------|----------|------|
| 1 | CEO | NULL | 1 |
| 2 | Alice | 1 | 2 |
| 3 | Bob | 1 | 2 |
| 4 | Charlie | 2 | 3 |
| 5 | David | 2 | 3 |
π How It Works?
1οΈβ£ Base Case: The CEO (ManagerID NULL) starts at Level 1.
2οΈβ£ Recursive Case: Employees reporting to the CEO are Level 2.
3οΈβ£ Recursion continues until all employee levels are calculated.
---
π When to Use CTEs?
β When you need to simplify complex queries
β When working with hierarchical data (Employee-Manager, Categories, etc.)
β When breaking large queries into readable parts
β When avoiding repetitive subqueries
---
Welcome to Day 15 of your SQL learning journey! π Today, we will dive into Common Table Expressions (CTEs), an advanced SQL concept that makes queries easier to read and write.
π What is a CTE?
A Common Table Expression (CTE) is a temporary result set that you can reference within a
SELECT, INSERT, UPDATE, or DELETE statement. β CTEs make complex queries simpler and more readable
β They help break down large queries into smaller parts
β CTEs are similar to temporary tables but exist only during query execution
---
πΉ 1. The WITH Clause β Creating a Simple CTE
The
WITH clause is used to define a Common Table Expression (CTE). π Basic Syntax of CTE
WITH CTE_Name AS (
SELECT column1, column2
FROM table_name
WHERE condition
)
SELECT * FROM CTE_Name;
-
WITH CTE_Name AS (...) β Creates a temporary result set (CTE). - The
SELECT * FROM CTE_Name statement retrieves data from the CTE. π Example: Using CTE to Simplify Queries
Imagine we have a Sales table:
| OrderID | Customer | Amount | OrderDate |
|---------|---------|--------|------------|
| 1 | Alice | 500 | 2024-01-05 |
| 2 | Bob | 700 | 2024-02-10 |
| 3 | Charlie | 300 | 2024-02-15 |
| 4 | Alice | 800 | 2024-03-01 |
We want to find customers who spent more than $600 in total.
Instead of writing a complex query, we use a CTE:
WITH TotalSales AS (
SELECT Customer, SUM(Amount) AS TotalAmount
FROM Sales
GROUP BY Customer
)
SELECT Customer, TotalAmount
FROM TotalSales
WHERE TotalAmount > 600;
β Output:
| Customer | TotalAmount |
|---------|------------|
| Alice | 1300 |
| Bob | 700 |
π How It Works?
- The CTE TotalSales calculates the total spending per customer.
- The final query filters customers with TotalAmount > 600.
- Without a CTE, this would require a nested subquery, making it harder to read!
---
πΉ 2. Recursive CTEs β Handling Hierarchical Data
A recursive CTE is a special type of CTE that refers to itself. It is useful for handling hierarchical data like:
β Employee-Manager relationships
β Category-Subcategory structures
β Family trees
π Example: Employee Hierarchy
Imagine a CompanyEmployees table:
| EmployeeID | Name | ManagerID |
|-----------|--------|----------|
| 1 | CEO | NULL |
| 2 | Alice | 1 |
| 3 | Bob | 1 |
| 4 | Charlie | 2 |
| 5 | David | 2 |
Here, the CEO (EmployeeID 1) manages Alice and Bob, while Alice manages Charlie and David.
π Recursive CTE to Find Employee Hierarchy
WITH EmployeeHierarchy AS (
-- Base Case: Select the CEO (Top-level manager)
SELECT EmployeeID, Name, ManagerID, 1 AS Level
FROM CompanyEmployees
WHERE ManagerID IS NULL
UNION ALL
-- Recursive Case: Select employees and increase hierarchy level
SELECT e.EmployeeID, e.Name, e.ManagerID, h.Level + 1
FROM CompanyEmployees e
INNER JOIN EmployeeHierarchy h
ON e.ManagerID = h.EmployeeID
)
SELECT * FROM EmployeeHierarchy;
β Output:
| EmployeeID | Name | ManagerID | Level |
|-----------|--------|----------|------|
| 1 | CEO | NULL | 1 |
| 2 | Alice | 1 | 2 |
| 3 | Bob | 1 | 2 |
| 4 | Charlie | 2 | 3 |
| 5 | David | 2 | 3 |
π How It Works?
1οΈβ£ Base Case: The CEO (ManagerID NULL) starts at Level 1.
2οΈβ£ Recursive Case: Employees reporting to the CEO are Level 2.
3οΈβ£ Recursion continues until all employee levels are calculated.
---
π When to Use CTEs?
β When you need to simplify complex queries
β When working with hierarchical data (Employee-Manager, Categories, etc.)
β When breaking large queries into readable parts
β When avoiding repetitive subqueries
---
π Summary Table: CTE vs. Subquery vs. Temporary Table
| Feature | CTE (
|----------|-------------|----------|----------------|
| Exists Temporarily? | β Yes | β No | β No |
| Improves Readability? | β Yes | β No | β Yes |
| Supports Recursion? | β Yes | β No | β No |
| Requires Explicit Deletion? | β No | β No | β Yes |
---
π Your Tasks for Today
β Try out the queries in your SQL editor
β Practice a recursive CTE with your own dataset
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Indexes and Performance Optimization in SQL!
π Like β€οΈ and Share if you're excited for Day 16! π
| Feature | CTE (
WITH) | Subquery | Temporary Table ||----------|-------------|----------|----------------|
| Exists Temporarily? | β Yes | β No | β No |
| Improves Readability? | β Yes | β No | β Yes |
| Supports Recursion? | β Yes | β No | β No |
| Requires Explicit Deletion? | β No | β No | β Yes |
---
π Your Tasks for Today
β Try out the queries in your SQL editor
β Practice a recursive CTE with your own dataset
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Indexes and Performance Optimization in SQL!
π Like β€οΈ and Share if you're excited for Day 16! π
β€2
Day 16: Window Functions β ROW_NUMBER, RANK, DENSE_RANK, NTILE
Welcome to Day 16 of your SQL learning journey! π Today, we will explore Window Functions, which help perform calculations across a specific group of rows without collapsing them into a single value.
π What are Window Functions?
A Window Function allows us to perform calculations over a subset of rows while keeping all original rows in the result.
β They do not group the data like `GROUP BY`
β They provide ranking, numbering, and distribution calculations
β Each row retains its identity while calculations are performed on a subset of data
---
πΉ 1. Understanding the OVER() Clause
All window functions work using the
π Basic Syntax of a Window Function
-
-
-
-
---
πΉ 2. ROW_NUMBER() β Assigning Unique Row Numbers
The
π Example: Assigning Row Numbers
Imagine we have a Students table:
| StudentID | Name | Subject | Marks |
|-----------|------|---------|-------|
| 1 | Alice | Math | 90 |
| 2 | Bob | Math | 85 |
| 3 | Charlie | Math | 85 |
| 4 | Alice | Science | 88 |
| 5 | Bob | Science | 92 |
We want to assign a row number to each student per subject based on marks.
β Output:
| Name | Subject | Marks | RowNum |
|---------|---------|-------|--------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 2 |
| Charlie | Math | 85 | 3 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- `PARTITION BY Subject` β Groups rows by subject.
- `ORDER BY Marks DESC` β Orders students by highest marks.
- Each student gets a unique row number for their subject.
---
πΉ 3. RANK() β Assigning Rank with Gaps
The
π Example: Assigning Ranks with Gaps
β Output:
| Name | Subject | Marks | RankNum |
|---------|---------|-------|--------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 2 |
| Charlie | Math | 85 | 2 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- `Bob` and `Charlie` have the same marks (85), so they get the same rank (2).
- Since ranks are skipped (`2 β 4` instead of `2 β 3`), gaps appear in the ranking.
---
πΉ 4. DENSE_RANK() β Assigning Rank Without Gaps
The
π Example: Assigning Dense Ranks
β Output:
| Name | Subject | Marks | DenseRankNum |
|---------|---------|-------|-------------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 2 |
| Charlie | Math | 85 | 2 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- Like `RANK()`, `Bob` and `Charlie` get the same rank (2).
- Unlike `RANK()`, the next rank continues (no gaps).
---
πΉ 5. NTILE(N) β Dividing Rows into Equal Groups
The
Welcome to Day 16 of your SQL learning journey! π Today, we will explore Window Functions, which help perform calculations across a specific group of rows without collapsing them into a single value.
π What are Window Functions?
A Window Function allows us to perform calculations over a subset of rows while keeping all original rows in the result.
β They do not group the data like `GROUP BY`
β They provide ranking, numbering, and distribution calculations
β Each row retains its identity while calculations are performed on a subset of data
---
πΉ 1. Understanding the OVER() Clause
All window functions work using the
OVER() clause, which defines how the calculation is applied. π Basic Syntax of a Window Function
SELECT column_name,
window_function() OVER (PARTITION BY column_name ORDER BY column_name)
FROM table_name;
-
window_function() β The function you want to apply (ROW_NUMBER(), RANK(), etc.). -
OVER() β Defines how the function operates. -
PARTITION BY column_name β Groups data into partitions (optional). -
ORDER BY column_name β Specifies row order for ranking or numbering. ---
πΉ 2. ROW_NUMBER() β Assigning Unique Row Numbers
The
ROW_NUMBER() function assigns a unique number to each row within a partition, starting from 1. π Example: Assigning Row Numbers
Imagine we have a Students table:
| StudentID | Name | Subject | Marks |
|-----------|------|---------|-------|
| 1 | Alice | Math | 90 |
| 2 | Bob | Math | 85 |
| 3 | Charlie | Math | 85 |
| 4 | Alice | Science | 88 |
| 5 | Bob | Science | 92 |
We want to assign a row number to each student per subject based on marks.
SELECT Name, Subject, Marks,
ROW_NUMBER() OVER (PARTITION BY Subject ORDER BY Marks DESC) AS RowNum
FROM Students;
β Output:
| Name | Subject | Marks | RowNum |
|---------|---------|-------|--------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 2 |
| Charlie | Math | 85 | 3 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- `PARTITION BY Subject` β Groups rows by subject.
- `ORDER BY Marks DESC` β Orders students by highest marks.
- Each student gets a unique row number for their subject.
---
πΉ 3. RANK() β Assigning Rank with Gaps
The
RANK() function assigns ranks to rows, but it allows gaps if two rows have the same value. π Example: Assigning Ranks with Gaps
SELECT Name, Subject, Marks,
RANK() OVER (PARTITION BY Subject ORDER BY Marks DESC) AS RankNum
FROM Students;
β Output:
| Name | Subject | Marks | RankNum |
|---------|---------|-------|--------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 2 |
| Charlie | Math | 85 | 2 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- `Bob` and `Charlie` have the same marks (85), so they get the same rank (2).
- Since ranks are skipped (`2 β 4` instead of `2 β 3`), gaps appear in the ranking.
---
πΉ 4. DENSE_RANK() β Assigning Rank Without Gaps
The
DENSE_RANK() function is similar to RANK(), but it does not leave gaps in the ranking. π Example: Assigning Dense Ranks
SELECT Name, Subject, Marks,
DENSE_RANK() OVER (PARTITION BY Subject ORDER BY Marks DESC) AS DenseRankNum
FROM Students;
β Output:
| Name | Subject | Marks | DenseRankNum |
|---------|---------|-------|-------------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 2 |
| Charlie | Math | 85 | 2 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- Like `RANK()`, `Bob` and `Charlie` get the same rank (2).
- Unlike `RANK()`, the next rank continues (no gaps).
---
πΉ 5. NTILE(N) β Dividing Rows into Equal Groups
The
NTILE(N) function divides rows into N equal groups.π1