Node.js › Databases

What is database indexing, and how does an index improve query performance in a Node.js application's database layer?

Advanced

Answer

An index is a separate data structure (commonly a B-tree) that the database maintains alongside a table, allowing it to look up rows matching a specific column value without scanning every row in the table sequentially -- dramatically speeding up queries filtering or sorting on indexed columns, at the cost of additional storage space and slightly slower write performance, since every index must also be updated on every insert or update.
-- Without an index, this query scans the entire orders table
SELECT * FROM orders WHERE customer_id = 12345;

-- Creating an index dramatically speeds up that exact query pattern
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
Real-world example An orders table growing to millions of rows starts causing a 'get customer's orders' query to take several seconds; adding an index on the customer_id column reduces that same query to milliseconds by letting the database jump directly to matching rows instead of scanning the entire table.

Common follow-ups: How do you identify which columns actually need an index versus adding indexes speculatively everywhere?;What's the tradeoff of having too many indexes on a frequently-written-to table?