Logo hdtoledo
hdtoledo.dev
Módulos_del_Sistema
MÓDULO_TEÓRICO

Fast Search (Indexes)

Fast Search Indexes

Fast Search (Indexes)

Doña Pepa's business has been a resounding success. She no longer has 10 customers; she now has 1 million customers all over the city!

One day, she urgently needs to find the phone number for "Juan García". If she searches her table without help, the computer has to read row 1, 2, 3... until it reaches 999,999 where Juan is. In databases, this is called a "Full Table Scan". It's the equivalent of looking for a word in a 5,000-page book by reading every page from the beginning. It's extremely slow.


The Solution: The Book's Index

What do you do when you want to look for a chapter in a book? You go to the Index at the beginning or end, look at the word, and the index tells you: "Juan García is on page 999,999". You go straight there, skipping everything else.

SQL does exactly the same thing. We can create Indexes (INDEX) to tell the database to keep an ordered and secret list of a specific column.

sql
CREATE INDEX idx_customer_name ON Customers (name);

What just happened? By executing this command, the database creates a special structure in its memory (usually a B-Tree). Now, when Pepa makes this query:

sql
SELECT phone FROM Customers WHERE name = 'Juan García';

The search won't take 10 seconds anymore; it will take 0.001 seconds! The search laser went straight to the information.


The Index Trap (When YES and when NO)

You might think: "Great! I'll put indexes on ALL the columns of ALL the tables so everything is fast". Stop right there!

  • Why NOT do it? Because an index is literally an "extra file" that the database has to keep updated. If you put an index on the name column, every time you register a NEW customer, SQL will take a little longer because it has to save the customer and also update the index. If you have 50 indexes, inserting a single piece of data will be painfully slow.

  • When to say YES?

    1. On columns you use a lot for searching (e.g., WHERE email = ... or WHERE name = ...).
    2. Good news! Primary Keys (PRIMARY KEY) and Foreign Keys (FOREIGN KEY) almost always have indexes created automatically by the database engine so that JOINS are super fast.

Conclusion: Indexes are like steroids for your read queries, but extra weight for insertions. Use them wisely.

In the next lesson, we will see how to avoid Doña Pepa's worst nightmare: What happens if the power goes out right in the millisecond she was saving a sale? We will talk about Transactions (ACID).