Creating Indexes in SQL: Steps and Examples, Explained

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

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

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

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.

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 Creating Indexes in SQL: Steps and Examples

How do you create an index in SQL?
Use CREATE INDEX with a name, the table and a column list, for example CREATE INDEX idx_orders_customer ON orders (customer_id). Queries do not need to mention the index; the optimizer considers it automatically. Check the effect by comparing plans before and after: in SQLite, EXPLAIN QUERY PLAN can change from SCAN orders to a SEARCH using the new index. MySQL uses EXPLAIN, and SQL Server shows execution plans.
What happens when you create a unique index on a column with duplicates?
CREATE UNIQUE INDEX fails, because the existing data must already satisfy the rule; it will not remove duplicates for you. Find them first with GROUP BY and HAVING COUNT(*) > 1. Once the index exists, inserts or updates that would repeat a non-NULL key are rejected. NULL handling differs: SQLite and MySQL allow several NULLs, while an ordinary single-column SQL Server unique index allows only one.
Does column order matter in a composite index?
Yes, the index sorts by its first column, then by the next column within each first value. An index on (customer_id, order_date) suits WHERE customer_id = 3 AND order_date >= '2025-09-01', with equality first and the range second. It can also serve customer-only searches, but a date-only search lacks the leading column, so the engine may scan the index or skip-scan instead. The order of WHERE conditions does not matter.
How do you see which indexes exist on a table?
Query the catalog. In SQLite, PRAGMA index_list('orders') shows index names and uniqueness, and PRAGMA index_info('idx_orders_customer') shows key columns with zero-based positions. MySQL's SHOW INDEX FROM orders lists one row per key column, with Seq_in_index starting at 1 and Non_unique set to 0 for unique indexes. In SQL Server, EXEC sp_helpindex 'orders' lists index descriptions and key columns.

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 →