Showing posts with label EXPLAIN PLAN. Show all posts
Showing posts with label EXPLAIN PLAN. Show all posts

Hands-On SQL & MongoDB Indexing Tutorial | Query Optimization Exercise

๐Ÿงช Hands-On Exercise: Indexing and Query Optimization


๐ŸŽฏ Objective:

Understand the impact of indexes by comparing query performance with and without indexing in both SQL and MongoDB.


๐Ÿ”น Scenario:

You're working with a database of 10,000 students, and you need to search for a student by name.


A. SQL Exercise (MySQL or PostgreSQL)


๐Ÿ“Œ Step 1: Create and Populate the Table

CREATE TABLE Students (
  StudentID INT PRIMARY KEY,
  Name VARCHAR(100),
  Class VARCHAR(10),
  Email VARCHAR(100)
);

-- Insert sample data (loop or script to add 10,000+ rows for better realism)
-- Example:
INSERT INTO Students (StudentID, Name, Class, Email)
VALUES
(1, 'Aisha P', '10A', 'aisha@example.com'),
(2, 'Ravi Patel', '10B', 'ravi@example.com'),
-- Add thousands more...
(10000, 'Simran Joshi', '12B', 'simran@example.com');

๐Ÿ“Œ Step 2: Run Query Without Index

EXPLAIN ANALYZE
SELECT * FROM Students WHERE Name = 'Simran Joshi';

๐Ÿ“‹ Note: Record the execution time or rows examined.


๐Ÿ“Œ Step 3: Add an Index

CREATE INDEX idx_name ON Students(Name);

๐Ÿ“Œ Step 4: Run the Same Query Again

EXPLAIN ANALYZE
SELECT * FROM Students WHERE Name = 'Simran Joshi';

Compare performance: Look for reduced cost, fewer rows scanned, and faster time.



๐Ÿ” Example Output (PostgreSQL with Index):

Index Scan using idx_name on students  (cost=0.28..8.30 rows=1 width=52)
  Index Cond: (name = 'Simran Joshi')
Planning Time: 0.080 ms
Execution Time: 0.102 ms

๐Ÿ†š Compare this with the earlier output (without index), which might look like:

Seq Scan on students  (cost=0.00..194.00 rows=1 width=52)
  Filter: (name = 'Simran Joshi')
Planning Time: 0.095 ms
Execution Time: 5.223 ms


B. MongoDB Exercise


๐Ÿ“Œ Step 1: Insert Sample Data

for (let i = 1; i <= 10000; i++) {
  db.students.insertOne({
    student_id: i,
    name: `Student${i}`,
    class: `10${i % 5}`,
    email: `student${i}@example.com`
  });
}

// Insert the student to query:
db.students.insertOne({
  student_id: 10001,
  name: "Simran Joshi",
  class: "12B",
  email: "simran@example.com"
});

๐Ÿ“Œ Step 2: Run Query Without Index

db.students.find({ name: "Simran Joshi" }).explain("executionStats");

๐Ÿ“‹ Note the totalDocsExamined and executionTimeMillis.


๐Ÿ“Œ Step 3: Add an Index on Name

db.students.createIndex({ name: 1 });

๐Ÿ“Œ Step 4: Re-run the Query

db.students.find({ name: "Simran Joshi" }).explain("executionStats");

✅ You should see:

  • Lower totalDocsExamined

  • Faster executionTimeMillis

  • WinningPlan using IXSCAN instead of COLLSCAN



๐Ÿ” Example Output (MongoDB after indexing):

{
  "executionStats": {
    "executionTimeMillis": 1,
    "totalDocsExamined": 1,
    "nReturned": 1
  },
  "queryPlanner": {
    "winningPlan": {
      "stage": "IXSCAN"
    }
  }
}

๐Ÿ†š Before indexing, the output might show:

{
  "executionStats": {
    "executionTimeMillis": 15,
    "totalDocsExamined": 10001,
    "nReturned": 1
  },
  "queryPlanner": {
    "winningPlan": {
      "stage": "COLLSCAN"
    }
  }
}

๐Ÿง  Reflection Questions

  1. How did indexing affect query speed in SQL and MongoDB?

  2. What would happen if you indexed every column? Why is that a bad idea?

  3. Which type of queries benefit most from indexing?


๐Ÿ’ก Try online:


๐ŸŽ“ Now You Completed this lab? Great! You're ready to continue with :

  • Part 9: SQL Joins vs NoSQL Referencing


Featured Post

Hands-On SQL & MongoDB Transaction Practice Task

๐Ÿงช Practice Task: Managing a Simple Fund Transfer System Practical  hands-on practice task  for  transactions and consistency , designed fo...

Popular Posts