Have you used indexing to optimize database queries?
sobes.tech AI
Answer from AI
Yes, indexing is one of the main ways to optimize queries in databases. Indexes significantly speed up searching and data retrieval based on specific columns, reducing the number of records that need to be scanned.
For example, if you have a users table with an email field, and you often search for users by email, creating an index on this field will allow the database to quickly find the necessary records without scanning the entire table.
In Node.js, when working with databases (such as MongoDB, PostgreSQL), indexes are created through the respective commands or driver methods:
// Example for MongoDB
await collection.createIndex({ email: 1 });
// Example for PostgreSQL
await client.query('CREATE INDEX idx_email ON users(email);');
Using indexes helps improve the performance of SELECT queries, but keep in mind that they can slow down insert and update operations, so indexes should be created thoughtfully based on usage scenarios.