Topic 12 – SQL Indexing and Optimization

image 2

Play Store Application link – SQL in 18 steps – App on Google Play

When working with databases, performance matters! Imagine a huge library where books are randomly placed on shelves—finding a book would take forever. Indexing in SQL is like organizing books alphabetically so you can find them quickly. Let’s explore how SQL indexing speeds up queries and optimizes database performance.


1. Types of Indexes

Indexes improve search speed by creating a structured path for queries. Different types of indexes serve different purposes.

B-Tree Index (Default Index)

  • Used in most databases (MySQL, Oracle, PostgreSQL, SQL Server).
  • Ideal for searching, sorting, and range-based queries (BETWEEN, >, <).
CREATE INDEX idx_employee_name ON employees(name);

Hash Index

  • Used for exact-match lookups (= operator) but not range searches.
  • Common in memory-based databases (e.g., MySQL’s MEMORY storage engine).
CREATE INDEX idx_employee_id ON employees(employee_id) USING HASH;

Full-Text Index

  • Used for searching text-heavy columns efficiently.
  • Supports natural language searches (MATCH ... AGAINST in MySQL, CONTAINS in SQL Server, TEXT indexing in PostgreSQL).
CREATE FULLTEXT INDEX idx_article_content ON articles(content);


2. Creating and Dropping Indexes

Indexes can be added or removed as needed.

Creating an Index

CREATE INDEX idx_customer_email ON customers(email);

Dropping an Index

DROP INDEX idx_customer_email ON customers;


3. Query Optimization Techniques

A slow query can affect application performance. Here’s how to optimize:

1. Use Indexes Wisely

  • Avoid indexing small tables; it may slow down inserts and updates.
  • Index frequently searched columns.

2. Avoid SELECT * (Use Specific Columns)

-- Bad Practice:
SELECT * FROM employees;

-- Optimized Query:
SELECT name, department FROM employees;

3. Use LIMIT for Large Data Queries

SELECT * FROM sales ORDER BY date DESC LIMIT 10;

4. Optimize Joins by Indexing Foreign Keys

CREATE INDEX idx_order_customer ON orders(customer_id);


4. Query Execution Plans: EXPLAIN vs EXPLAIN PLAN

Each database offers tools to analyze query execution.

MySQL: EXPLAIN

EXPLAIN SELECT * FROM orders WHERE customer_id = 101;

  • Shows how MySQL processes the query.
  • Helps identify missing indexes and inefficient joins.

Oracle: EXPLAIN PLAN

EXPLAIN PLAN FOR SELECT * FROM orders WHERE customer_id = 101;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

  • Similar to MySQL’s EXPLAIN but provides deeper insights.
  • Useful for tuning Oracle database queries.

Conclusion

Indexes make databases faster but should be used carefully. Too many indexes slow down INSERT and UPDATE operations. Understanding indexing types and using tools like EXPLAIN helps optimize queries and improve performance.

Leave a Reply

Your email address will not be published. Required fields are marked *