Consider a Rails application with a users table having 1 million rows. You add an index on the email column. What is the expected effect on the following query?
SELECT * FROM users WHERE email = 'example@example.com';
Think about how indexes help databases find data.
Indexes allow the database to quickly find rows matching the condition without scanning the entire table, speeding up SELECT queries.
Which of the following is the correct way to add an index on the username column of the users table in a Rails migration?
Remember to use symbols for table and column names.
In Rails migrations, add_index :users, :username is the standard syntax. Parentheses are optional and unique: true adds a unique constraint if needed.
You have a products table with columns name (string) and description (text). You want to optimize search queries that look for keywords in the description. Which index type is best to improve full-text search performance?
Think about which index type supports searching words inside large text fields.
Full-text indexes are designed to speed up searches for words or phrases inside large text columns, unlike regular B-tree indexes which are better for exact matches.
You run this migration code:
add_index :orders, :customer_id, unique: true
But it fails with an error saying the index already exists. What is the most likely cause?
Check if the index already exists before adding it.
If an index on the same column already exists, trying to add another index with the same name or on the same column will cause an error.
You create a composite index on (category_id, price) columns in the products table. Which of the following queries will benefit from this index?
1. SELECT * FROM products WHERE category_id = 5;
2. SELECT * FROM products WHERE price = 100;
3. SELECT * FROM products WHERE category_id = 5 AND price = 100;
4. SELECT * FROM products WHERE price = 100 AND category_id = 5;
Think about how composite indexes work and the order of columns.
A composite index on (category_id, price) helps queries filtering by category_id alone or both category_id and price. Queries filtering only by price cannot use this index efficiently.