UPI Study › Courses › Database Programming › Free lessons › Lesson 9.7 Free with a free account
Types of Indexes and the Trade-Offs Between Read Speed and Write Overhead
Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.7 · lesson 55 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: Creating Indexes in SQL: Steps and Examples →← What Database Indexes Are and How They Speed Up Query PerformanceNext lesson: Creating Indexes in SQL: Steps and Examples →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Weigh clustered, unique, composite and full-text indexes against write costs.
- Compare clustered and nonclustered indexes in SQL Server and InnoDB
- Explain how unique, composite and covering indexes serve different queries
- Distinguish full-text indexes from ordinary indexes and LIKE searches
- Weigh index read benefits against storage and write maintenance costs
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,270 words). Read along, or search it.
Opening Problem
Should Every Column Be Indexed
Leo Park, Lantern Books' developer, suggests indexing every column. Amina Diallo, the database administrator, asks which reads improve and which writes become more expensive. An index has a purpose and a cost. How do they choose a small useful set, rather than collecting structures that no important query needs? We will distinguish storage organization, uniqueness, column ordering, query coverage, and word search.
Sample Database
Fresh Shop Data for Index Tests
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.
Storage Organization
Clustered, Nonclustered and Heap Tables
A clustered index holds row data at its leaf level, with one clustering order per table. A nonclustered index is a separate structure with row locators. SQL Server permits a heap with no clustered index. Its primary key is clustered by default when a suitable clustered structure does not already exist. InnoDB always chooses a clustered key: the primary key, an eligible unique non-null key, or a hidden generated identifier if neither is available. These server definitions are non-run listings. SQLite's rowid tables use their own storage model, so we do not call a separate SQLite index clustered. Secondary entries carry locator information. A short clustering key reduces repeated key storage, but clustering still has internal pages and maintenance costs.
Unique Index
Enforcing Distinct Product Names
A unique index both supports lookups and enforces distinct keys. This catalog index prevents two products from sharing the same non-null product name. That is a business rule we are choosing for the sandbox. Real catalogs may need repeated display names, so uniqueness belongs on the key the application actually guarantees. A duplicate insert or update would be rejected, and building this index would fail if existing non-null names already duplicated each other. Run the definition and lookup. The query does not name the index; the optimizer decides whether to use the available structure. Notebook is found. For optional unique values, SQLite and MySQL allow multiple nulls; a normal single-column SQL Server unique index permits only one.
Composite Index
Customer First, Then Order Date
A composite index has multiple key columns in a fixed order. Here entries sort by customer identifier, then by date within each customer's entries. That ordering makes a leading customer lookup natural. Adding a date equality or range can narrow the matching customer block further. The order of conditions in where does not set the index order. A date-only search generally lacks that leading block, though scans or skip-scans can still be possible. Run the customer report. It selects only the customer identifier and order date, which are both present in the composite index. This index covers this particular query: all requested columns are available there. Covering is a relationship to a query, rather than a universal label for the index.
Included Columns
Covering a Query With INCLUDE
SQL Server can include a payload column without adding it to the search key. The included order date can cover a customer-date report, without defining date as a key component. MySQL has no include clause, so a composite key is a common way to carry the additional value. SQLite also uses its own multicolumn index form here. A wider index takes more space and adds maintenance for the values it contains. Cover a valuable query deliberately, rather than copying every column into every index. These are alternative server listings, rather than extra definitions to stack blindly. Check what the existing composite index already supplies. An overlapping single-column index may be unnecessary, but size, uniqueness, and other workload needs can justify keeping it. Compare plans and maintenance before removing anything.
Full-Text Index
Word Search Versus Substring Search
Full-text indexing organizes words for text search, rather than treating a description as one ordinary sorted value. It suits documents and long descriptions. MySQL uses match against, while SQL Server uses contains with its full-text feature and a configured full-text index. This is a non-run dialect comparison. SQL Server setup needs an appropriate unique key and full-text catalog configuration. An ordinary index is not a substitute for that infrastructure. A leading wildcard in like generally prevents a normal prefix lookup. Word search is a different question from finding an arbitrary character substring. Tokenization, stopwords, and language settings affect full-text matches. Do not promise substring behavior, just because both searches contain the same letters.
Write Overhead
Every Index Adds Maintenance Work
An insert adds entries to base storage and relevant indexes. A delete removes them, while an update changes indexes containing affected key or included values. One table plus three secondary indexes means four logical structures to maintain. It does not mean exactly four physical disk writes, because pages, logging, and caching add other work. Indexes store keys and locators; covering payloads add more space. An index never used by important queries can consume resources while contributing little read benefit. Small tables, heavy bulk loads, rarely searched columns, and overlapping indexes all deserve restraint. A changed workload can also make a previously useful index expendable. Start with a slow important query, inspect its plan, add one targeted structure, and measure again. Check write cost and storage along with the read improvement.
Selectivity
Cardinality Ratio Versus Matched Fraction
Two different ideas are sometimes called selectivity. A column's distinct-value count divided by row count describes its cardinality ratio; a predicate's matched fraction describes that particular search. Our customers have four distinct cities across six people. The Pune predicate matches three people, so its matched fraction differs from the city cardinality ratio. Skew matters: even a column with few distinct values can have a rare value worth finding. Neither ratio alone decides whether an index pays. Run the calculation. These proportions describe the small illustrative baseline, without claiming a universal scan threshold or a benchmark speedup. The city ratio rounds to zero point six seven, while Pune matches one half. Judge the actual predicate, distribution, and needed output columns.
Quick Check
Two Rows Under a Composite Unique Rule
A new order-line sandbox has a unique index on the pair of order and product identifiers. The insert adds two rows, both for order one. Does the insert succeed with two rows, succeed with one, or fail? Pause, and predict. The insert succeeds with two rows. The unique rule applies to the entire pair, and the two pairs are different. Run it, and count star prints two. Sharing an order identifier is allowed when the product identifier makes the composite key distinct. One would incorrectly treat the first component as independently unique. Failure would require a repeated full pair under this definition.
Null Check
Two Nulls Under a Unique Index
A fresh SQLite sandbox stores two missing stock codes under a unique index. The final aggregate counts the code column, rather than whole rows. What happens: zero known codes, one known code, or a uniqueness error? Pause, and predict. Zero known codes are counted. SQLite permits both null entries in this unique index, and count of the column excludes null values. The real run prints zero. Count star would report two stored rows, while count of the missing codes reports none. A uniqueness error would fit different null rules in an ordinary single-column SQL Server unique index. It does not describe this SQLite program.
Key Takeaways
Keep the Smallest Useful Set
Leo and Amina can now evaluate each proposed structure by its job. Clustered organization, uniqueness, composite order, coverage, and word search answer different needs. Every extra structure has storage and maintenance costs. Account for key width, update volume, and the columns a real query needs. Inspect plans and distributions, then keep the smallest set that serves the workload reliably.
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 Types of Indexes and the Trade-Offs Between Read Speed and Write Overhead
What is the difference between a clustered and a nonclustered index?
What is a covering index?
Do indexes slow down inserts and updates?
When should you use a full-text index instead of a normal index?
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 →