1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL Indexes Explained: How They Work and When to Use Them

An index is what turns a slow table scan into a fast lookup. We tested one on 200,000 rows and show the numbers, the query plans, the traps that make an index useless and its cost on writes.

8 min read
SQL indexes explained: how they work and when to use them

Key takeaways

  • An index is a sorted copy of one or more columns that lets the database find rows without reading the whole table.
  • In our test, one lookup on 200,000 rows dropped from about 8 ms to about 0.003 ms after adding an index.
  • In a composite index the column order matters: it helps queries that use the leading columns.
  • Indexes speed up reads but slow down writes and use storage, so add them for real query patterns only.

A query that feels instant on 100 rows can crawl on 10 million. Most of the time the cure is not a bigger server. It is a SQL index on the right column.

This guide builds on our SQL tutorial for beginners. If you join tables a lot, read SQL joins explained too, because join columns are prime candidates for indexes.

What an SQL index is

Think of the index at the back of a book. Instead of reading every page to find “foreign key”, you look it up in the sorted list and jump to the page. A database index works the same way: a sorted structure, usually a B-tree, that stores column values and pointers to the rows.

Without an index the database does a full table scan and checks every row. With one, it does an index seek and goes straight to the matching rows.

CREATE INDEX idx_users_email ON users (email);
DROP INDEX idx_users_email;

Our 200,000-row test

We created a users table with 200,000 rows in SQLite 3.50 and looked up one email address. The EXPLAIN QUERY PLAN command shows how the database will run a query.

SELECT * FROM users WHERE email = 'user150000@example.com';

-- before: SCAN users                                       (about 8.16 ms)
CREATE INDEX idx_users_email ON users (email);
-- after:  SEARCH users USING INDEX idx_users_email (email=?)  (about 0.003 ms)

The word SCAN means every row was read. SEARCH ... USING INDEX means the database jumped to the match. Times are averages from our run; yours will differ, but the gap grows with table size. Other databases print plans with EXPLAIN or EXPLAIN ANALYZE.

Composite indexes and column order

When queries filter on several columns, one index on both can beat two separate ones.

SELECT COUNT(*) FROM users WHERE country = 'IN' AND age > 60;

CREATE INDEX idx_country_age ON users (country, age);
-- before: about 10.81 ms      after: about 0.35 ms
-- plan: SEARCH users USING COVERING INDEX idx_country_age (country=? AND age>?)

Order matters. This index works for filters on country, or on country and age. A query that filters only on age cannot seek into it. In our test it fell back to scanning the index, which is better than scanning the table but not a true lookup:

SELECT COUNT(*) FROM users WHERE age > 60;
-- plan: SCAN users USING COVERING INDEX idx_country_age

A good rule: put columns you compare with = first and a range column last.

What stops an index from being used

  • A function on the column. WHERE LOWER(email) = ... cannot use a plain index on email. Our test plan showed SCAN users.
  • A leading wildcard. WHERE email LIKE '%150000@example.com' forces a scan as well. LIKE 'user15%' can use an index.
  • Low-selectivity columns. An index on a yes/no column helps little because half of the rows match.
  • Type mismatches. Comparing a number column with a string can disable the index in some databases.

Tip: to search case-insensitively with an index, store a lowercase copy of the value, or create an expression index if your database supports it, such as PostgreSQL.

The cost of indexes

Every index must be updated on each insert, update and delete, and it takes disk space. We inserted 20,000 rows into the same table once with our two extra indexes and once without them. The version with indexes was about twice as slow, in a test that took only a few hundredths of a second, so the exact numbers are small, but the direction is always the same.

Index type What it is Good for
Primary key Unique index that identifies each row Lookups by ID, foreign keys
Unique index Index that forbids duplicates Emails, usernames
Composite index Index on several columns Queries that filter on those columns together
Covering index Index that contains every column the query needs Very fast reads without touching the table
Clustered index Table rows stored in index order, in databases that support it Range queries on one ordering

When to add an index

  1. Find slow queries first, from logs or the query plan, not by guessing.
  2. Index columns used in WHERE, JOIN and ORDER BY of frequent queries.
  3. Prefer high-selectivity columns such as email or order number.
  4. Check the plan again after adding the index to confirm it is used.
  5. Drop indexes nobody uses. They still cost every write.

Testers can verify this too. Compare query times with and without data growth when you validate database behaviour, using the queries in our SQL interview questions for testers.

Final thoughts

Read the plan, add the smallest useful index and read the plan again. That loop will fix most slow queries without any other change.

Frequently asked questions

What is an index in SQL?

An index is a sorted data structure on one or more columns that lets the database find rows quickly without scanning the entire table.

Do indexes slow down inserts and updates?

Yes. Every index has to be kept in sync with the table, so writes become slower as you add indexes. That is the price for faster reads.

What is the difference between a clustered and a non-clustered index?

A clustered index decides the physical order of the rows in the table, so there is only one per table. A non-clustered index is a separate structure that points back to the rows.

Does column order matter in a composite index?

Yes. The index helps queries that use its leading columns. A filter on only the second column usually cannot seek into the index.

How can I check whether a query uses an index?

Run EXPLAIN, or EXPLAIN QUERY PLAN in SQLite, in front of the query. A scan means no index was used, while a seek or search shows the index name.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →