UPI Study › Courses › Database Programming › Free lessons › Lesson 9.8 Free with a free account
Creating Indexes in SQL: Steps and Examples
Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.8 · lesson 56 of 769 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: Working with Schema Objects in Practice →← Types of Indexes and the Trade-Offs Between Read Speed and Write OverheadNext lesson: Working with Schema Objects in Practice →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Create targeted indexes and verify them with catalogs and query plans.
- Write CREATE INDEX and CREATE UNIQUE INDEX statements for an actual query
- Choose composite index column order based on equality and range conditions
- Compare query plans before and after creating an index
- Inspect index names, uniqueness and key order in SQLite, MySQL and SQL Server
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,030 words). Read along, or search it.
Opening Problem
Created Successfully Is Not Proof
Amina Diallo, Lantern Books' database administrator, receives a note: the index was created successfully. Leo Park, the developer, still wants evidence that the important query benefits. What should they inspect before and after the change? A successful definition only establishes that an object exists. We will build targeted indexes, inspect their key order, and compare real SQLite access plans.
Sample Database
Starting From the Shared Baseline
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.
Baseline Plan
EXPLAIN QUERY PLAN Shows a Scan
Start with the actual query. It requests order identifiers for one customer, and our baseline has no separate index on the referencing customer column. SQLite's explain query plan reports the chosen operations. The dot command disables the shell's tree formatting, so we get plain columns without box-drawing characters. This small dataset demonstrates access methods, rather than a trustworthy timing benchmark. A realistic speed comparison also needs representative data and repeated workload measurements. Run the inspection before changing anything. Save the plan, so the later comparison has a known starting point. The detail reports scan orders. SQLite has chosen a broad read for this version of the query and schema.
CREATE INDEX
Indexing the Customer Column
Create index takes a chosen name, the target table, and a parenthesized column list. Here the key is the customer identifier used in our filter. No change to the select statement is required. The optimizer can consider the new access path automatically, rather than needing the index name in every query. Primary and unique rules already have supporting structures. InnoDB also supplies required referencing foreign-key indexes; SQLite and SQL Server do not generally do that for every foreign key. Run the definition and inspect the same query again. This compares the access method while holding the requested result constant. The detail now reports a search using the covering index. In this SQLite rowid table, its entries also supply the order identifier needed by the query.
Unique Index
A Uniqueness Rule Plus a Lookup Route
Add unique when the indexed key is a genuine uniqueness rule. This sandbox requires distinct non-null product names, as well as providing another lookup route. Creating a unique index fails if existing keys violate the rule. Review duplicates first, rather than assuming the build will clean the data for you. Null behavior differs by engine. SQLite and MySQL permit several nulls in a unique column, while an ordinary single-column SQL Server unique index permits one. Run this definition on the clean baseline. The lookup asks for the known catalog title after the rule is installed. Product eleven is returned. An attempted duplicate non-null name would be rejected; choosing the correct unique business key is more important than choosing a fashionable index name.
Composite Index
Equality First, Then a Date Range
A composite index lists multiple key columns. Put them in the order that fits the important lookup, rather than the order they happen to appear in a select list. Here customer equality comes first, followed by a date range. Equal customer values occupy one region, with dates ordered inside that region. A date-only search lacks that usual leading key condition. The engine might scan this index or choose a skip-scan, but a direct leading-prefix lookup is a different access path. Run the combined predicate. The customer and date conditions cooperate to narrow our small ordered result. Only Asha's later order appears. The composite structure may also serve customer-only searches, making the earlier single-column index potentially overlapping.
Catalog Inspection
Index Names and Key Positions
Inspect what you actually created. SQLite's index list reports names and uniqueness, while index info reports each key column's position. Our names use a short index prefix and table-purpose initials. A production convention can be more descriptive, as long as the team applies it consistently. MySQL and SQL Server require index names unique within a table. SQLite uses a wider schema namespace, so the same name cannot identify indexes on two different tables there. Run both catalog queries. The second result is useful, when a composite definition exists but its key order has been forgotten. Customer identifier is position zero, followed by order date at one. Those are SQLite's zero-based positions; MySQL's sequence-in-index field starts at one.
Server Tools
SHOW INDEX, Help Procedures and Plans
MySQL show index supplies the key name, column name, sequence in index, non-unique flag, and index type. A composite index appears as multiple rows. Non-unique zero means duplicates are forbidden, and one means they are allowed. The primary index is named primary in this MySQL display. SQL Server's help index procedure lists index descriptions and key order. Its estimated execution plan shows seek or scan operators, and statistics I O reports logical reads. These are non-run server listings. Compare MySQL explain's possible keys, chosen key, type, and estimated rows; estimates are not exact row counts or timing results. Compare a bare date with an inclusive start and exclusive end. Functions or leading wildcards can defeat ordinary seeks; broad matches may favor scans. Expression indexes offer other possibilities.
Quick Check
Which Column Sits at Position Zero
A new index definition appears on screen. A catalog query selects the key column at SQLite position zero. Which column is returned: order identifier, customer identifier, or order date? Pause, and predict. Order date is returned. The index definition sets its key order, and the catalog's zero position identifies the leading column. Run the inspection, and the printed name confirms that order. The earlier customer-first index does not control this independent definition. Customer identifier is the second key here. Order identifier can participate in SQLite's row locator, but it is not the declared first key in this query.
Key Takeaways
Evidence Before and After the Change
Amina and Leo have evidence beyond a successful create statement. Define the index for an actual query, with a deliberate key order and uniqueness rule. Inspect the catalog to confirm what exists, and compare plans before and after the change. Keep only useful structures, balancing read work against maintenance and storage. A real plan is evidence about access, while representative measurements establish performance.
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 Creating Indexes in SQL: Steps and Examples
How do you create an index in SQL?
What happens when you create a unique index on a column with duplicates?
Does column order matter in a composite index?
How do you see which indexes exist on a table?
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 →