What Database Indexes Are and How They Speed Up Query Performance

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

← 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 →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

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.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A database index is a structure that organizes key values so the engine can locate matching rows without reading the whole table. Ordinary indexes are commonly B-trees: a root holds separator keys, branches narrow the key range, and sorted leaves hold entries that lead to the rows. Like the index of a book, it offers a route to a location. Indexes can serve equality tests, ranges, joins and ordering.
Why doesn't the database use my index?
The optimizer picks the plan it estimates is cheapest, and an index lookup is not always cheaper. When a query needs most of a table's rows, or the table is tiny, reading it directly can beat many separate lookups. Stale statistics or a very common value can steer the optimizer toward a scan, while a function wrapped around the column, such as YEAR(order_date), or a leading wildcard, such as LIKE '%book', can prevent an ordinary seek.
How do you read the type column in MySQL EXPLAIN?
The type column names the access method MySQL plans to use. const means at most one row found by comparing a primary or unique key with a constant; ref reads rows matching an indexed value; range reads a bounded interval of an index; index scans an entire index; and ALL scans the whole table. Check key for the chosen index and rows for the estimated number of rows examined.
How does an index stay fast as a table grows?
A B-tree stays shallow because each page branches to many children, so each extra level multiplies the number of reachable entries. In a rough illustration with 100-way branching, about two levels cover a thousand rows and about four cover ten million. Real depth depends on page size, key width and how full pages are, and each lookup still pays for matching entries and any row fetches.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Database Programming
3 credits · NCCRS
Enroll →