@Codingdidi
9.18K subscribers
26 photos
7 videos
47 files
260 links
Free learning Resources For Data Analysts, Data science, ML, AI, GEN AI and Job updates, career growth, Tech updates
Download Telegram
CREATE TABLE Orders (
ID INT PRIMARY KEY,
OrderDetails XML
);


Now, insert XML data:

INSERT INTO Orders (ID, OrderDetails)
VALUES (1, '<Order><Product>Laptop</Product><Price>1000</Price></Order>');


---

๐Ÿ”น Querying XML Data

To extract XML values, use the .value() function:

SELECT OrderDetails.value('(/Order/Product)[1]', 'NVARCHAR(50)') AS Product  
FROM Orders;


โœ”๏ธ Extracts the Product name from XML.

---

## ๐Ÿ”น Converting Table Data to JSON & XML

โœ… Convert Table to JSON

SELECT ID, Name FROM Customers  
FOR JSON AUTO;


โœ”๏ธ Converts table rows into JSON format.

---

โœ… Convert Table to XML

SELECT ID, Name FROM Customers  
FOR XML AUTO;


โœ”๏ธ Converts table rows into XML format.

---

๐Ÿ”น Summary of Today's Topics

| Concept | Key Takeaways |
|------------|-------------------|
| PIVOT | Converts rows into columns for summary reports. |
| UNPIVOT | Converts columns back into rows for data normalization. |
| JSON in SQL | Stores and queries structured data in JSON format. |
| XML in SQL | Stores and retrieves hierarchical data using XML. |

---

๐Ÿ”น Your Task for Today

โœ… Practice pivoting and unpivoting a sample dataset.
โœ… Store and query JSON data in a SQL table.
โœ… Store and query XML data in a SQL table.

---

๐Ÿ’ก Whatโ€™s Next?
Tomorrow, we will learn Stored Procedures, Functions, and Triggers in SQL. Stay tuned! ๐Ÿš€

๐Ÿ’ฌ Comment below if you have questions! Like โค๏ธ & Share if you're enjoying this SQL series! ๐Ÿ˜Š
Day 27: Writing Stored Procedures and Functions & Automating Processes with Triggers ๐Ÿš€

Welcome to Day 27 of your SQL journey! Today, we will learn:

โœ”๏ธ Stored Procedures โ€“ Predefined SQL code that can be executed multiple times.
โœ”๏ธ Functions โ€“ SQL code that returns a single value or table.
โœ”๏ธ Triggers โ€“ Automated actions that execute when a certain event occurs.

Letโ€™s break these down step by step! ๐Ÿ‘‡

---

๐Ÿ”น Part 1: Writing Stored Procedures

โœ… What is a Stored Procedure?

A Stored Procedure is a set of SQL statements stored in the database that can be executed whenever needed.

๐Ÿ”น Why Use Stored Procedures?
โœ”๏ธ Reusability โ€“ Write once, use multiple times.
โœ”๏ธ Security โ€“ Prevent SQL injection.
โœ”๏ธ Performance โ€“ Optimized query execution.

---

๐Ÿ”น Creating a Simple Stored Procedure

Letโ€™s create a stored procedure to retrieve all customers from a Customers table.

CREATE PROCEDURE GetAllCustomers  
AS
BEGIN
SELECT * FROM Customers;
END;


๐Ÿ”น How to Execute a Stored Procedure?

EXEC GetAllCustomers;


โœ”๏ธ The procedure fetches all customer records when executed.

---

๐Ÿ”น Stored Procedure with Parameters

Letโ€™s create a procedure to get customers from a specific country.

CREATE PROCEDURE GetCustomersByCountry  
@Country NVARCHAR(50)
AS
BEGIN
SELECT * FROM Customers WHERE Country = @Country;
END;

๐Ÿ”น Execute with a Parameter

EXEC GetCustomersByCountry 'USA';


โœ”๏ธ This retrieves all customers from the USA.

---

๐Ÿ”น Stored Procedure with Output Parameter

Stored procedures can return values using output parameters.

CREATE PROCEDURE GetTotalCustomers  
@Total INT OUTPUT
AS
BEGIN
SELECT @Total = COUNT(*) FROM Customers;
END;


๐Ÿ”น Execute and Get the Output

DECLARE @TotalCustomers INT;
EXEC GetTotalCustomers @TotalCustomers OUTPUT;
PRINT @TotalCustomers;


โœ”๏ธ This counts and prints the total number of customers.

---

๐Ÿ”น Part 2: Writing Functions in SQL

โœ… What is a Function?

A Function in SQL is a reusable block of code that returns a value.

๐Ÿ”น Types of Functions in SQL:
1๏ธโƒฃ Scalar Functions โ€“ Return a single value.
2๏ธโƒฃ Table-Valued Functions โ€“ Return a table.

---

๐Ÿ”น Creating a Scalar Function

Letโ€™s create a function that calculates the total price after tax for a given price.

CREATE FUNCTION CalculateTax(@Price DECIMAL(10,2))  
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Price * 1.10; -- Adding 10% tax
END;


๐Ÿ”น Using the Function

SELECT dbo.CalculateTax(100) AS PriceWithTax;


โœ”๏ธ If the input is 100, the output will be 110.

---

๐Ÿ”น Creating a Table-Valued Function

Letโ€™s create a function that returns customers from a given country.

CREATE FUNCTION GetCustomersFromCountry(@Country NVARCHAR(50))  
RETURNS TABLE
AS
RETURN
(
SELECT * FROM Customers WHERE Country = @Country
);


๐Ÿ”น Using the Function

SELECT * FROM dbo.GetCustomersFromCountry('USA');


โœ”๏ธ This retrieves all USA customers in a tabular format.

---

๐Ÿ”น Part 3: Automating Processes with Triggers

โœ… What is a Trigger?

A Trigger is a special type of stored procedure that executes automatically when a specific action occurs in the database.

๐Ÿ”น Why Use Triggers?
โœ”๏ธ Enforce Business Rules โ€“ Prevent invalid data entry.
โœ”๏ธ Maintain Audit Logs โ€“ Track changes automatically.
โœ”๏ธ Automate Actions โ€“ Example: Send a notification when a new record is inserted.

---

๐Ÿ”น Types of Triggers in SQL

1๏ธโƒฃ AFTER Triggers โ€“ Execute after an INSERT, UPDATE, or DELETE operation.
2๏ธโƒฃ INSTEAD OF Triggers โ€“ Replace an operation with custom logic.

---

๐Ÿ”น Creating an AFTER INSERT Trigger

Letโ€™s create a trigger that logs new customer entries in an audit table.

CREATE TABLE CustomerLog (
LogID INT IDENTITY PRIMARY KEY,
CustomerID INT,
ActionTaken NVARCHAR(50),
ActionDate DATETIME DEFAULT GETDATE()
);


Now, letโ€™s create the trigger:

CREATE TRIGGER trg_AfterCustomerInsert  
ON Customers
AFTER INSERT
AS
BEGIN
INSERT INTO CustomerLog (CustomerID, ActionTaken)
SELECT ID, 'Inserted' FROM INSERTED;
END;
๐Ÿ‘1
๐Ÿ”น How it Works?
โœ”๏ธ When a new customer is added, an entry is automatically made in CustomerLog.

---

๐Ÿ”น Creating an AFTER UPDATE Trigger

Letโ€™s create a trigger to track salary changes in an Employees table.

CREATE TRIGGER trg_AfterSalaryUpdate  
ON Employees
AFTER UPDATE
AS
BEGIN
IF UPDATE(Salary)
BEGIN
INSERT INTO SalaryAudit (EmployeeID, OldSalary, NewSalary, ChangeDate)
SELECT i.ID, d.Salary, i.Salary, GETDATE()
FROM INSERTED i
JOIN DELETED d ON i.ID = d.ID;
END
END;


โœ”๏ธ INSERTED Table โ€“ Holds new data after an update.
โœ”๏ธ DELETED Table โ€“ Holds old data before the update.

---

๐Ÿ”น Creating an INSTEAD OF DELETE Trigger

Letโ€™s prevent accidental deletion of employees by marking them as "Inactive" instead of deleting.

CREATE TRIGGER trg_InsteadOfDelete  
ON Employees
INSTEAD OF DELETE
AS
BEGIN
UPDATE Employees
SET IsActive = 0
WHERE ID IN (SELECT ID FROM DELETED);
END;


โœ”๏ธ Now, when someone tries to delete an employee, they are just marked as inactive instead.

---

๐Ÿ”น Summary of Todayโ€™s Topics

| Concept | Key Takeaways |
|------------|-------------------|
| Stored Procedures | Predefined SQL queries that execute on demand. |
| Functions | Return a single value (scalar) or table (table-valued). |
| Triggers | Execute automatically when an INSERT, UPDATE, or DELETE happens. |

---

๐Ÿ”น Your Task for Today

โœ… Create a stored procedure to get customer orders.
โœ… Write a function to calculate discounts.
โœ… Create a trigger to track changes in a table.

---

๐Ÿ’ก Whatโ€™s Next?
Tomorrow, we will explore Integrating SQL with Python, Power BI, and Tableau & SQL in Big Data (NoSQL). ๐Ÿš€

๐Ÿ’ฌ Comment below if you have questions! Like โค๏ธ & Share if you're enjoying this SQL series! ๐Ÿ˜Š
Day 28: Integrating SQL with Other Tools & SQL in Big Data (NoSQL) ๐Ÿš€

Welcome to Day 28 of your SQL journey! Today, we will cover:

โœ”๏ธ How SQL integrates with other tools like Python, Power BI, and Tableau.
โœ”๏ธ SQL in Big Data โ€“ Introduction to NoSQL databases.

Letโ€™s break everything down step by step! ๐Ÿ‘‡

---

๐Ÿ”น Part 1: Integrating SQL with Other Tools

SQL is often used in combination with other tools for data analysis, reporting, and visualization.

๐Ÿ”น Why Integrate SQL with Other Tools?
โœ”๏ธ Automate Data Extraction ๐Ÿ“ฅ
โœ”๏ธ Analyze Data in Python ๐Ÿ
โœ”๏ธ Visualize Data in Power BI & Tableau ๐Ÿ“Š

---

๐Ÿ”น SQL with Python

Python is widely used for data analysis, machine learning, and automation. To connect Python with SQL, we use libraries like:
โœ”๏ธ sqlite3 โ€“ For SQLite databases
โœ”๏ธ pyodbc โ€“ For MS SQL Server
โœ”๏ธ mysql-connector-python โ€“ For MySQL
โœ”๏ธ psycopg2 โ€“ For PostgreSQL

๐Ÿ”น Connecting Python to SQL (Example: MySQL)

1๏ธโƒฃ Install MySQL Connector
pip install mysql-connector-python


2๏ธโƒฃ Connect Python to MySQL Database
import mysql.connector  

# Connect to database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="company"
)

cursor = conn.cursor()

# Execute a query
cursor.execute("SELECT * FROM Employees")

# Fetch and display data
for row in cursor.fetchall():
print(row)

# Close the connection
conn.close()


โœ”๏ธ This connects Python to MySQL and fetches employee data.

---

๐Ÿ”น SQL with Power BI

Power BI is a powerful tool for data visualization and business intelligence.

### ๐Ÿ”น Steps to Connect SQL with Power BI
1๏ธโƒฃ Open Power BI
2๏ธโƒฃ Click on โ€œGet Dataโ€ โ†’ Select โ€œSQL Serverโ€
3๏ธโƒฃ Enter Server Name & Database Name
4๏ธโƒฃ Load the Data and start creating reports!

---

๐Ÿ”น SQL with Tableau

Tableau is another great tool for data visualization.

๐Ÿ”น Steps to Connect SQL with Tableau
1๏ธโƒฃ Open Tableau
2๏ธโƒฃ Click on โ€œConnectโ€ โ†’ Choose your SQL Database
3๏ธโƒฃ Enter Server Credentials & Connect
4๏ธโƒฃ Drag & Drop Tables to build interactive reports!

---

๐Ÿ”น Part 2: SQL in Big Data & Introduction to NoSQL

๐Ÿ”น What is Big Data?

Big Data refers to huge volumes of structured and unstructured data that traditional SQL databases cannot handle efficiently.

๐Ÿ”น SQL vs NoSQL

| Feature | SQL (Relational DB) | NoSQL (Non-Relational DB) |
|---------|------------------|----------------------|
| Data Structure | Tables (Rows & Columns) | Documents, Key-Value, Graphs, etc. |
| Schema | Fixed Schema | Flexible Schema |
| Scalability | Vertical Scaling | Horizontal Scaling |
| Transactions | Follows ACID | BASE (Eventual Consistency) |
| Example DBs | MySQL, PostgreSQL, SQL Server | MongoDB, Firebase, Cassandra |

---

๐Ÿ”น NoSQL Databases Overview

There are four types of NoSQL databases:

1๏ธโƒฃ Document Databases (MongoDB, CouchDB) โ€“ Store data as JSON-like documents.
2๏ธโƒฃ Key-Value Stores (Redis, DynamoDB) โ€“ Store data as key-value pairs.
3๏ธโƒฃ Column-Family Stores (Cassandra, HBase) โ€“ Store data in columns instead of rows.
4๏ธโƒฃ Graph Databases (Neo4j) โ€“ Store relationships between data nodes.

---

๐Ÿ”น SQL vs NoSQL: When to Use What?

โœ”๏ธ Use SQL when:
- Your data has a structured format.
- You need ACID transactions (Banking, ERP).

โœ”๏ธ Use NoSQL when:
- Your data is unstructured (JSON, images, logs).
- You need high-speed scaling (Social Media, IoT).

---

๐Ÿ”น Summary of Todayโ€™s Topics

| Concept | Key Takeaways |
|------------|-------------------|
| SQL with Python | Automates data analysis and machine learning. |
| SQL with Power BI & Tableau | Helps create business reports and dashboards. |
| NoSQL Databases | Handle Big Data and flexible schema structures. |
| SQL vs NoSQL | SQL is structured; NoSQL is flexible and scalable. |

---

๐Ÿ”น Your Task for Today

โœ… Connect SQL with Python & Fetch Data
โœ… Load SQL Data in Power BI or Tableau
โœ… Explore NoSQL by installing MongoDB & running basic queries

---
๐Ÿ‘1
๐Ÿ’ก Whatโ€™s Next?
Tomorrow, we will focus on Query Performance Tuning & SQL Optimization Techniques! ๐Ÿš€

๐Ÿ’ฌ Comment below if you have questions! Like โค๏ธ & Share if you're enjoying this SQL series! ๐Ÿ˜Š
Day 29: Query Performance Tuning โ€“ Optimize Your SQL Queries ๐Ÿš€

Welcome to Day 29 of your SQL journey! Today, weโ€™ll cover:

โœ”๏ธ How to optimize SQL queries for faster execution.
โœ”๏ธ Common performance tuning techniques to improve efficiency.
โœ”๏ธ Best practices for writing optimized SQL queries.

By the end of this lesson, youโ€™ll be able to write SQL queries that run faster and handle large datasets efficiently!

---

๐Ÿ”น Why is Query Performance Tuning Important?

When working with databases, slow queries can affect application performance. Optimizing queries helps:

โœ”๏ธ Reduce execution time โณ
โœ”๏ธ Handle large amounts of data efficiently ๐Ÿ“Š
โœ”๏ธ Improve database performance ๐Ÿš€

---

๐Ÿ”น 1. Use SELECT Only What You Need

โŒ Bad Query: Selecting All Columns
SELECT * FROM Employees;

โœ”๏ธ This fetches all columns from the table, even if you need only a few.

โœ… Optimized Query: Select Specific Columns
SELECT EmployeeID, Name, Salary FROM Employees;

โœ”๏ธ This improves performance by fetching only the required data.

---

๐Ÿ”น 2. Use Proper Indexing

Indexes speed up searches by allowing the database to locate data faster.

How to Create an Index?
CREATE INDEX idx_employee_name ON Employees(Name);

โœ”๏ธ This index speeds up queries filtering by Name.

Using Index in Query
SELECT * FROM Employees WHERE Name = 'John Doe';

โœ”๏ธ The database will use the index instead of scanning the entire table.

---

๐Ÿ”น 3. Avoid Using Functions on Indexed Columns

Using functions prevents indexes from working efficiently.

โŒ Bad Query: Function on Indexed Column
SELECT * FROM Employees WHERE LOWER(Name) = 'john doe';

โœ”๏ธ The database has to apply LOWER() on every row, making it slow.

โœ… Optimized Query: Avoid Functions on Indexed Column
SELECT * FROM Employees WHERE Name = 'John Doe';

โœ”๏ธ This allows the index to be used directly, improving speed.

---

๐Ÿ”น 4. Use Joins Efficiently

When joining tables, use INNER JOIN instead of CROSS JOIN if possible.

โŒ Bad Query: CROSS JOIN (Slow)
SELECT Orders.OrderID, Customers.CustomerName  
FROM Orders, Customers
WHERE Orders.CustomerID = Customers.CustomerID;

โœ”๏ธ CROSS JOIN generates all possible combinations, leading to performance issues.

โœ… Optimized Query: Use INNER JOIN
SELECT Orders.OrderID, Customers.CustomerName  
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

โœ”๏ธ INNER JOIN fetches only matching rows, reducing unnecessary computations.

---

๐Ÿ”น 5. Use EXISTS Instead of IN for Subqueries

When checking if a record exists in another table, EXISTS is usually faster than IN.

โŒ Bad Query: Using IN (Slow for Large Data)
SELECT * FROM Employees  
WHERE EmployeeID IN (SELECT EmployeeID FROM Salaries WHERE Salary > 50000);

โœ”๏ธ IN executes the subquery multiple times, making it slower.

โœ… Optimized Query: Using EXISTS
SELECT * FROM Employees  
WHERE EXISTS (SELECT 1 FROM Salaries WHERE Salaries.EmployeeID = Employees.EmployeeID AND Salary > 50000);

โœ”๏ธ EXISTS stops checking once a match is found, making it more efficient.

---

๐Ÿ”น 6. Optimize ORDER BY with Indexing

Sorting large datasets can be slow. Adding an index on the ORDER BY column improves performance.

Creating an Index on Sorted Column
CREATE INDEX idx_salary ON Employees(Salary);

Optimized Query
SELECT * FROM Employees ORDER BY Salary;

โœ”๏ธ The database uses the index instead of sorting all rows manually.

---

# ๐Ÿ”น 7. Limit Data Retrieval Using LIMIT or TOP

Fetching too much data slows down performance. Use LIMIT (MySQL, PostgreSQL) or TOP (SQL Server) to limit results.

Optimized Query: Fetch Only First 10 Records
SELECT * FROM Employees LIMIT 10; -- MySQL, PostgreSQL  
SELECT TOP 10 * FROM Employees; -- SQL Server

โœ”๏ธ This ensures only required rows are fetched, making queries faster.

---

๐Ÿ”น 8. Use Proper Data Types

Choosing the right data type saves storage and speeds up queries.
๐Ÿ‘2โค1
โŒ Bad Practice: Using Large Data Types
CREATE TABLE Users (  
UserID BIGINT,
Name VARCHAR(500),
Age INT
);

โœ”๏ธ VARCHAR(500) is too large for names.

โœ… Optimized Table: Use Smaller Data Types
CREATE TABLE Users (  
UserID INT,
Name VARCHAR(100),
Age TINYINT
);

โœ”๏ธ TINYINT (1 byte) instead of INT (4 bytes) for Age saves space.

---

๐Ÿ”น 9. Use Partitioning for Large Tables

Partitioning splits a large table into smaller parts for faster queries.
Example: Partitioning a Sales Table by Year
CREATE TABLE Sales (  
SaleID INT,
SaleDate DATE,
Amount DECIMAL(10,2)
) PARTITION BY RANGE (YEAR(SaleDate));

โœ”๏ธ This makes it faster to search for specific years.

---

๐Ÿ”น 10. Use Query Execution Plan for Optimization

EXPLAIN (MySQL, PostgreSQL) or EXECUTION PLAN (SQL Server) helps analyze how a query runs.

How to Use EXPLAIN?
EXPLAIN SELECT * FROM Employees WHERE Name = 'John Doe';

โœ”๏ธ It shows if indexes are used and where the query is slow.

---

๐Ÿ”น Summary of SQL Performance Tuning Techniques

| Technique | Benefit |
|--------------|------------|
| Select Only Needed Columns | Reduces memory usage |
| Use Indexing | Speeds up searches |
| Avoid Functions on Indexed Columns | Allows index usage |
| Optimize Joins | Reduces unnecessary computations |
| Use EXISTS Instead of IN | Faster subqueries |
| Optimize ORDER BY | Uses indexes for sorting |
| Use LIMIT/TOP | Fetches only required rows |
| Choose Proper Data Types | Saves storage space |
| Use Partitioning | Speeds up queries on large tables |
| Analyze Execution Plan | Finds slow queries |

---

๐Ÿ”น Your Task for Today

โœ… Optimize a slow query using indexing or LIMIT.
โœ… Use EXPLAIN to analyze your query performance.
โœ… Try EXISTS instead of IN for a subquery.

---

๐Ÿ’ก Whatโ€™s Next?
Tomorrow is the final day โ€“ Day 30: Final Review & SQL Projects! ๐Ÿš€

๐Ÿ’ฌ Comment below if you have questions! Like โค๏ธ & Share if this helped you! ๐Ÿ˜Š
๐Ÿ‘1
Day 30: Final Review & SQL Projects โ€“ Apply Your Knowledge! ๐Ÿš€

๐ŸŽ‰ Congratulations! You've reached the final day of your 30-day SQL journey. Today, weโ€™ll:

โœ… Review all key SQL concepts learned over the past 30 days.
โœ… Work on real-world SQL projects to apply your skills.
โœ… Solve case studies & challenges to test your knowledge.

By the end of this lesson, youโ€™ll be confident in writing SQL queries and solving real-world data problems!

---

๐Ÿ”น Quick Recap: Key SQL Concepts You Learned

| Topic | Key Learnings |
|-----------|------------------|
| Day 1-5: Basics | SQL syntax, SELECT, WHERE, ORDER BY, GROUP BY, HAVING, Aggregate Functions |
| Day 6-10: Joins & Subqueries | INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, Subqueries |
| Day 11-15: Advanced Queries | Common Table Expressions (CTEs), Window Functions, Case Statements |
| Day 16-20: Views, Transactions, Indexing | Creating Views, Indexing, Transactions & ACID properties, Error Handling |
| Day 21-25: Database Design & Security | Normalization (1NF, 2NF, 3NF, BCNF), Constraints, Backup & Restore, Role-Based Permissions |
| Day 26-29: Performance Optimization | Pivoting, JSON/XML in SQL, Stored Procedures, Triggers, Query Performance Tuning |

If youโ€™ve completed all the lessons, you now have a solid SQL foundation! ๐Ÿ†

---

๐Ÿ”น Real-World SQL Projects & Case Studies

Now, letโ€™s apply what youโ€™ve learned by working on SQL projects.

Project 1: Analyzing Sales Data ๐Ÿ“Š

Scenario: You work for an e-commerce company, and management wants to analyze sales performance.

Dataset: Sales Table
| SaleID | Date | CustomerID | ProductID | Quantity | Price | TotalAmount |
|--------|------|------------|------------|---------|------|------------|
| 101 | 2024-01-10 | 1 | 1001 | 2 | 500 | 1000 |
| 102 | 2024-01-11 | 2 | 1002 | 1 | 300 | 300 |
| 103 | 2024-01-12 | 1 | 1003 | 5 | 200 | 1000 |

Tasks:
โœ”๏ธ Find total sales per customer
SELECT CustomerID, SUM(TotalAmount) AS TotalSpent  
FROM Sales
GROUP BY CustomerID
ORDER BY TotalSpent DESC;

โœ”๏ธ Get the top 5 products by sales revenue
SELECT ProductID, SUM(TotalAmount) AS Revenue  
FROM Sales
GROUP BY ProductID
ORDER BY Revenue DESC
LIMIT 5;

โœ”๏ธ Find the total revenue for each month
SELECT DATE_FORMAT(Date, '%Y-%m') AS Month, SUM(TotalAmount) AS Revenue  
FROM Sales
GROUP BY Month
ORDER BY Month;

โœ”๏ธ Find customers who made purchases in January but not in February
SELECT DISTINCT CustomerID  
FROM Sales
WHERE DATE_FORMAT(Date, '%Y-%m') = '2024-01'
AND CustomerID NOT IN (
SELECT DISTINCT CustomerID FROM Sales
WHERE DATE_FORMAT(Date, '%Y-%m') = '2024-02'
);

๐ŸŽฏ Objective: Gain hands-on experience analyzing business sales data.

---

Project 2: Building a Reporting Dashboard ๐Ÿ“Š

๐Ÿ”น Tools: Use SQL with Power BI, Tableau, or Python (Pandas & Matplotlib)

โœ”๏ธ Step 1: Write SQL queries to extract data from your database.
โœ”๏ธ Step 2: Connect SQL with Power BI/Tableau to create reports.
โœ”๏ธ Step 3: Build visualizations (e.g., bar charts, trend lines, KPIs).

๐ŸŽฏ Objective: Convert raw data into actionable insights for decision-making.

---

Project 3: Employee Management System

Scenario: HR wants to track employee performance and salaries.

Dataset: Employees Table
| EmpID | Name | Department | Salary | JoinDate |
|--------|------|------------|--------|---------|
| 1 | Alice | IT | 80000 | 2021-05-10 |
| 2 | Bob | HR | 60000 | 2022-08-15 |
| 3 | Charlie | IT | 90000 | 2019-12-01 |

Tasks:
โœ”๏ธ Find average salary by department
SELECT Department, AVG(Salary) AS AvgSalary  
FROM Employees
GROUP BY Department;

โœ”๏ธ List employees who have been with the company for more than 3 years
SELECT Name, JoinDate  
FROM Employees
WHERE JoinDate <= DATE_SUB(CURDATE(), INTERVAL 3 YEAR);

โœ”๏ธ Create a stored procedure to update salaries based on department
DELIMITER //  
CREATE PROCEDURE UpdateSalaries()
BEGIN
UPDATE Employees SET Salary = Salary * 1.10 WHERE Department = 'IT';
END //
DELIMITER ;

๐ŸŽฏ Objective: Learn how to manage employee data using SQL.

---
๐Ÿ‘3
๐Ÿ”น Final Challenge: Solve an Advanced SQL Problem

Problem Statement:
You have a table with user transactions. Find the second highest transaction amount for each user.

Dataset: Transactions Table
| TransactionID | UserID | Amount |
|--------------|--------|--------|
| 1 | 101 | 500 |
| 2 | 101 | 700 |
| 3 | 102 | 900 |
| 4 | 101 | 800 |
| 5 | 102 | 1000 |

Solution Using Window Function
SELECT UserID, Amount  
FROM (
SELECT UserID, Amount,
RANK() OVER (PARTITION BY UserID ORDER BY Amount DESC) AS rnk
FROM Transactions
) Ranked
WHERE rnk = 2;

โœ”๏ธ This finds the second highest transaction for each user using RANK().

---

๐Ÿ”น Next Steps: What to Do After Completing This Course?

๐Ÿš€ 1. Keep Practicing SQL
- Use LeetCode (SQL section) for solving challenges.
- Try HackerRank SQL challenges to strengthen your skills.

๐Ÿ“‚ 2. Build More Projects
- Create a Portfolio Website showcasing your SQL projects.
- Work on real-world datasets (Kaggle, Google BigQuery).

๐ŸŽ“ 3. Learn Advanced Topics
- Data Warehousing (OLAP, Snowflake Schema)
- ETL (Extract, Transform, Load) Concepts
- NoSQL Databases (MongoDB, Firebase)

๐ŸŽฏ 4. Get Certified
- Microsoft SQL Server Certification
- Google Data Analytics Certificate
- IBM Data Science Professional Certificate

๐Ÿ’ผ 5. Apply for Jobs & Freelance Work
- Look for SQL-related job roles (Data Analyst, Data Engineer).
- Offer SQL consulting services on platforms like Upwork & Fiverr.

---

๐Ÿ”น Final Thoughts: Congratulations on Finishing 30 Days of SQL! ๐ŸŽ‰

๐Ÿ‘ Youโ€™ve mastered SQL fundamentals & real-world applications!
โœ”๏ธ You can now write complex queries, optimize performance, and analyze data.
โœ”๏ธ Youโ€™re ready to work with databases professionally!

๐Ÿ’ฌ Drop a comment if you completed this 30-day challenge!
๐Ÿ”ฅ Like & Share if this journey helped you!

๐Ÿš€ Next Stop: Data Science, Python, or MAchine LEarning? Whatโ€™s your next goal? Let me know! ๐Ÿ˜Š
๐Ÿ‘5โค3
Hello everyone!!
I hope this 30 day sql series helped you all.

Looking forward to your feedback for future series!! ๐Ÿ˜
โค19๐Ÿ‘6โœ1
SQL books wonโ€™t teach you this.

Natural Keys vs. Autoincrement IDs vs. Public IDs. (or maybe all together)


๐—ก๐—ฎ๐˜๐˜‚๐—ฟ๐—ฎ๐—น ๐—ž๐—ฒ๐˜†๐˜€

Natural keys carry intrinsic meaning because they are part of the domain.

They are directly related to the data, making them intuitive and easy to understand. Examples include email addresses or employee IDs.

The problem is that they are usually not good for performance, but they can also be a security risk if you expose them.


๐—”๐˜‚๐˜๐—ผ๐—ถ๐—ป๐—ฐ๐—ฟ๐—ฒ๐—บ๐—ฒ๐—ป๐˜ ๐—œ๐——๐˜€

Autoincrement IDs automatically generate unique integers to identify rows within a table.

They are often used as primary keys.

Simple integers are fast for the database to index and query. They provide optimal performance.

However, they are vulnerable to enumeration attacks since predicting the next or previous record is easy.


๐—ฃ๐˜‚๐—ฏ๐—น๐—ถ๐—ฐ ๐—œ๐——๐˜€ (๐—จ๐—จ๐—œ๐——๐˜€)

UUIDs (Universally Unique Identifiers) are 128-bit identifiers used to uniquely identify information without relying on a centralized authority.

They are difficult to guess, making them suitable for public exposure in APIs.

The problem is they are larger and more complex than integers. This can impact performance, particularly in indexing and storage.


๐—™๐—ถ๐—ป๐—ฑ๐—ถ๐—ป๐—ด ๐˜๐—ต๐—ฒ ๐—ฆ๐˜„๐—ฒ๐—ฒ๐˜ ๐—ฆ๐—ฝ๐—ผ๐˜: ๐—” ๐— ๐—ถ๐˜…๐—ฒ๐—ฑ ๐—”๐—ฝ๐—ฝ๐—ฟ๐—ผ๐—ฎ๐—ฐ๐—ต

Combining different types of keys can offer a balanced solution:

โ€ข InternalID: Used for internal operations and relationships between tables.

โ€ข PublicID: Used in API responses and endpoints to securely reference user records.

โ€ข Email (Natural Key): Used to ensure unique identification of users within the business logic.


The mixed approach keeps your system fast, secure, and easy to understand.
โค6๐Ÿ‘4
Are you done with watching ๐’๐๐‹ tutorials but don't know where to practice it?

Check out these top 11 online sources that provide practical exercises and challenges to help you master SQL:

1. SQL Zoo: https://sqlzoo.net/wiki/SQL_Tutorial

2. SQLBolt : https://sqlbolt.com/

3. SQLPad: https://sqlpad.io/

4. Mode: https://mode.com/

5. Strata Scratch: https://www.stratascratch.com/

6. LeetCode: https://leetcode.com/problemset/all/

7. HackerRank: https://www.hackerrank.com/domains/sql

8. W3 Schools: https://www.w3schools.com/sql/default.asp

9. SQL Roadmap: https://t.me/sqlspecialist/386

10. Learnsql: https://learnsql.com/?ref=analyst
โค9๐Ÿ‘3
Which SQL statement is used to insert new data in a database?
Anonymous Quiz
27%
Insert New
3%
Add Record
6%
Add New
64%
Insert Into
๐Ÿ‘3
This media is not supported in your browser
VIEW IN TELEGRAM
Hurry up and enroll within Navratri offer and get low prices! ๐Ÿซถ๐Ÿป๐Ÿ˜

WhatsApp at +91-9910986344
๐Ÿ‘2
Which of the following matches the definition given below: It is an artificial key that aims to uniquely identify each record.
Anonymous Quiz
61%
Primary Key
19%
Foreign Key
13%
Surrogate Key
8%
composite Key
Hey everyone!

It's my dad's birthday today! ๐ŸŽ‰๐ŸŽ‚

To celebrate, I'm offering a huge discount on my live python courseโ€”now just โ‚น3000!

But hurry, this offer is only valid for the next 24 hours! โณ

Grab your spot now! ๐Ÿš€


Ping me on WhatsApp at +91-9910986344
Before the offer ends ๐Ÿ˜๐Ÿฅณ
๐ŸŽ‰5๐Ÿ‘2
The most popular programming languages:

1. Python
2. TypeScript
3. JavaScript
4. C#
5. HTML
6. Rust
7. C++
8. C
9. Go
10. Lua
11. Kotlin
12. Java
13. Swift
14. Jupyter Notebook
15. Shell
16. CSS
17. GDScript
18. Solidity
19. Vue
20. PHP
21. Dart
22. Ruby
23. Objective-C
24. PowerShell
25. Scala

According to the Latest GitHub Repositories
๐Ÿ‘3โค1
SQL, or Structured Query Language, is a domain-specific language used to manage and manipulate relational databases.

A - Aggregate Functions: Functions like COUNT, SUM, AVG, MIN, and MAX used to perform operations on data in a database.

B - BETWEEN: A SQL operator used to filter results within a specific range.

C - CREATE TABLE: SQL statement for creating a new table in a database.

D - DELETE: SQL statement used to delete records from a table.

E - EXISTS: SQL operator used in a subquery to test if a specified condition exists.

F - FOREIGN KEY: A field in a database table that is a primary key in another table, establishing a link between the two tables.

G - GROUP BY: SQL clause used to group rows that have the same values in specified columns.

H - HAVING: SQL clause used in combination with GROUP BY to filter the results.

I - INNER JOIN: SQL clause used to combine rows from two or more tables based on a related column between them.

J - JOIN: Combines rows from two or more tables based on a related column.

K - KEY: A field or set of fields in a database table that uniquely identifies each record.

L - LIKE: SQL operator used in a WHERE clause to search for a specified pattern in a column.

M - MODIFY: SQL command used to modify an existing database table.

N - NULL: Represents missing or undefined data in a database.

O - ORDER BY: SQL clause used to sort the result set in ascending or descending order.

P - PRIMARY KEY: A field in a table that uniquely identifies each record in that table.

Q - QUERY: A request for data from a database using SQL.

R - ROLLBACK: SQL command used to undo transactions that have not been saved to the database.

S - SELECT: SQL statement used to query the database and retrieve data.

T - TRUNCATE: SQL command used to delete all records from a table without logging individual row deletions.

U - UPDATE: SQL statement used to modify the existing records in a table.

V - VIEW: A virtual table based on the result of a SELECT query.

W - WHERE: SQL clause used to filter the results of a query based on a specified condition.

X - (E)XISTS: Used in conjunction with SELECT to test the existence of rows returned by a subquery.

Z - ZERO: Represents the absence of a value in numeric fields or the initial state of boolean fields.

Here you can find essential Pyspark Resources๐Ÿ‘‡
https://www.instagram.com/codingdidi

Like this post if you need more ๐Ÿ‘โค๏ธ

Hope it helps :)
๐Ÿ‘7โค1