The order list in a dealer portal opened in under a second in the first months. As the data grew it went to three seconds, then ten, and buying a bigger server did not fix it. Most of the time the culprit is not the server but the database reading the entire table to find one record. Database indexing and query performance is the discipline of shrinking that read: the right index, the right query shape and a habit of measuring.
In this guide we explain how an index works, the difference between a full scan and an index lookup counted in pages, selectivity, column order in composite indexes, covering indexes, the N+1 query problem, the cost of pagination, what an index costs in writes and storage, how to find slow queries and read a query plan, and a six-step improvement path. All numbers are illustrative; they are not measurements of any particular database. Choosing the type of database is a separate subject: see our how to choose a database guide.
How Does an Index Work? The Book Index and the B-Tree
An index is a separate search structure, kept sorted by chosen columns, that tells you where a value lives, like the index at the back of a book. Without it you would read the whole book; in a database that is called a full table scan.
In most relational databases the structure is a B-tree: a root page at the top, intermediate pages below it and sorted leaf pages at the bottom. A search enters at the root and steps down one branch per level until it reaches a leaf, so the number of steps equals the number of levels. Illustrative assumption: 200 entries fit in one page.
- Three levels address 200 × 200 × 200 = 8,000,000 entries; 10,000,000 rows need four levels: 50,000 leaf pages, 250 intermediate pages, 2 intermediate pages and 1 root (10,000,000 ÷ 200 = 50,000; ÷ 200 = 250; ÷ 200 → 2).
- Even if the table grows 160 times to 1.6 billion rows, about 4 levels suffice (200⁴ = 1.6 billion), while a full scan grows linearly.
On a small table the difference is invisible; on millions of rows it is dramatic. For the broader question of load see our software scalability guide.
How Much Faster Is an Index Lookup Than a Full Table Scan?
The number of pages read for the same query can differ by hundreds of times. In our example the order-line table of a dealer portal has 10,000,000 rows; at 200 bytes per row and 8 KB per page, 40 rows fit in a page, so the table is 10,000,000 ÷ 40 = 250,000 pages (about 2 GB). On a disk reading 500 MB/s a full scan takes about 4 seconds.
The query: "open orders of dealer 118". With 500 dealers there are 20,000 rows per dealer on average; open lines are 2%, so 20,000 × 2% = 400 rows match.
| Method | Pages read | Calculation |
|---|---|---|
| Full table scan | 250,000 | The whole table |
| Index lookup by a single order number | 5 | 3 intermediate + 1 leaf + 1 table page |
| Index on the dealer column only | 20,103 | 3 + 100 leaves (20,000 ÷ 200) + 20,000 table rows |
| Composite index on dealer, status and date | 405 | 3 + 2 leaves (400 ÷ 200) + 400 table rows |
| Covering index | 7 | 3 + 4 leaves (400 ÷ 100); no table visit |
The gap between a full scan and the composite index is 250,000 ÷ 405 ≈ 617 times; with the covering index 250,000 ÷ 7 ≈ 35,714 times. A single-column index gains only 250,000 ÷ 20,103 ≈ 12.4 times: the real gain comes from matching the column combination to the query.
What Is Selectivity and When Does an Index Not Help?
Selectivity is how small a slice of the table a search value picks out. When many rows match, the database abandons the index and reads the table end to end, because with an index each row is a random access to a separate table page.
Assume a random read costs 4 times a sequential read (illustrative). Index cost is roughly matching rows × 4; a scan costs 250,000 sequential pages. Break-even: 250,000 ÷ 4 = 62,500 rows, or 0.625% of the table.
| Condition | Matching rows | Index cost (approx.) | Full scan | Cheaper |
|---|---|---|---|---|
| Order number = one value | 1 | 8 | 250,000 | Index |
| Dealer = 118 | 20,000 (0.2%) | 80,100 | 250,000 | Index (3.1×) |
| Dealer = 118 and status = open | 400 (0.004%) | 1,605 | 250,000 | Index (156×) |
| Status = open (all dealers) | 200,000 (2%) | 801,000 | 250,000 | Scan (3.2×) |
The five-valued "status" column is therefore a weak candidate on its own, but becomes strong when combined with a many-valued column such as dealer. Distribution matters too: for a large dealer holding 4% of the table (400,000 rows) the index loses, since 400,000 × 4 = 1,600,000 > 250,000.
How Do You Choose Column Order in a Composite Index?
A composite index sorts several columns left to right and only helps searches that start with its leftmost columns. The rule: columns searched by equality come first, then the range or sort column.
An index ordered (dealer, status, date) serves: dealer only; dealer and status; dealer + status + date range (the sort order also comes from the index). It helps partly for dealer and date without status, because every status value must be walked. It does not help for status alone or date alone.
The effect of order: the data spans 1,095 days (3 years) spread evenly, and the query is "open orders of dealer 118 in the last 30 days". With the order (date, dealer, status) the index walks all entries of the last 30 days: 10,000,000 × 30 ÷ 1,095 ≈ 273,973 entries, about 1,370 pages at 200 entries per leaf. With (dealer, status, date) the matching entries are 400 × 30 ÷ 1,095 ≈ 11 and it finishes in about 5 pages: roughly a 274-fold difference.
What Is a Covering Index?
A covering index carries every column the query needs, so the database answers from the leaf page and never visits the table. In the example above, if dealer, status, date and amount are all in the index, the 400-row answer comes in 7 pages instead of 405.
The cost: as entries grow, fewer fit in a page (100 instead of 200). Reserve covering indexes for critical, very frequent queries.
What Is the N+1 Query Problem?
N+1 means fetching a list with one query and then running a separate query for every row. Each query is fast, so it goes unnoticed in logs; the problem is the number of queries.
A page shows 50 orders and fetches each order's dealer name and lines separately: 1 + 50 + 50 = 101 queries. At 3 ms per query the page waits 101 × 3 = 303 ms. With batched fetching three queries suffice (orders, their dealers, their lines); at 5 ms each that is 15 ms: 303 ÷ 15 ≈ 20 times faster.
The load drops too: at 20 page views per second, 20 × 101 = 2,020 queries/s becomes 20 × 3 = 60 queries/s (33.7 times fewer). The symptom is page time growing with list length.
Why Does Pagination Slow Down on Deeper Pages?
Offset-based pagination ("skip this many rows, give me the next 50") slows down as pages get deeper because the database also counts the skipped rows. Keyset pagination ("give me the next 50 after the last date and number I saw") goes straight to that position.
On page 2,000, 99,950 rows are skipped and 50 returned: about 100,000 entries ÷ 200 = 500 leaf pages + 3 intermediate pages ≈ 503 pages. Keyset reaches the position in 3 intermediate + 1 leaf = 4 pages, about 126 times less. On page 1 the two are the same; offset cost grows linearly with the page number.
Keyset needs a unique sort column (add the number to the date); its price is that you cannot jump to a random page.
What Do Indexes Cost in Writes and Storage?
Every index is updated on every row written, so more indexes mean slower inserts, updates and deletes and more disk.
The example table has 5 indexes including the primary key (32 bytes per entry; composite 40, covering 80):
| Index | Entry size | Size (10 million rows) | Use (90 days) |
|---|---|---|---|
| Primary key | 32 bytes | 320 MB | Constant |
| Dealer, status, date (composite) | 40 bytes | 400 MB | 1,200,000 times |
| Dealer, status, date, amount (covering) | 80 bytes | 800 MB | 340,000 times |
| Old index A | 32 bytes | 320 MB | 0 |
| Old index B | 32 bytes | 320 MB | 0 |
| Total | 2,160 MB |
The total is 320 + 400 + 800 + 320 + 320 = 2,160 MB, 108% of the table itself (2,000 MB). Each insert performs table + 5 indexes = 6 writes; at 9,000 rows a day that is 9,000 × 6 = 54,000 writes. With only the table and the primary key it would be 9,000 × 2 = 18,000: five indexes triple the write work. Backups grow too: see our guide to backing up business data.
How Do You Find a Slow Query and Read a Query Plan?
Improvement starts with measurement, not guesses: a slow query log records queries above a threshold (say 200 ms) with their durations. The slowest single query is often not the most important; total time is query count × average time.
| Query | Daily count | Average | Total time | Share |
|---|---|---|---|---|
| Q1: Dealer name in order list (N+1) | 1,200,000 | 3 ms | 3,600 s | 34.3% |
| Q2: Dealer's open orders (dealer index only) | 25,000 | 180 ms | 4,500 s | 42.9% |
| Q3: Management summary report | 30 | 40,000 ms | 1,200 s | 11.4% |
| Q4: Lookup by order number | 600,000 | 2 ms | 1,200 s | 11.4% |
| Total | 10,500 s (2.9 h) | 100% |
The slowest single query is Q3 (40 s) but it is only 11.4% of total time; the gains are in Q2 and Q1. In the plan of the query you chose (conceptual reading):
- Access type: is the whole table scanned, or an index used?
- Estimated vs actual rows: an estimate of 400 against 20,000 actual (a 50-fold gap) means stale statistics.
- Sort step and discarded rows: if the result is sorted separately or most rows read are then discarded, the index column order does not fit the query.
Query logs can contain personal data as parameters; consult your legal counsel on KVKK (Turkey's personal data protection law) details. For continuous observation see our software monitoring guide.
How Do You Clean Up Unused Indexes?
An index with a zero usage counter only produces cost. In the table above, old indexes A and B were never used in 90 days; removing them frees 320 + 320 = 640 MB (29.6% of 2,160 MB) and cuts writes per insert from 6 to 4: 9,000 × 4 = 36,000, a 33.3% reduction from 54,000.
The observation window must cover the business cycle: an index used by a month-end report can look unused in 90 days. An index that enforces uniqueness is never dropped. Remove first in a test environment and compare plans.
When Should a Cache Step In?
A cache stores a computed result for a short time; it suits answers that repeat often and change rarely. It does not replace an index: on a miss the slow query runs.
Example: a dashboard summary is requested 600 times a minute and each computation takes 800 ms. With a 60-second cache one computation runs per minute and 599 requests are served from the cache: 599 ÷ 600 ≈ 99.8% hit rate. The price is data that can be 60 seconds stale; stock availability, which must be correct at order time, is not suitable. To move heavy work out of the order flow see our message queue guide.
How Do You Improve Query Performance in Six Steps?
The sequence below reduces guesswork and makes each change measurable.
- Measure: Collect the slow query log at real volume across one business cycle.
- Rank: Sort by count × time and pick the top three.
- Read the plan: Look for scans, estimate gaps, sorts and N+1 signs.
- Fix: An index, batched fetching, keyset pagination or a rewrite; one change at a time.
- Verify: Measure before and after on the same data, including write and storage impact.
- Clean up: Review unused indexes every quarter.
In the example, the composite index cuts the pages read for Q2 from 20,103 to 405; if time is proportional to pages, 180 ms × 405 ÷ 20,103 ≈ 3.6 ms. Once the N+1 in Q1 becomes one batched query per page, it is 1,200,000 ÷ 50 = 24,000 pages × 5 ms = 120 s a day. For Q2, 25,000 × 3.6 ms = 90 s. New total: 120 + 90 + 1,200 + 1,200 = 2,610 s. That is a 75.1% reduction from 10,500 s (7,890 ÷ 10,500), and the database's daily busy time falls from 2.9 hours to about 43.5 minutes. To test under load see our performance testing guide.
What Are Common Mistakes in Indexing and Query Tuning?
- Indexing every column: Write load and storage grow and most indexes go unused.
- Testing with small data: At 10,000 rows even an unindexed query is fast; a fix not tried at real volume is unproven.
- Applying a function to the column: Wrapping the column in a function in the condition often disables the index; apply the operation to the constant instead.
- Leaving statistics stale and using a cache instead of an index: One makes the planner choose badly, the other brings the slow query back on a miss.
We recommend reading: What is a data warehouse?
We recommend reading: What is custom software?
We recommend reading: How to Improve Ecommerce Site Search: Zero Results, Turkish Characters, Scoring and Payback Guide
We recommend reading: What Is Caching? Layers, TTL, Invalidation, Cache Stampede and Payback Guide
We recommend reading: How to Improve Website Speed: Page Weight Budget, Images, Scripts and Core Web Vitals Guide
We recommend reading: How to Set Up a Data Archiving and Retention Policy: Data Tiers, the Archive Rule, Legal Hold and Deletion Guide
We recommend reading: How to Design a REST API: Resource Naming, Pagination, Error Format and Idempotency Guide
Setting Performance Expectations in Custom Software with İnovabil
At İnovabil our focus is building bespoke software from scratch: custom software, ERP, CRM, e-commerce, web, mobile and integration. Data volume shapes how a system behaves not on day one but a few years later, so we recommend writing down the expected record counts, the most frequent queries and the acceptable response time during requirements analysis, and trying the system with data close to real volume.
We built CRM, purchasing and mobile for Avcılar İnşaat; a purchasing system for İZBAN; logistics and shipment planning with wholesale order management for Karyak; warehouse management and a complaint and support management system for Sleepy; and a prepaid cargo system for Kredili Kargo. Send us a short summary of your data expectations and we will draw up a measurement plan together.
We recommend reading: Our software development process
Frequently Asked Questions
What is database indexing and what is it for?
An index is a separate search structure kept sorted by chosen columns. It finds the record without reading the whole table; in the example it turns a 250,000-page scan into a 5-page lookup. Its price is being updated on every write and taking disk space.
Is it good to add an index on every column?
No. Every index slows writes and grows storage. In the example 5 indexes raise write work from 18,000 to 54,000; removing the unused ones brings it to 36,000.
Why does column order matter in a composite index?
A composite index only helps searches that start with its leftmost columns. Equality columns come first, the range or sort column last. In the example the same three columns read about 1,370 pages in the wrong order and about 5 in the right one.
What is the N+1 query problem and how do you spot it?
It means fetching a list and then running a separate query per row. The symptom is page time growing with list length. In the example 101 queries drop to 3 with batched fetching.
Where should you start to find a slow query?
Turn on the slow query log, rank queries by count × time and read the plans of the top three. Measure again on the same data after each change.