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
π Example: Dividing Students into 2 Groups (NTILE(2))
β Output:
| Name | Subject | Marks | TileNum |
|---------|---------|-------|--------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 1 |
| Charlie | Math | 85 | 2 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- Rows are divided into 2 equal groups (`NTILE(2)`).
- If the number of rows isn't perfectly divisible, some groups may have one extra row.
---
π Summary of Window Functions
| Function | Purpose | Handles Ties? | Gaps in Ranking? |
|--------------|--------------------------------|-------------|---------------|
|
|
|
|
---
π When to Use Window Functions?
β When you need row numbers or rankings without grouping data.
β When working with ranked results like leaderboards.
β When dividing data into equal groups using
---
π Your Tasks for Today
β Try out the queries in your SQL editor
β Experiment with `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, and `NTILE(4)`
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Aggregate Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 17! π
SELECT Name, Subject, Marks,
NTILE(2) OVER (PARTITION BY Subject ORDER BY Marks DESC) AS TileNum
FROM Students;
β Output:
| Name | Subject | Marks | TileNum |
|---------|---------|-------|--------|
| Alice | Math | 90 | 1 |
| Bob | Math | 85 | 1 |
| Charlie | Math | 85 | 2 |
| Bob | Science | 92 | 1 |
| Alice | Science | 88 | 2 |
π How It Works?
- Rows are divided into 2 equal groups (`NTILE(2)`).
- If the number of rows isn't perfectly divisible, some groups may have one extra row.
---
π Summary of Window Functions
| Function | Purpose | Handles Ties? | Gaps in Ranking? |
|--------------|--------------------------------|-------------|---------------|
|
ROW_NUMBER()
| Assigns unique row numbers | β No | β No ||
RANK()
| Assigns ranks with gaps | β
Yes | β
Yes ||
DENSE_RANK()
| Assigns ranks without gaps | β
Yes | β No ||
NTILE(N)
| Divides rows into N groups | β No | β No |---
π When to Use Window Functions?
β When you need row numbers or rankings without grouping data.
β When working with ranked results like leaderboards.
β When dividing data into equal groups using
NTILE()
. ---
π Your Tasks for Today
β Try out the queries in your SQL editor
β Experiment with `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, and `NTILE(4)`
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Aggregate Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 17! π
Day 17: More Window Functions β LEAD, LAG, FIRST_VALUE, LAST_VALUE
Welcome to Day 17 of your SQL learning journey! π Today, we will explore advanced Window Functions, including LEAD, LAG, FIRST_VALUE, and LAST_VALUE. These functions help us compare rows within a partition by looking at previous and next values in a dataset.
π What are Window Functions?
Window functions perform calculations over a specific group of rows, similar to aggregate functions (
---
πΉ 1. LEAD() β Get the Next Rowβs Value
The
π Example: Finding Next Monthβs Sales
Imagine we have a
| Month | Sales |
|--------|-------|
| Jan | 1000 |
| Feb | 1200 |
| Mar | 1500 |
| Apr | 1300 |
We want to compare this monthβs sales with next monthβs sales.
β Output:
| Month | Sales | Next_Month_Sales |
|-------|-------|------------------|
| Jan | 1000 | 1200 |
| Feb | 1200 | 1500 |
| Mar | 1500 | 1300 |
| Apr | 1300 | NULL |
π How It Works?
-
- April has NULL because there is no next row.
β Use Cases:
- Comparing sales of the current and next month.
- Finding future trends in data.
---
πΉ 2. LAG() β Get the Previous Rowβs Value
The
π Example: Comparing Current Sales with Previous Month
β Output:
| Month | Sales | Prev_Month_Sales |
|-------|-------|------------------|
| Jan | 1000 | NULL |
| Feb | 1200 | 1000 |
| Mar | 1500 | 1200 |
| Apr | 1300 | 1500 |
π How It Works?
-
- January has NULL because there is no previous row.
β Use Cases:
- Comparing current and past values in sales, stock prices, etc.
- Analyzing month-over-month or year-over-year changes.
---
πΉ 3. FIRST_VALUE() β Get the First Rowβs Value
The
π Example: Finding the First Monthβs Sales
β Output:
| Month | Sales | First_Month_Sales |
|-------|-------|------------------|
| Jan | 1000 | 1000 |
| Feb | 1200 | 1000 |
| Mar | 1500 | 1000 |
| Apr | 1300 | 1000 |
π How It Works?
-
β Use Cases:
- Finding the initial value for a dataset.
- Comparing each row to the starting value.
---
πΉ 4. LAST_VALUE() β Get the Last Rowβs Value
The
π Example: Finding the Latest Monthβs Sales
β Output:
| Month | Sales | Last_Month_Sales |
|-------|-------|-----------------|
| Jan | 1000 | 1300 |
| Feb | 1200 | 1300 |
| Mar | 1500 | 1300 |
| Apr | 1300 | 1300 |
Welcome to Day 17 of your SQL learning journey! π Today, we will explore advanced Window Functions, including LEAD, LAG, FIRST_VALUE, and LAST_VALUE. These functions help us compare rows within a partition by looking at previous and next values in a dataset.
π What are Window Functions?
Window functions perform calculations over a specific group of rows, similar to aggregate functions (
SUM
, AVG
, etc.), but they do not collapse rows into a single output. Instead, they return results for each row individually while considering values from other rows.---
πΉ 1. LEAD() β Get the Next Rowβs Value
The
LEAD()
function fetches the value from the next row within the same partition. It is useful for comparing current and next row values. π Example: Finding Next Monthβs Sales
Imagine we have a
Sales
table:| Month | Sales |
|--------|-------|
| Jan | 1000 |
| Feb | 1200 |
| Mar | 1500 |
| Apr | 1300 |
We want to compare this monthβs sales with next monthβs sales.
SELECT Month, Sales,
LEAD(Sales) OVER (ORDER BY Month) AS Next_Month_Sales
FROM Sales;
β Output:
| Month | Sales | Next_Month_Sales |
|-------|-------|------------------|
| Jan | 1000 | 1200 |
| Feb | 1200 | 1500 |
| Mar | 1500 | 1300 |
| Apr | 1300 | NULL |
π How It Works?
-
LEAD(Sales) OVER (ORDER BY Month)
β Looks at the next rowβs sales value. - April has NULL because there is no next row.
β Use Cases:
- Comparing sales of the current and next month.
- Finding future trends in data.
---
πΉ 2. LAG() β Get the Previous Rowβs Value
The
LAG()
function fetches the value from the previous row within the same partition. It helps in comparing a current row with its previous row. π Example: Comparing Current Sales with Previous Month
SELECT Month, Sales,
LAG(Sales) OVER (ORDER BY Month) AS Prev_Month_Sales
FROM Sales;
β Output:
| Month | Sales | Prev_Month_Sales |
|-------|-------|------------------|
| Jan | 1000 | NULL |
| Feb | 1200 | 1000 |
| Mar | 1500 | 1200 |
| Apr | 1300 | 1500 |
π How It Works?
-
LAG(Sales) OVER (ORDER BY Month)
β Looks at the previous rowβs sales value. - January has NULL because there is no previous row.
β Use Cases:
- Comparing current and past values in sales, stock prices, etc.
- Analyzing month-over-month or year-over-year changes.
---
πΉ 3. FIRST_VALUE() β Get the First Rowβs Value
The
FIRST_VALUE()
function returns the first value in a partition. It is useful when you need to reference the earliest or starting value. π Example: Finding the First Monthβs Sales
SELECT Month, Sales,
FIRST_VALUE(Sales) OVER (ORDER BY Month) AS First_Month_Sales
FROM Sales;
β Output:
| Month | Sales | First_Month_Sales |
|-------|-------|------------------|
| Jan | 1000 | 1000 |
| Feb | 1200 | 1000 |
| Mar | 1500 | 1000 |
| Apr | 1300 | 1000 |
π How It Works?
-
FIRST_VALUE(Sales) OVER (ORDER BY Month)
β Returns the first rowβs sales value (1000) for every row. β Use Cases:
- Finding the initial value for a dataset.
- Comparing each row to the starting value.
---
πΉ 4. LAST_VALUE() β Get the Last Rowβs Value
The
LAST_VALUE()
function returns the last value in a partition. It helps in identifying the latest value in an ordered dataset. π Example: Finding the Latest Monthβs Sales
SELECT Month, Sales,
LAST_VALUE(Sales) OVER (ORDER BY Month ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS Last_Month_Sales
FROM Sales;
β Output:
| Month | Sales | Last_Month_Sales |
|-------|-------|-----------------|
| Jan | 1000 | 1300 |
| Feb | 1200 | 1300 |
| Mar | 1500 | 1300 |
| Apr | 1300 | 1300 |
π1
π How It Works?
-
-
β Use Cases:
- Finding the latest recorded value.
- Comparing current values to the last recorded value.
---
π Summary of Window Functions
| Function | Purpose | Example Use |
|--------------|---------------------------------|----------------------------|
|
|
|
|
---
π When to Use These Functions?
β When comparing current and previous row values (
β When comparing current and next row values (
β When finding the first value in a dataset (
β When finding the latest value in a dataset (
---
π Your Tasks for Today
β Try out the queries in your SQL editor.
β Experiment with `LEAD()`, `LAG()`, `FIRST_VALUE()`, and `LAST_VALUE()`.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Advanced Joins in SQL!
π Like β€οΈ and Share if you're excited for Day 18! π
-
LAST_VALUE(Sales) OVER (...)
β Looks at the last rowβs sales value (1300). -
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
ensures it considers all rows. β Use Cases:
- Finding the latest recorded value.
- Comparing current values to the last recorded value.
---
π Summary of Window Functions
| Function | Purpose | Example Use |
|--------------|---------------------------------|----------------------------|
|
LEAD()
| Get the next rowβs value | Comparing current vs next row ||
LAG()
| Get the previous rowβs value | Comparing current vs previous row ||
FIRST_VALUE()
| Get the first rowβs value | Finding the starting value ||
LAST_VALUE()
| Get the last rowβs value | Finding the latest value |---
π When to Use These Functions?
β When comparing current and previous row values (
LAG()
). β When comparing current and next row values (
LEAD()
). β When finding the first value in a dataset (
FIRST_VALUE()
). β When finding the latest value in a dataset (
LAST_VALUE()
). ---
π Your Tasks for Today
β Try out the queries in your SQL editor.
β Experiment with `LEAD()`, `LAG()`, `FIRST_VALUE()`, and `LAST_VALUE()`.
β Comment "Done β " once you complete todayβs practice!
Tomorrow, we will explore Advanced Joins in SQL!
π Like β€οΈ and Share if you're excited for Day 18! π
π1
I hope you all are finding this series interesting and helpful at the same time.
IF there's anything that you guys want to add, do let me know.
Happy Learning!!
IF there's anything that you guys want to add, do let me know.
Happy Learning!!
# Day 18: Creating and Managing Views, Temporary Tables, and Table Variables
Welcome to Day 18 of your SQL learning journey! π Today, we will explore:
βοΈ Views β A way to store queries as virtual tables.
βοΈ Temporary Tables β Short-term tables used for temporary data storage.
βοΈ Table Variables β Variables that store table-like structures in memory.
Each of these concepts helps us organize data, improve query performance, and manage temporary results efficiently. Letβs dive in!
---
πΉ 1. What is a VIEW in SQL?
A VIEW is a virtual table created from a SQL query. It does not store actual data but fetches it from the original table(s) whenever queried.
π Why Use Views?
β Simplifies Complex Queries β You can save a query as a view and reuse it.
β Security β You can restrict access by exposing only necessary columns.
β Consistency β Ensures that all users work with the same data representation.
---
π Example: Creating a VIEW
Letβs say we have a table called
| EmployeeID | Name | Department | Salary |
|-----------|------|------------|--------|
| 1 | John | HR | 50000 |
| 2 | Alice | IT | 70000 |
| 3 | Bob | Finance | 60000 |
Now, we create a VIEW that shows only IT department employees:
β Now, instead of writing the same query again, we can just run:
Output:
| EmployeeID | Name | Salary |
|-----------|------|--------|
| 2 | Alice | 70000 |
π Managing Views
βοΈ Updating a View:
βοΈ Deleting a View:
βοΈ Updating Data in a View:
- If the view is based on a single table, you can update data directly:
- If the view is based on multiple tables, updating may not be allowed.
---
πΉ 2. What are Temporary Tables in SQL?
A Temporary Table is a table that exists only for the duration of a session. Once the session ends, the table is automatically deleted.
π Why Use Temporary Tables?
β Store Intermediate Data β Useful when working with complex calculations or large datasets.
β Improve Performance β Speeds up queries by reducing redundant computations.
β Prevents Changes to Main Tables β Temporary tables do not affect original data.
---
π Example: Creating a Temporary Table
A temporary table name starts with `#`.
Now, we insert some values:
β Fetching Data from Temporary Table
Output:
| EmployeeID | Name | Salary |
|-----------|------|--------|
| 1 | John | 50000 |
| 2 | Alice | 70000 |
β Deleting a Temporary Table
π‘ Note: Temporary tables are deleted automatically once the session ends!
---
πΉ 3. What are Table Variables?
A Table Variable is a special type of variable in SQL that holds table-like data. Unlike temporary tables, table variables do not persist beyond the batch execution.
π Why Use Table Variables?
β Uses Less System Resources β Stored in memory, making operations faster.
β Does Not Require Explicit Deletion β Automatically removed after execution.
β Better for Small Datasets β Works best when dealing with a few rows of data.
---
π Example: Creating a Table Variable
β Inserting Data
β Fetching Data from a Table Variable
Output:
Welcome to Day 18 of your SQL learning journey! π Today, we will explore:
βοΈ Views β A way to store queries as virtual tables.
βοΈ Temporary Tables β Short-term tables used for temporary data storage.
βοΈ Table Variables β Variables that store table-like structures in memory.
Each of these concepts helps us organize data, improve query performance, and manage temporary results efficiently. Letβs dive in!
---
πΉ 1. What is a VIEW in SQL?
A VIEW is a virtual table created from a SQL query. It does not store actual data but fetches it from the original table(s) whenever queried.
π Why Use Views?
β Simplifies Complex Queries β You can save a query as a view and reuse it.
β Security β You can restrict access by exposing only necessary columns.
β Consistency β Ensures that all users work with the same data representation.
---
π Example: Creating a VIEW
Letβs say we have a table called
Employees
: | EmployeeID | Name | Department | Salary |
|-----------|------|------------|--------|
| 1 | John | HR | 50000 |
| 2 | Alice | IT | 70000 |
| 3 | Bob | Finance | 60000 |
Now, we create a VIEW that shows only IT department employees:
CREATE VIEW IT_Employees AS
SELECT EmployeeID, Name, Salary
FROM Employees
WHERE Department = 'IT';
β Now, instead of writing the same query again, we can just run:
SELECT * FROM IT_Employees;
Output:
| EmployeeID | Name | Salary |
|-----------|------|--------|
| 2 | Alice | 70000 |
π Managing Views
βοΈ Updating a View:
ALTER VIEW IT_Employees AS
SELECT EmployeeID, Name, Salary, Department
FROM Employees
WHERE Department = 'IT';
βοΈ Deleting a View:
DROP VIEW IT_Employees;
βοΈ Updating Data in a View:
- If the view is based on a single table, you can update data directly:
UPDATE IT_Employees
SET Salary = 75000
WHERE EmployeeID = 2;
- If the view is based on multiple tables, updating may not be allowed.
---
πΉ 2. What are Temporary Tables in SQL?
A Temporary Table is a table that exists only for the duration of a session. Once the session ends, the table is automatically deleted.
π Why Use Temporary Tables?
β Store Intermediate Data β Useful when working with complex calculations or large datasets.
β Improve Performance β Speeds up queries by reducing redundant computations.
β Prevents Changes to Main Tables β Temporary tables do not affect original data.
---
π Example: Creating a Temporary Table
A temporary table name starts with `#`.
CREATE TABLE #TempEmployees (
EmployeeID INT,
Name VARCHAR(50),
Salary DECIMAL(10,2)
);
Now, we insert some values:
INSERT INTO #TempEmployees (EmployeeID, Name, Salary)
VALUES (1, 'John', 50000),
(2, 'Alice', 70000);
β Fetching Data from Temporary Table
SELECT * FROM #TempEmployees;
Output:
| EmployeeID | Name | Salary |
|-----------|------|--------|
| 1 | John | 50000 |
| 2 | Alice | 70000 |
β Deleting a Temporary Table
DROP TABLE #TempEmployees;
π‘ Note: Temporary tables are deleted automatically once the session ends!
---
πΉ 3. What are Table Variables?
A Table Variable is a special type of variable in SQL that holds table-like data. Unlike temporary tables, table variables do not persist beyond the batch execution.
π Why Use Table Variables?
β Uses Less System Resources β Stored in memory, making operations faster.
β Does Not Require Explicit Deletion β Automatically removed after execution.
β Better for Small Datasets β Works best when dealing with a few rows of data.
---
π Example: Creating a Table Variable
DECLARE @EmpTable TABLE (
EmployeeID INT,
Name VARCHAR(50),
Salary DECIMAL(10,2)
);
β Inserting Data
INSERT INTO @EmpTable (EmployeeID, Name, Salary)
VALUES (1, 'John', 50000),
(2, 'Alice', 70000);
β Fetching Data from a Table Variable
SELECT * FROM @EmpTable;
Output:
π1
| EmployeeID | Name | Salary |
|-----------|------|--------|
| 1 | John | 50000 |
| 2 | Alice | 70000 |
π‘ Difference from Temporary Tables:
- Table Variables are limited to the batch they are declared in.
- Table Variables cannot be dropped, they disappear automatically.
---
π Summary: Views vs. Temporary Tables vs. Table Variables
| Feature | Views | Temporary Tables | Table Variables |
|----------------|-----------------|-----------------|----------------|
| Stores Data? | β (Virtual Table) | β Yes (Temporary) | β Yes (In Memory) |
| Persists? | β Yes (Until Dropped) | β No (Deleted when session ends) | β No (Deleted after batch ends) |
| Performance | πΉ Faster (No Data Stored) | πΉ Good for Large Data | πΉ Best for Small Data |
| Used For? | Read-Only Queries | Storing Intermediate Data | Storing Small Data Temporarily |
---
π When to Use These Features?
β Use VIEWS to simplify complex queries and improve security.
β Use TEMPORARY TABLES for storing large intermediate results.
β Use TABLE VARIABLES for storing small datasets within a session.
---
π Your Tasks for Today
β Create a VIEW and query it
β Experiment with TEMPORARY TABLES
β Practice using TABLE VARIABLES
Tomorrow, we will explore Stored Procedures and Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 19! π
|-----------|------|--------|
| 1 | John | 50000 |
| 2 | Alice | 70000 |
π‘ Difference from Temporary Tables:
- Table Variables are limited to the batch they are declared in.
- Table Variables cannot be dropped, they disappear automatically.
---
π Summary: Views vs. Temporary Tables vs. Table Variables
| Feature | Views | Temporary Tables | Table Variables |
|----------------|-----------------|-----------------|----------------|
| Stores Data? | β (Virtual Table) | β Yes (Temporary) | β Yes (In Memory) |
| Persists? | β Yes (Until Dropped) | β No (Deleted when session ends) | β No (Deleted after batch ends) |
| Performance | πΉ Faster (No Data Stored) | πΉ Good for Large Data | πΉ Best for Small Data |
| Used For? | Read-Only Queries | Storing Intermediate Data | Storing Small Data Temporarily |
---
π When to Use These Features?
β Use VIEWS to simplify complex queries and improve security.
β Use TEMPORARY TABLES for storing large intermediate results.
β Use TABLE VARIABLES for storing small datasets within a session.
---
π Your Tasks for Today
β Create a VIEW and query it
β Experiment with TEMPORARY TABLES
β Practice using TABLE VARIABLES
Tomorrow, we will explore Stored Procedures and Functions in SQL!
π Like β€οΈ and Share if you're excited for Day 19! π
π2
Hi, all
here's the tutorial in hindi, where you can learn data cleaning with python.
https://youtu.be/OkD5kGQdXJY
Let me know if you're liking this playlist and what you want me to add in this...!!
here's the tutorial in hindi, where you can learn data cleaning with python.
https://youtu.be/OkD5kGQdXJY
Let me know if you're liking this playlist and what you want me to add in this...!!
YouTube
Data Cleaning with Python: Handling Missing Values, Duplicates & More! | Codingdidi
Are you struggling with messy data? In this Python tutorial, weβll dive deep into data cleaningβone of the most powerful techniques for handlingdata efficiently! π
π What You'll Learn in This Video:
2:40 How to remove duplicate values
7:10 Learn to handlingβ¦
π What You'll Learn in This Video:
2:40 How to remove duplicate values
7:10 Learn to handlingβ¦
β€3