Types of Indexes and the Trade-Offs Between Read Speed and Write Overhead

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

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

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

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.

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 Types of Indexes and the Trade-Offs Between Read Speed and Write Overhead

What is the difference between a clustered and a nonclustered index?
A clustered index stores the table's row data at its leaf level, so a table has at most one clustering order, while a nonclustered index is a separate structure whose entries locate rows. In SQL Server, a primary key is clustered by default when no clustered index exists, and a table without one is a heap. InnoDB always clusters by the primary key, an eligible unique non-null key, or a hidden row identifier.
What is a covering index?
A covering index contains every column a particular query needs, so the engine can answer from the index without fetching the table row. An index on (customer_id, order_date) covers SELECT customer_id, order_date FROM orders WHERE customer_id = 3. SQL Server can add non-key columns with INCLUDE; MySQL has no INCLUDE clause, so a composite key is a common substitute. Wider indexes cost more space and maintenance.
Do indexes slow down inserts and updates?
Usually, yes: each index adds maintenance work to inserts, deletes and updates that change its columns. An insert adds an entry to every relevant index, a delete removes it, and an update touches only indexes containing a changed key or included column. A table with three secondary indexes has four logical structures to maintain, though not four disk writes. An index can also help an UPDATE or DELETE find its rows, so weigh read gains against write costs.
When should you use a full-text index instead of a normal index?
Use a full-text index for searching words inside long text, such as product descriptions or documents. An ordinary index sorts whole values, so LIKE '%notebook%' with a leading wildcard generally cannot use a normal prefix lookup. MySQL searches full-text indexes with MATCH ... AGAINST, and SQL Server uses CONTAINS with a configured full-text index. Tokenization, stopwords and language settings affect matches, so word search differs from substring search.

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 →