Learn how database indexes work, when to create them, and how to use SQLite's EXPLAIN QUERY PLAN to measure their impact. Optimize real queries step by step and understand the tradeoffs of indexing without over-trusting any single plan output.
An index is like the index in the back of a textbook. Without it, the database scans every row (reads the whole book). With it, the database jumps straight to the matching rows (looks up the page number). See this in action.
sqlite3 ecommerce.db "SELECT COUNT(*) FROM orders;"sqlite3 ecommerce.db "EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 5;"sqlite3 ecommerce.db ".indexes orders"EXPLAIN QUERY PLAN shows how SQLite plans to execute a query without actually running it. The output tells you whether the database will SCAN (read every row) or SEARCH (use an index to jump directly). Our schema already created some indexes, and `.indexes` shows them. The index idx_orders_customer on customer_id means looking up orders by customer is fast. Without that index, SQLite would have to read every order to find the ones belonging to customer 5.
First command shows the total number of orders. EXPLAIN QUERY PLAN shows 'SEARCH orders USING INDEX idx_orders_customer' — it's using the index, not scanning. The .indexes command lists all existing indexes on the orders table.