Square CloudSquare Cloud

What is a database index and when to create one

An index is a separate, sorted structure, usually a B-tree, that lets the database find rows without reading the whole table. Add one for columns used in WHERE, JOIN and ORDER BY of frequent queries, and confirm the gain with EXPLAIN.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand how a B-tree index finds a row in a few steps
  • Decide when to add an index, how to order the columns of a composite index and when it hurts
  • Read PostgreSQL and MySQL EXPLAIN output and MongoDB's explain to confirm the index is used
On this page

With a thousand rows, every query looks fast. With a million, the same customer lookup that took a millisecond takes hundreds, and the page that runs it slows down. Most of the time the code didn't change and the database isn't overloaded: it is just reading the entire table to find half a dozen rows, because nobody created an index.

An index is the first place to look when a query slows down as data grows, and also one of the easiest ways to make writes slow without noticing. This guide explains what an index is inside, when to create one, how to order its columns and how to confirm the effect with EXPLAIN.

What is a database index?#

An index is a structure kept apart from the table that stores the values of one or more columns in order, each with a pointer to the row where it lives.

The classic comparison is the index at the back of a book: instead of flipping through 400 pages looking for "replication", you go to R, find the entry and jump straight to pages 212 and 318. Without an index, the database does the equivalent of flipping through everything, called a sequential scan (Seq Scan in PostgreSQL, full table scan in MySQL, COLLSCAN in MongoDB).

The database maintains the index on its own: once it exists, it follows every write to the table. The query planner decides, query by query, whether using it pays off.

How does a B-tree index work inside?#

The default type in PostgreSQL, MySQL (InnoDB) and MongoDB is the B-tree, a balanced tree of pages:

  • The leaves hold every value of the column in order, each with the pointer to its row.
  • The internal nodes and the root hold only ranges of values ("1 to 5,000 go this way, 5,001 to 10,000 that way").

To find customer_id = 42, the database reads the root, walks down the right branch and reaches the leaf in a few steps. Because each page holds hundreds of entries, the tree stays shallow even with millions of rows, and each extra level multiplies its capacity. That is why the lookup stays fast as the table grows, while a sequential scan gets proportionally slower.

Since the leaves are sorted, the same B-tree serves equality (=, IN), ranges (<, >, BETWEEN), prefixes (LIKE 'abc%'; in PostgreSQL outside the C locale this needs an operator class such as text_pattern_ops) and rows already sorted for an ORDER BY ... LIMIT. It doesn't serve LIKE '%abc' (the start is unknown) or a column wrapped in a function.

What the pointer points to depends on the engine. In PostgreSQL, the leaf points to the row's position in the table. In InnoDB, the table itself is organized by the primary key (the clustered index), and a secondary index stores the primary key value to fetch the full row.

When should you create an index?#

Create one when a frequent query filters, joins or sorts by a column and returns a small part of the table:

  • WHERE columns with good selectivity: email, customer_id, order_id.
  • JOIN columns, foreign keys in particular. The PostgreSQL docs point out that declaring a foreign key doesn't index the referencing column; MySQL creates that index itself.
  • ORDER BY with LIMIT, such as "this customer's 20 most recent orders".
  • Uniqueness. The primary key and UNIQUE constraints already create a unique index automatically.

An example in PostgreSQL, with a million orders:

sql
CREATE TABLE orders (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id  bigint NOT NULL,
  status       text NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now()
);

INSERT INTO orders (customer_id, status, created_at)
SELECT (random() * 10000)::int,
       (ARRAY['paid', 'pending', 'canceled'])[1 + floor(random() * 3)::int],
       now() - random() * interval '365 days'
FROM generate_series(1, 1000000);

ANALYZE orders;

EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;

How do you read EXPLAIN and confirm the index is used?#

Without an index, the plan shows a sequential scan that throws almost everything away (trimmed output):

text
Seq Scan on orders  (cost=... rows=100 ...) (actual time=... rows=97 loops=1)
  Filter: (customer_id = 42)
  Rows Removed by Filter: 999903

On a large table it may appear as a Parallel Seq Scan under a Gather; it's the same full read. Now create the index and run it again:

sql
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
text
Bitmap Heap Scan on orders  (cost=... rows=100 ...) (actual time=... rows=97 loops=1)
  Recheck Cond: (customer_id = 42)
  ->  Bitmap Index Scan on orders_customer_id_idx  (...)
        Index Cond: (customer_id = 42)

Index Scan, Index Only Scan and Bitmap Index Scan all use the index; the planner picks among them by the expected row count. Compare the execution time at the end of the output too. Careful: EXPLAIN ANALYZE really runs the query, so test an UPDATE or DELETE inside BEGIN and ROLLBACK.

In MySQL, EXPLAIN shows the same thing in columns. Before the index, type: ALL (a full table scan) and key: NULL; after it, type: ref and the index name in key, with rows dropping from close to a million to a few dozen:

sql
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;

If things are still slow after the index, the bottleneck may be elsewhere: why is my app slow shows how to tell the database, the network and the code apart.

How does a composite index work and why does column order matter?#

A composite index covers several columns, sorted by the first, then by the second within each value of the first, and so on, like a phone book sorted by last name and then first name.

sql
CREATE INDEX orders_customer_status_date_idx
  ON orders (customer_id, status, created_at);

It serves queries that use the start of the column list (the "leftmost prefix"):

  • WHERE customer_id = 42
  • WHERE customer_id = 42 AND status = 'paid'
  • WHERE customer_id = 42 AND status = 'paid' ORDER BY created_at DESC LIMIT 20

It does not serve WHERE status = 'paid' on its own well, because status values are spread across every customer. PostgreSQL and MySQL have an optimization called skip scan that, in specific cases, uses the index without the first column when that column has few distinct values. Don't design the index around it.

The rule of thumb: columns compared with equality first, then the range or ORDER BY column. The PostgreSQL docs also advise using composite indexes sparingly: in most cases a single column is enough, and more than three rarely helps. If an ORM creates your tables, the composite index goes in the model definition; see which ORM to use in Node.js.

When does an index hurt?#

Indexes aren't free, and the PostgreSQL docs recommend dropping the ones that are seldom used:

  • Slower writes. Every INSERT writes an entry into each of the table's indexes, and so do many UPDATEs. A log table with eight indexes does eight extra writes for every new row.
  • Space. Indexes take disk and compete with data for the database's cache memory.
  • Low selectivity. A boolean column or a status with three values rarely helps on its own: if the condition returns a big chunk of the table, a sequential read is cheaper, and the planner chooses it.
  • Small tables. With a few hundred rows, reading everything beats consulting the index.
  • A function on the column. WHERE lower(email) = 'ana@example.com' doesn't use an index on email. Create an expression index: CREATE INDEX ON users (lower(email)) in PostgreSQL or CREATE INDEX users_email_lower ON users ((lower(email))) in MySQL.

To find unused indexes:

sql
-- PostgreSQL: idx_scan = 0 since the last statistics reset
SELECT relname AS table_name, indexrelname AS index_name, idx_scan
FROM pg_stat_user_indexes
ORDER BY idx_scan;

-- MySQL
SELECT * FROM sys.schema_unused_indexes;

Don't drop primary key or UNIQUE indexes even with zero reads: they enforce the constraint.

Building an index on a large table has a cost too. In PostgreSQL, a plain CREATE INDEX blocks writes until it finishes; CREATE INDEX CONCURRENTLY lets writes through, takes longer and can't run inside a transaction, which matters for migrations on deploy tools. In InnoDB, adding a secondary index keeps the table available for reads and writes.

Beyond the B-tree there are types for specific cases: GIN for jsonb, arrays and text search in PostgreSQL, FULLTEXT in MySQL, and pgvector's vector indexes, which compete with dedicated vector databases.

What about MongoDB?#

MongoDB creates a unique index on _id in every collection and uses B-trees for the rest. The reasoning is the same, with the ESR guideline from its docs for composite indexes: Equality fields first, then Sort fields, then Range fields.

js
db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1 });

db.orders
  .find({ customerId: 42, status: "paid" })
  .sort({ createdAt: -1 })
  .explain("executionStats");

In the result, IXSCAN in the winning plan means the index was used and COLLSCAN means a full collection read. Compare totalDocsExamined with nReturned: with a good index, the two stay close. The engine itself is covered in what is MongoDB.

How to do this on Square Cloud#

Square Cloud offers PostgreSQL, MySQL and MongoDB hosting from the Standard plan. You create the database in the dashboard, choose the instance's memory, and it is ready in seconds in the same datacenter as your apps. Indexes are part of your schema: creating, measuring and dropping each one is up to you.

The connection is external and requires TLS, so you can run EXPLAIN from your own machine with the engine's client, using the URL and certificate from the dashboard. The dashboard also has a data explorer for quick lookups; for analyzing plans and creating indexes day to day, use the engine's dedicated tool.

Before creating or dropping indexes on a large table, take a manual snapshot of the database: manual snapshots are on every plan, and every plan with databases also includes a daily automatic snapshot. PostgreSQL comes with the pgvector extension, in case your next index is for vector search.

See engines, limits and plans on the database hosting page.

Database hosting

MongoDB, PostgreSQL, MySQL and Redis next to your app

Database hosting

FAQs

Does a primary key already create an index?

Yes. In PostgreSQL and MySQL, the primary key and UNIQUE constraints create a unique index automatically. A foreign key only gets an automatic index in MySQL (InnoDB); in PostgreSQL you create it yourself on the referencing column.

Should I index every column?

No. The database keeps every index in sync with the table, which costs something on every write, and each one takes disk and memory. Index for the queries you actually run and drop the ones nobody uses.

Why is the database ignoring my index?

The usual reasons: the query wraps the column in a function, the column isn't the first one of a composite index, the table is small, or the condition returns a large share of the table. In those cases a sequential read is cheaper and the planner picks it.

Does creating an index lock the table?

In PostgreSQL, a plain CREATE INDEX blocks writes until it finishes, and CREATE INDEX CONCURRENTLY avoids that at the cost of a longer build. In MySQL with InnoDB, adding a secondary index keeps the table available for reads and writes.

Next articleHow to connect PostgreSQL to Node.js (pg and Prisma)Connect Node.js to PostgreSQL with pg or Prisma: one pool per process, the URL in an environment variable, and TLS that verifies the server against its CA.

More in Databases

See all 32 articles