Imagine you have a huge phone book and you want to find a person's phone number. Which method is faster?
- Looking at every name one by one.
- Using the alphabetical index to jump directly to the name.
How does this relate to database indexes?
Think about how you find a word in a dictionary quickly.
Indexes work like a book's index. They help the database find rows quickly by pointing to where the data is stored, avoiding a full scan.
Given a table users(id INT, name VARCHAR(100)) with 1 million rows, which query will run faster?
SELECT * FROM users WHERE name = 'Alice';
Assuming there is an index on name, which option is true about the query speed?
Indexes help find matching rows quickly.
With an index on name, the database can quickly locate rows where name = 'Alice' without scanning all rows.
Which SQL statement correctly creates an index on the email column of the customers table?
Remember the order: CREATE INDEX <index_name> ON <table>(<column>);
The correct syntax is CREATE INDEX index_name ON table_name(column_name); to create an index.
You have a table orders(order_id, customer_id, order_date). You often run this query:
SELECT * FROM orders WHERE customer_id = 123 AND order_date = '2024-01-01';
Which index will speed up this query the most?
Think about which columns appear together in the WHERE clause.
A composite index on both customer_id and order_date lets the database filter rows using both conditions efficiently.
Given a table products(id, name, price) with an index on price, why does this query not use the index?
SELECT * FROM products WHERE price + 10 > 100;
Indexes work best when the column is used directly in conditions.
Using an expression like price + 10 prevents the database from using the index on price because it cannot quickly look up values after modification.