UPI Study › Courses › Database Programming › Free lessons › Lesson 9.6 Free with a free account
What Database Indexes Are and How They Speed Up Query Performance
Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.6 · lesson 54 of 7610 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Types of Indexes and the Trade-Offs Between Read Speed and Write Overhead →← Removing Views with SQL DROP ViewNext lesson: Types of Indexes and the Trade-Offs Between Read Speed and Write Overhead →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
How B-tree indexes and the optimizer choose between seeks and scans.
- Explain how a B-tree index locates rows through separator keys and sorted leaves
- Distinguish secondary, clustered and covering index lookups
- Explain why the optimizer may choose a table scan even when an index exists
- Read access methods in MySQL EXPLAIN and SQL Server execution plans
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,214 words). Read along, or search it.
Opening Problem
A Lookup That Slows as the Store Grows
Amina Diallo, Lantern Books' database administrator, sees a catalog lookup getting slower as the store grows. The requested book has not changed. Why should finding one row require reading every product? A reference book offers a clue: its index sends you toward a location, instead of making you read every page. A database index provides another route. When does that route save work?
Definition
Index Entries and Row Locators
An ordinary index organizes key values so the engine can locate matching entries. Those entries lead to the requested row information. In a secondary index, an entry includes a row locator. That locator might be a physical reference or a clustering key, depending on the engine and table. A clustered index is different: its leaf level holds stored row data. Do not assume every kind of index points to a completely separate table copy. Indexes serve equality conditions, ranges, joins, and ordering. Check the access structures already created for primary keys.
B-Tree Structure
Root, Separator Keys and Sorted Leaves
A B-tree starts at a root, which holds separator keys. This simplified tree uses product identifiers from our shared catalog, arranged for explanation. The leaves hold sorted entries. Identifiers below fourteen sit on the left, fourteen through sixteen in the middle, and seventeen onward on the right. The branches connect each key range to the appropriate leaf. Real trees can have additional internal branch levels, with many separator keys on each page. Balanced means equal leaf depth. Caching and row fetching still affect elapsed time.
Tree Search
Finding Product Sixteen
Search for product sixteen. Compare it with the root's separators: it belongs in the middle range, so the other two leaf ranges can be skipped. Within that leaf, find sixteen and use its locator to reach the row. A secondary lookup may require that additional table access. A covering index holds every requested column, potentially avoiding the extra row fetch.
Tree Depth
Why Trees Stay Shallow
The tree stays shallow because a page can divide the search among many children. A rough hundred-way branching illustration adds a level for each hundredfold increase. For a thousand rows, imagine about two levels; for a hundred thousand, about three. Ten million rows might need about four in that simplified model. These depths are illustrative. Page size, key width, and tree fill change the real structure. A scan's candidate work grows with the rows examined. A targeted tree search narrows the route, then still pays for matching entries and any required row fetches.
Scan Versus Seek
When Reading Broadly Can Win
A table scan examines rows broadly and tests the condition as it goes. An index lookup, often called a seek, navigates to matching key entries. A selective large-table lookup can avoid unrelated rows. Index use alone promises no particular speedup. When most rows are needed, sequential access can beat many separate lookups. A tiny table may be cheaper to read directly, even when an index exists. Indexes also consume storage and need maintenance when data changes. Inserts and deletes affect entries; updates affect indexes containing changed key or included values.
Query Optimizer
Statistics and Predicate Selectivity
The optimizer selects an execution plan: a set of operations for answering the query. It compares available alternatives using estimated costs and engine-specific search strategies. Statistics describe row counts and value distributions. Together with indexes and query conditions, they help estimate how much work each candidate access path would require. Here, predicate selectivity means the fraction of rows matched. A rare value may favor a lookup, while a common value may favor a scan. There is no universal cutoff. Changing data or stale statistics can change the plan.
MySQL EXPLAIN
Reading the Type, Key and Rows Fields
MySQL explain exposes the proposed access path. Its type field distinguishes common access methods, while key names the chosen index and rows estimates examined rows. Const means at most one row through a constant primary or unique-key lookup. Ref describes matching indexed values, and range describes a bounded interval. Index means scanning an index, while all means scanning the table. An index scan still visits entries broadly, so index use alone does not prove a targeted lookup. Extra supplies further notes. Interpret estimated rows alongside the query purpose.
SQL Server Plans
Seeks, Scans and Function-Wrapped Columns
SQL Server's estimated plan uses operators such as index seek, clustered index seek, table scan, and clustered index scan. Data commonly flows from right to left. Inspect the index name and estimated rows. Compare them with the workload. Wrapping a column in a function can prevent an ordinary matching seek. A leading-wildcard pattern often has the same problem; expression indexes or specialized search structures can change the options. A bare date range can fit an ordered date index better than extracting each row's year. Match the query to the structure, then inspect the plan again.
Sample Database
Loading the Shared Catalog
Our examples use Lantern Books, a fictional campus bookstore. This disposable database starts with the shared course data. Customers and products hold people and inventory. Prices and quantities are illustrative, and each lesson resets its own copy. Orders link to customers, while order items link orders to products. Foreign key checks are enabled for this connection. Save the setup file, then run it against a fresh shop database. Successful creation prints no rows here. Later commands reopen that database file. These examples use the real SQLite shell, and server dialect differences will be labeled.
Primary Key Lookup
Product Sixteen by Integer Key
The shared catalog gives the diagram a real lookup. Here we ask for the product whose identifier is sixteen, the same target used in the annotated tree. SQLite's integer primary key provides direct access to its row. Server storage details differ, while the purpose remains locating the requested key. A query plan describes that access method; a returned row describes the answer. Keep those two kinds of evidence separate when investigating performance. Run this lookup against shop. No separate index definition is needed for the integer primary key. Pen Set is returned with identifier sixteen. This real result establishes correctness, while a plan and representative workload would establish the access cost.
Quick Check
An Archival Report Reading Every Row
A fresh archival report needs every product with nonnegative stock. This table enforces nonnegative stock, and the report needs the whole matching set. What response makes sense for this report? Choose force lookups, accept the broad read, or delete matches. Pause, and decide. Accept the broad read. With a small table and all its rows matching, repeated index navigation may cost more than direct reading. The run counts eight matching rows. Deleting them changes the data, and forcing lookups does not establish a faster plan. Amina's original lookup asks for one row from a growing catalog. Its access needs differ from this report, which requests the entire set.
Range Check
Sixteen Included, Eighteen Excluded
A new range lookup starts at sixteen, includes that boundary, and stops before eighteen. The catalog still contains the eight shared product identifiers. How many keys match: two, one, or three? Pause, and predict. Two keys match, sixteen and seventeen. The lower boundary is included, while eighteen is excluded. The real count confirms two. A range can cross leaf boundaries in the conceptual tree; the index remains ordered across those leaves. One assumes a lookup can return only one key. Three forgets the strict upper boundary, which excludes eighteen.
Key Takeaways
An Index Is a Route, Not a Promise
An index offers a route through organized keys. Balanced trees narrow searches, while coverage and row fetching affect the remaining work. The optimizer chooses an access path using estimates. A scan can be appropriate, and an existing index can reasonably go unused. Read the plan in its own engine's vocabulary, then judge it against the question and changing data.
About Database Programming at UPI Study
Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About What Database Indexes Are and How They Speed Up Query Performance
What is a database index?
Why doesn't the database use my index?
How do you read the type column in MySQL EXPLAIN?
How does an index stay fast as a table grows?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Database Programming.
76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →