Junior — Middle
What is the role of indexes in a database and how do they help speed up query execution?
sobes.tech AI
Answer from AI
Indexes in a database are special data structures that speed up the search and retrieval of data from tables. They work like pointers or contents in a book, allowing you to quickly find the needed records without scanning all rows.
Role of indexes:
- Accelerate the execution of SELECT queries, especially with WHERE, JOIN, ORDER BY conditions.
- Help quickly find data by keys.
- Can improve the performance of sorting and grouping.
Example: if you have a user table with millions of records, an index on the email field will allow you to quickly find a user by email without scanning the entire table.
Example of creating an index in SQL:
CREATE INDEX idx_users_email ON users(email);
After that, the query
SELECT * FROM users WHERE email = 'example@mail.com';
will execute much faster.