Lesson 1: SQL Basics
1.2 Installing MySQL / PostgreSQL
Learn how to install SQL server on your machine.
Explanation:-
No code, setup instructions vary by OS.1.3 Creating a Database
CREATE DATABASE makes a new database.
CREATE DATABASE school;
Explanation:-
Creates a database named school.1.4 Creating Tables
CREATE TABLE defines structure for storing data.
CREATE TABLE students (id INT, name VARCHAR(50));
Explanation:-
Creates table students with id and name columns.1.5 Inserting Data
INSERT INTO adds rows into a table.
INSERT INTO students VALUES (1, "Amit");
Explanation:-
Inserts a row with id=1 and name="Amit".1.6 Selecting Data
SELECT retrieves rows from a table.
SELECT * FROM students;
Explanation:-
Returns all rows and columns from students.1.7 Filtering Data with WHERE
WHERE filters records based on conditions.
SELECT * FROM students WHERE id=1;
Explanation:-
Returns rows where id=1.1.8 UPDATE Data
UPDATE modifies existing records.
UPDATE students SET name="Kapil" WHERE id=1;
Explanation:-
Changes name to Kapil where id=1.1.9 DELETE Data
DELETE removes records from a table.
DELETE FROM students WHERE id=1;
Explanation:-
Removes rows where id=1.1.10 ORDER BY Clause
Sort results in ascending or descending order.
SELECT * FROM students ORDER BY name ASC;
Explanation:-
Orders students by name alphabetically.1.11 LIMIT Clause
Restrict the number of rows returned.
SELECT * FROM students LIMIT 5;
Explanation:-
Returns only the first 5 rows.1.12 DISTINCT Keyword
Removes duplicates in results.
SELECT DISTINCT name FROM students;
Explanation:-
Returns unique student names.1.13 AND / OR Operators
Combine multiple conditions.
SELECT * FROM students WHERE id>1 AND name="Kapil";
Explanation:-
Returns rows where id>1 and name is Kapil.Lesson 2: Filtering & Sorting Data
2.14 IN Operator
Check if a value is in a set.
SELECT * FROM students WHERE id IN (1,2,3);
Explanation:-
Returns rows where id is 1,2,3.2.15 BETWEEN Operator
Select values within a range.
SELECT * FROM students WHERE id BETWEEN 1 AND 5;
Explanation:-
Returns rows with id from 1 to 5.2.16 LIKE Operator
Search for a pattern in a column.
SELECT * FROM students WHERE name LIKE "A%";
Explanation:-
Returns rows where name starts with "A".2.17 IS NULL / IS NOT NULL
Filter rows with NULL or non-NULL values.
SELECT * FROM students WHERE name IS NOT NULL;
Explanation:-
Returns rows where name is not NULL.2.18 Column Aliases
Rename columns in results.
SELECT name AS student_name FROM students;
Explanation:-
Displays name as student_name.2.19 Table Aliases
Rename tables in queries.
SELECT s.name FROM students AS s;
Explanation:-
s is an alias for students table.2.20 INNER JOIN
Return matching rows from two tables.
SELECT * FROM students s INNER JOIN marks m ON s.id=m.stu_id;
Explanation:-
Only rows where s.id = m.stu_id are returned.2.21 LEFT JOIN
Return all rows from left table, matching rows from right.
SELECT * FROM students s LEFT JOIN marks m ON s.id=m.stu_id;
Explanation:-
Includes all students even if they have no marks.2.22 RIGHT JOIN
Return all rows from right table, matching rows from left.
SELECT * FROM students s RIGHT JOIN marks m ON s.id=m.stu_id;
Explanation:-
Includes all marks even if no matching student.2.23 FULL OUTER JOIN
Return all rows with matching or non-matching.
SELECT * FROM students s FULL OUTER JOIN marks m ON s.id=m.stu_id;
Explanation:-
Includes all rows from both tables.2.24 CROSS JOIN
Cartesian product of two tables.
SELECT * FROM students CROSS JOIN marks;
Explanation:-
Every student combined with every mark row.2.25 SELF JOIN
Join a table to itself.
SELECT a.name, b.name FROM employees a, employees b WHERE a.manager_id=b.id;
Explanation:-
Used for hierarchy like manager-subordinate.2.26 GROUP BY Clause
Group rows by column(s).
SELECT stu_id, COUNT(*) FROM marks GROUP BY stu_id;
Explanation:-
Counts marks rows per student.2.27 HAVING Clause
Filter grouped results.
SELECT stu_id, AVG(marks) FROM marks GROUP BY stu_id HAVING AVG(marks)>50;
Explanation:-
Selects students with average marks >50.Lesson 3: SQL Functions and Operators
3.28 COUNT Function
Count rows or values.
SELECT COUNT(*) FROM students;
Explanation:-
Returns number of rows in students table.3.29 SUM Function
Sum of numeric column.
SELECT SUM(marks) FROM marks;
Explanation:-
Adds all marks.3.30 AVG Function
Average value of column.
SELECT AVG(marks) FROM marks;
Explanation:-
Returns average marks.3.31 MIN / MAX Functions
Smallest and largest values.
SELECT MIN(marks), MAX(marks) FROM marks;
Explanation:-
Returns min and max marks.3.32 String Functions
Manipulate text data.
SELECT CONCAT(name," Kumar") FROM students;
Explanation:-
Adds " Kumar" to each student name.3.33 SUBSTRING Function
Extract part of string.
SELECT SUBSTRING(name,1,3) FROM students;
Explanation:-
Returns first 3 characters of name.3.34 TRIM Function
Remove spaces.
SELECT TRIM(" Kapil ");
Explanation:-
Removes leading/trailing spaces.3.35 UPPER / LOWER Functions
Change text case.
SELECT UPPER(name), LOWER(name) FROM students;
Explanation:-
Converts names to uppercase or lowercase.3.36 REPLACE Function
Replace substring.
SELECT REPLACE(name,"Kapil","Amit") FROM students;
Explanation:-
Replaces Kapil with Amit.3.37 NOW() / CURDATE()
Current date/time functions.
SELECT NOW(), CURDATE();
Explanation:-
NOW() returns current datetime, CURDATE() current date.3.38 DATEDIFF Function
Days between dates.
SELECT DATEDIFF("2025-10-05","2025-10-01");
Explanation:-
Returns number of days between two dates.3.39 DATE_ADD / DATE_SUB
Add/subtract days to date.
SELECT DATE_ADD(CURDATE(), INTERVAL 5 DAY);
Explanation:-
Adds 5 days to today.3.40 CASE Statement
Conditional logic in SELECT.
SELECT name, CASE WHEN marks>50 THEN "Pass" ELSE "Fail" END FROM marks;
Explanation:-
Shows Pass/Fail based on marks.Lesson 4: Joins and Subqueries
4.41 UNION
Combine results from two SELECTs (unique).
SELECT name FROM students UNION SELECT name FROM teachers;
Explanation:-
Combines unique names from both tables.4.42 UNION ALL
Combine results including duplicates.
SELECT name FROM students UNION ALL SELECT name FROM teachers;
Explanation:-
Includes all names, duplicates allowed.4.43 EXISTS
Check if subquery returns any rows.
SELECT * FROM students s WHERE EXISTS (SELECT * FROM marks m WHERE m.stu_id=s.id);
Explanation:-
Returns students who have marks.4.44 NOT EXISTS
Check if subquery returns no rows.
SELECT * FROM students s WHERE NOT EXISTS (SELECT * FROM marks m WHERE m.stu_id=s.id);
Explanation:-
Students without marks.4.45 IN Subquery
Filter rows using subquery.
SELECT * FROM students WHERE id IN (SELECT stu_id FROM marks);
Explanation:-
Students who have marks.4.46 NOT IN Subquery
Exclude rows using subquery.
SELECT * FROM students WHERE id NOT IN (SELECT stu_id FROM marks);
Explanation:-
Students without marks.4.47 Nested Queries
Subquery inside SELECT/WHERE.
SELECT name FROM students WHERE id=(SELECT MAX(stu_id) FROM marks);
Explanation:-
Student with highest stu_id in marks.4.48 Indexes
Improve query performance.
CREATE INDEX idx_name ON students(name);
Explanation:-
Creates index on name column for faster search.4.49 Primary Key
Unique identifier for table rows.
ALTER TABLE students ADD PRIMARY KEY(id);
Explanation:-
id uniquely identifies each row.4.50 Foreign Key
Relational integrity between tables.
ALTER TABLE marks ADD FOREIGN KEY (stu_id) REFERENCES students(id);
Explanation:-
Marks.stu_id must match students.id.4.51 Unique Constraint
Ensure column values are unique.
ALTER TABLE students ADD UNIQUE(email);
Explanation:-
No two students can have the same email.4.52 NOT NULL Constraint
Prevent NULL values in a column.
ALTER TABLE students MODIFY name VARCHAR(50) NOT NULL;
Explanation:-
Name column cannot have NULL values.4.53 DEFAULT Values
Set default column value.
ALTER TABLE students ADD COLUMN status VARCHAR(10) DEFAULT "Active";
Explanation:-
If no value is given, status will be Active.Lesson 5: Constraints & Table Modifications
5.54 CHECK Constraint
Restrict values in a column.
ALTER TABLE students ADD CONSTRAINT chk_age CHECK (age>=18);
Explanation:-
Ensures age is 18 or older.5.55 TRUNCATE TABLE
Delete all rows quickly and reset auto_increment.
TRUNCATE TABLE students;
Explanation:-
Removes all rows from students table.5.56 DROP TABLE
Remove table completely.
DROP TABLE students;
Explanation:-
Deletes students table entirely.5.57 Renaming Table
Change table name.
ALTER TABLE students RENAME TO student_info;
Explanation:-
Renames table students to student_info.5.58 Renaming Column
Change column name.
ALTER TABLE students RENAME COLUMN name TO student_name;
Explanation:-
Renames column name to student_name.5.59 Adding Column
Add new column.
ALTER TABLE students ADD COLUMN dob DATE;
Explanation:-
Adds date of birth column.5.60 Dropping Column
Remove column.
ALTER TABLE students DROP COLUMN dob;
Explanation:-
Deletes dob column.5.61 Modifying Column
Change datatype or size.
ALTER TABLE students MODIFY COLUMN name VARCHAR(100);
Explanation:-
Changes column length to 100 characters.5.62 Transaction Basics
Use COMMIT and ROLLBACK to control transactions.
START TRANSACTION;
UPDATE students SET name="Kapil" WHERE id=1;
ROLLBACK;
Explanation:-
ROLLBACK undoes changes made in transaction.5.63 COMMIT
Permanently save transaction changes.
START TRANSACTION;
UPDATE students SET name="Kapil" WHERE id=1;
COMMIT;
Explanation:-
COMMIT saves changes to database.5.64 Savepoints
Partial rollback within transaction.
SAVEPOINT sp1;
UPDATE students SET name="Amit" WHERE id=1;
ROLLBACK TO sp1;
Explanation:-
Rolls back only to savepoint sp1.5.65 SET Operators
Combine query results: UNION, INTERSECT, MINUS.
Explanation:-
Used to combine or filter results from multiple queries.5.66 EXPLAIN
Check query execution plan.
EXPLAIN SELECT * FROM students;
Explanation:-
Shows how database executes query for optimization.Lesson 6: Transactions & Query Optimization
6.67 Aliases for Aggregates
Rename result of aggregation.
SELECT COUNT(*) AS total_students FROM students;
Explanation:-
Returns count of students with alias total_students.6.68 DISTINCT with Aggregates
Count unique values.
SELECT COUNT(DISTINCT name) FROM students;
Explanation:-
Counts unique student names.6.69 ? Multiclass Logistic Regression — One-vs-Rest (OvR) and One-vs-One (OvO)
Concept:
Logistic Regression is primarily used for binary classification. However, in real-world scenarios, we often need to classify data into more than two classes. For example, predicting the type of product purchased: Electronics, Clothing, or Grocery.
To handle multiple classes, two main strategies are used:
1️⃣ One-vs-Rest (OvR) — Also called One-vs-All. The model trains one classifier per class, treating that class as “1” and all others as “0.” The class with the highest probability wins.
2️⃣ One-vs-One (OvO) — This approach builds a classifier for every possible pair of classes. If there are 3 classes, it builds 3 classifiers (A vs B, B vs C, A vs C). The class that wins the most pairwise comparisons is predicted.
Let’s see this in action using a dataset with three categories: Electronics, Grocery, and Clothing.
Logistic Regression is primarily used for binary classification. However, in real-world scenarios, we often need to classify data into more than two classes. For example, predicting the type of product purchased: Electronics, Clothing, or Grocery.
To handle multiple classes, two main strategies are used:
1️⃣ One-vs-Rest (OvR) — Also called One-vs-All. The model trains one classifier per class, treating that class as “1” and all others as “0.” The class with the highest probability wins.
2️⃣ One-vs-One (OvO) — This approach builds a classifier for every possible pair of classes. If there are 3 classes, it builds 3 classifiers (A vs B, B vs C, A vs C). The class that wins the most pairwise comparisons is predicted.
Let’s see this in action using a dataset with three categories: Electronics, Grocery, and Clothing.
# Multiclass Logistic Regression Example
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix
# Load the dataset
df = pd.read_csv("multiclass_product_data.csv")
print(df.head())
# Encode categorical variables
df = pd.get_dummies(df, columns=["Product_Category", "Store_Size"], drop_first=True)
# Define features and target
X = df.drop("Target_Product_Type", axis=1)
y = df["Target_Product_Type"]
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Feature scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train One-vs-Rest Logistic Regression
ovr_model = LogisticRegression(multi_class="ovr", solver="liblinear")
ovr_model.fit(X_train_scaled, y_train)
y_pred_ovr = ovr_model.predict(X_test_scaled)
# Train One-vs-One Logistic Regression
ovo_model = LogisticRegression(multi_class="ovo", solver="liblinear")
ovo_model.fit(X_train_scaled, y_train)
y_pred_ovo = ovo_model.predict(X_test_scaled)
# Evaluate both models
print("One-vs-Rest Classification Report:")
print(classification_report(y_test, y_pred_ovr))
print("One-vs-One Classification Report:")
print(classification_report(y_test, y_pred_ovo))
# Confusion Matrix for OvR
cm_ovr = confusion_matrix(y_test, y_pred_ovr)
print("Confusion Matrix (OvR):")
print(cm_ovr)
Explanation:-
✅ Code Explanation: 1️⃣ We load the multiclass_product_data.csv dataset, which includes products from multiple categories.2️⃣ We perform one-hot encoding on categorical features like Product_Category and Store_Size.
3️⃣ The target variable Target_Product_Type contains three classes — Electronics, Grocery, and Clothing.
4️⃣ Two models are trained:
• OvR: One model per class.
• OvO: One model per pair of classes.
5️⃣ After prediction, both models are evaluated using classification_report and confusion_matrix.
6️⃣ You can compare precision, recall, and F1-score for each class to determine which strategy performs better.
? Conclusion:
For small datasets — OvO works well but may take more time.
For larger datasets — OvR is faster and typically sufficient for most business problems.
6.70 Subqueries in SELECT
Compute values with subquery.
SELECT name, (SELECT AVG(marks) FROM marks WHERE stu_id=students.id) AS avg_marks FROM students;
Explanation:-
Shows student with average marks.6.71 Correlated Subquery
Subquery depends on outer query.
SELECT name FROM students s WHERE EXISTS (SELECT * FROM marks m WHERE m.stu_id=s.id AND m.marks>50);
Explanation:-
Selects students with marks>50.6.72 SET Data Manipulation
Update multiple rows.
UPDATE students SET status="Inactive" WHERE id>5;
Explanation:-
Changes status for multiple students.6.73 CASE in UPDATE
Conditional updates.
UPDATE students SET status=CASE WHEN id=1 THEN "Active" ELSE "Inactive" END;
Explanation:-
Updates status based on id using CASE.6.74 LIMIT with DELETE
Delete limited rows.
DELETE FROM students ORDER BY id DESC LIMIT 1;
Explanation:-
Deletes only last row.6.75 LIMIT with UPDATE
Update limited rows.
UPDATE students SET status="Test" ORDER BY id ASC LIMIT 1;
Explanation:-
Updates only first row.6.76 Commenting Queries
Add single-line comment.
-- This is a comment
SELECT * FROM students;
Explanation:-
Comment does not affect query.6.77 Multi-line Comments
Add multi-line comment.
/* Comment 1
Comment 2 */
SELECT * FROM students;
Explanation:-
Multiple lines can be commented.6.78 Temporary Tables
Tables that exist temporarily.
CREATE TEMPORARY TABLE temp_students (id INT, name VARCHAR(50));
Explanation:-
Table exists only during session.6.79 IFNULL / COALESCE
Handle NULL values.
SELECT IFNULL(name,"No Name") FROM students;
Explanation:-
Replace NULL with default value.Lesson 7: Data Types & Normalization
7.80 CASE with Aggregates
Conditional aggregation.
SELECT COUNT(CASE WHEN marks>50 THEN 1 END) AS passed_students FROM marks;
Explanation:-
Counts students with marks>50.7.81 Data Types Overview
Common SQL data types.
Explanation:-
INT, VARCHAR, DATE, DECIMAL, TEXT, BLOB, etc.7.82 CHAR vs VARCHAR
Fixed vs variable length strings.
Explanation:-
CHAR stores fixed size, VARCHAR variable size.7.83 DECIMAL / NUMERIC
Store precise decimal values.
Explanation:-
DECIMAL(10,2) stores numbers with 2 decimal places.7.84 TEXT / BLOB
Store large text or binary.
Explanation:-
TEXT for long text, BLOB for binary files.7.85 Normalization Basics
Organize tables to reduce redundancy.
Explanation:-
Separate related data into different tables.7.86 1NF / 2NF / 3NF
Normal forms explained.
Explanation:-
Rules to avoid duplicate data and dependencies.7.87 Denormalization
Combine tables for performance.
Explanation:-
May duplicate data for faster queries.7.88 Stored Procedures
Reusable SQL code blocks.
CREATE PROCEDURE get_students() BEGIN SELECT * FROM students; END;
Explanation:-
Defines procedure to get all students.7.89 Calling Stored Procedure
Execute procedure.
CALL get_students();
Explanation:-
Runs procedure get_students.7.90 Stored Functions
Return value from function.
CREATE FUNCTION total_marks(stu INT) RETURNS INT BEGIN DECLARE t INT; SELECT SUM(marks) INTO t FROM marks WHERE stu_id=stu; RETURN t; END;
Explanation:-
Calculates total marks for a student.7.91 Triggers
Execute actions on table events.
CREATE TRIGGER before_insert_student BEFORE INSERT ON students FOR EACH ROW SET NEW.name=UPPER(NEW.name);
Explanation:-
Automatically converts inserted student names to uppercase.7.92 Views
Virtual table from query.
CREATE VIEW student_info AS SELECT s.name, m.marks FROM students s JOIN marks m ON s.id=m.stu_id;
Explanation:-
View shows student names with marks.Lesson 8: Stored Procedures, Triggers, and Views
8.93 Privileges / GRANT
Give permissions to users.
GRANT SELECT, INSERT ON school.* TO "user"@"localhost";
Explanation:-
Gives SELECT and INSERT privileges.8.94 REVOKE
Remove permissions.
REVOKE INSERT ON school.* FROM "user"@"localhost";
Explanation:-
Removes INSERT privilege from user.8.95 Backup using mysqldump
Export database to file.
mysqldump -u root -p school > school.sql
Explanation:-
Backup database data to SQL file.8.96 Restore from Backup
Import database from SQL file.
mysql -u root -p school < school.sql
Explanation:-
Restores database from backup file.8.97 Import CSV
Load CSV data into table.
LOAD DATA INFILE "students.csv" INTO TABLE students FIELDS TERMINATED BY "," LINES TERMINATED BY "\n";
Explanation:-
Imports CSV file into table.8.98 Export CSV
Save table data to CSV.
SELECT * FROM students INTO OUTFILE "students.csv" FIELDS TERMINATED BY "," LINES TERMINATED BY "\n";
Explanation:-
Exports table data to CSV file.8.99 Performance Tuning Basics
Optimize queries for faster execution.
EXPLAIN SELECT * FROM students;
Explanation:-
Analyze query plan and optimize indexes.8.100 Indexing Strategies
Use indexes to speed up queries.
CREATE INDEX idx_marks ON marks(marks);
Explanation:-
Speeds up searching marks column.8.101 Composite Index
Index on multiple columns.
CREATE INDEX idx_student_marks ON marks(stu_id, marks);
Explanation:-
Faster queries involving both columns.8.102 Clustered vs Non-Clustered Index
Explain index types.
Explanation:-
Clustered: table rows physically ordered. Non-clustered: separate structure.8.103 Full-Text Index
Search text efficiently.
CREATE FULLTEXT INDEX idx_name ON students(name);
Explanation:-
Allows fast text search in name column.8.104 Views with Joins
Combine multiple tables in view.
CREATE VIEW student_marks AS SELECT s.name, m.marks FROM students s JOIN marks m ON s.id=m.stu_id;
Explanation:-
View shows joined data.8.105 Updatable Views
Modify data through view.
Explanation:-
View must include key column and no aggregation for updates.Lesson 9: CTEs, Window Functions, and Analytics
9.106 CTE Basics
Common Table Expressions for readable queries.
WITH cte AS (SELECT * FROM students) SELECT * FROM cte;
Explanation:-
Temporary named result set used in query.9.107 Recursive CTE
CTE calling itself for hierarchy.
WITH RECURSIVE emp_hierarchy AS (SELECT * FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.* FROM employees e JOIN emp_hierarchy h ON e.manager_id=h.id) SELECT * FROM emp_hierarchy;
Explanation:-
Generates hierarchical employee tree.9.108 Window Functions
Perform calculations over partitions.
SELECT name, marks, RANK() OVER(PARTITION BY course_id ORDER BY marks DESC) AS rank FROM marks;
Explanation:-
Ranks students per course.9.109 ROW_NUMBER
Assign unique row numbers.
SELECT name, ROW_NUMBER() OVER(ORDER BY marks DESC) AS row_num FROM marks;
Explanation:-
Each row gets a sequential number.9.110 RANK
Assign rank with ties.
SELECT name, RANK() OVER(ORDER BY marks DESC) AS rank FROM marks;
Explanation:-
Rows with same marks get same rank.9.111 DENSE_RANK
Rank without gaps.
SELECT name, DENSE_RANK() OVER(ORDER BY marks DESC) AS drank FROM marks;
Explanation:-
Ranks consecutive without gaps.9.112 NTILE
Divide rows into buckets.
SELECT name, NTILE(4) OVER(ORDER BY marks DESC) AS quartile FROM marks;
Explanation:-
Divides students into 4 quartiles.9.113 LAG / LEAD
Access previous/next row values.
SELECT name, marks, LAG(marks) OVER(ORDER BY marks) AS prev_marks FROM marks;
Explanation:-
Shows previous row marks.9.114 FIRST_VALUE / LAST_VALUE
Get first/last value in window.
SELECT name, FIRST_VALUE(marks) OVER(ORDER BY marks) AS first_mark FROM marks;
Explanation:-
Returns first mark in ordered window.9.115 Advanced Subqueries
Use multiple levels of nested queries.
Explanation:-
Subqueries can appear in SELECT, FROM, WHERE clauses.9.116 Dynamic SQL
SQL constructed at runtime.
PREPARE stmt FROM "SELECT * FROM students WHERE id=?";
Explanation:-
Execute dynamic queries with parameters.9.117 Temporary Variables
Store intermediate values.
SET @total_marks = (SELECT SUM(marks) FROM marks);
Explanation:-
Use variables to hold query results.9.118 Stored Procedure Parameters
Pass input/output to procedures.
CREATE PROCEDURE get_marks(IN stu INT, OUT total INT) BEGIN SELECT SUM(marks) INTO total FROM marks WHERE stu_id=stu; END;
Explanation:-
Procedure takes input and returns output.Lesson 10: Advanced Query Techniques
10.119 Error Handling in Procedures
Handle exceptions.
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
Explanation:-
Rollback transaction on error.10.120 Triggers for Auditing
Automatically log changes.
CREATE TRIGGER log_update AFTER UPDATE ON students FOR EACH ROW INSERT INTO audit_table VALUES (OLD.name, NEW.name, NOW());
Explanation:-
Logs old and new values on update.10.121 Recursive Queries
Self-referencing queries.
Explanation:-
Useful for hierarchy, org charts, or bill of materials.10.122 Pivot Tables
Convert rows to columns.
Explanation:-
Use CASE or PIVOT function depending on DB.10.123 Unpivot
Convert columns to rows.
Explanation:-
Reverse of pivot.10.124 Advanced Joins with Multiple Tables
SELECT * FROM t1 JOIN t2 ON ... JOIN t3 ON ...;
Explanation:-
Combine many tables in one query.10.125 Conditional Aggregates
Aggregates with conditions.
SELECT SUM(CASE WHEN marks>50 THEN 1 ELSE 0 END) AS passed FROM marks;
Explanation:-
Counts students passing marks only.10.126 Ranking Analytics
Generate ranks with ties.
SELECT name, RANK() OVER(ORDER BY marks DESC) AS rnk FROM marks;
Explanation:-
Rank students by marks.10.127 Data Partitioning
Split data into partitions.
Explanation:-
Improves query performance on large datasets.10.128 Optimizing JOINs
Choose correct join type for performance.
Explanation:-
INNER JOIN faster than OUTER if possible.10.129 Query Execution Plan
Use EXPLAIN to analyze.
EXPLAIN SELECT * FROM marks WHERE marks>50;
Explanation:-
Helps optimize queries.10.130 Analyzing Index Usage
EXPLAIN SELECT ...;
Explanation:-
Check if indexes are being used.Lesson 11: Performance, Indexing & JSON
11.131 Bulk Insert
Insert many rows efficiently.
INSERT INTO students (id,name) VALUES (1,"Amit"),(2,"Kapil");
Explanation:-
Insert multiple rows at once.11.132 Batch Update
Update many rows in one query.
UPDATE students SET status="Active" WHERE id IN (1,2,3);
Explanation:-
Update multiple rows efficiently.11.133 DELETE with JOIN
Delete rows based on another table.
DELETE s FROM students s JOIN marks m ON s.id=m.stu_id WHERE m.marks<40;
Explanation:-
Delete students with failing marks.11.134 Advanced Date Functions
DATE_FORMAT, TIMESTAMPDIFF, etc.
SELECT DATE_FORMAT(CURDATE(),"%Y-%m-%d");
Explanation:-
Format date output.11.135 Regular Expressions
Pattern matching.
SELECT * FROM students WHERE name REGEXP "^[A-Z]";
Explanation:-
Names starting with uppercase letter.11.136 JSON Data Type
Store JSON in table.
CREATE TABLE t (id INT, data JSON);
Explanation:-
Allows structured JSON storage.11.137 JSON Functions
Extract data from JSON.
SELECT JSON_EXTRACT(data,"$.name") FROM t;
Explanation:-
Get name from JSON column.11.138 Window Aggregates
SUM, AVG over partitions.
SELECT SUM(marks) OVER(PARTITION BY course_id) AS total FROM marks;
Explanation:-
Total marks per course.11.139 CROSS APPLY / OUTER APPLY
Join table-valued functions.
Explanation:-
Database-specific advanced join technique.11.140 Materialized Views
Store precomputed views for speed.
Explanation:-
Faster than normal views for large datasets.11.141 Performance Hints
Optimize query execution.
Explanation:-
DB-specific hints like USE INDEX.Lesson 12: Database Management & Best Practices
12.142 Locking & Concurrency
Prevent data conflicts.
SELECT * FROM students FOR UPDATE;
Explanation:-
Locks selected rows for transaction.12.143 Isolation Levels
Control transaction behavior.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
Explanation:-
Prevents dirty reads, phantom reads.12.144 Deadlock Handling
Detect and handle deadlocks.
Explanation:-
DBMS handles automatically or via retry logic.12.145 Replication Basics
Copy data between servers.
Explanation:-
Used for backup or scaling read queries.12.146 Partitioned Tables
Split tables for large data.
Explanation:-
Improves performance and management.12.147 Sharding Overview
Horizontal partitioning across servers.
Explanation:-
Useful for huge datasets in distributed systems.12.148 Backup Strategies
Full, incremental, differential backups.
Explanation:-
Plan regular backups to avoid data loss.12.149 Data Import/Export Tools
MySQL Workbench, SQLLoader, etc.
Explanation:-
Graphical tools or commands for data transfer.12.150 SQL Best Practices
Coding standards, naming, indexing, performance tips.
Comments (1)
Login to comment
addkee: superb course for everyone