Custom PHP

Database Indexing for PHP Applications, Without the Guesswork

Database indexing for PHP applications is the practice of adding the right B-tree indexes so the queries your PHP code sends to MySQL read fewer rows, then proving it with EXPLAIN. In my builds I start from the slow query log, order composite index columns by equality, range and sort, check covering index hits in the Extra column, and measure write cost before keeping any new index.

By Saif Al Jahanwebdev-saif.com

What an index changes inside InnoDB

In MySQL's InnoDB, the primary key is the table: rows are stored in a B-tree clustered by that key, and every secondary index is a separate B-tree whose leaf nodes hold the indexed columns plus the primary key. A lookup through a secondary index therefore means two tree walks unless the index covers the query. Your PHP code never touches those trees directly, but every PDO query you send is parsed, costed and executed against them. Indexing is not a setting you switch on; it is a decision about which access paths the optimizer can choose. The goal is to reduce rows examined, not just rows returned. I treat an index as a bet that a specific access pattern will repeat often enough to justify the storage and maintenance cost.

  • InnoDB clusters rows by the primary key; secondary index leaves store that key
  • A B-tree lookup is logarithmic, so rows examined matters more than table size
  • The optimizer can ignore an index, so confirm the chosen key in EXPLAIN
  • Each extra index consumes buffer pool pages that data pages also need

Read EXPLAIN before you add anything

Start from evidence, not intuition. Enable the slow query log with long_query_time = 0.5 during a representative window and summarise it with pt-query-digest; the top two or three statements usually account for most database time. Then run EXPLAIN FORMAT=JSON on the exact SQL your PHP prepares, with the same parameter values, because the optimizer works from cardinality and value distribution. On MySQL 8.0.18 and later, EXPLAIN ANALYZE executes the statement and reports actual versus estimated rows and loops, which exposes stale statistics. Read the type column first: system and const are best, eq_ref and ref are good indexed lookups, range is acceptable, index is a full index scan, and ALL is a full table scan. Then check key, rows, filtered and Extra. "Using filesort" or "Using temporary" on a frequent query is a signal, not automatically a bug.

  • long_query_time = 0.5 in the slow query log, summarised with pt-query-digest
  • EXPLAIN FORMAT=JSON for the plan; EXPLAIN ANALYZE for actual rows and loops
  • type ordering: system > const > eq_ref > ref > range > index > ALL
  • Extra: Using index is good; Using filesort and Using temporary need a closer look
  • Run ANALYZE TABLE when estimated and actual rows disagree badly

Composite indexes and the leftmost-prefix rule

A composite index is one B-tree keyed by several columns, so column order decides which queries can use it. InnoDB can seek on a leading prefix of the index and then stop: with an index on (tenant_id, status, created_at), a query filtering tenant_id and status can use the first two columns, while a query filtering only status cannot seek at all. Put columns joined by equality first, then the column used for a range or sort. For WHERE tenant_id = ? AND status = ? AND created_at BETWEEN ? AND ?, that order is the practical starting point. Leading with tenant_id also isolates tenants in a multi-tenant PHP app. Check Cardinality with SHOW INDEX FROM orders; a low-cardinality leading column such as a boolean flag rarely earns its space. MySQL 8.0.13 added skip scans for some cases, but I do not design around them.

  • Equality columns first, then the range column, then the sort column
  • An index on (a, b, c) also serves (a) and (a, b), but not (b) alone
  • Check Cardinality with SHOW INDEX FROM orders; low-cardinality leading columns waste space
  • Keep every index definition in a migration so PHP deployments reproduce it

Covering indexes: removing the second tree walk

A covering index contains every column the query needs, so InnoDB returns the result from the index leaf without looking up the clustered row. EXPLAIN tells you this plainly: the Extra column shows Using index. For a dashboard query that selects only status and created_at for one tenant, an index on (tenant_id, created_at, status) can serve the filter, the sort and the projection at once. Because InnoDB secondary leaves already carry the primary key, you do not append it manually. The trap is SELECT *: one extra column in the projection breaks the cover and turns a cheap index scan into thousands of random primary-key lookups. Covering indexes are wider, so they use more buffer pool pages and cost more to maintain. I use them for stable, high-frequency reads, not for every list endpoint.

  • Confirm with Extra = Using index in EXPLAIN rather than assuming it
  • Select only the columns you need; one SELECT * breaks the cover
  • InnoDB already stores the primary key in every secondary index leaf
  • Wider indexes mean fewer data pages in the buffer pool and more write work

When indexes hurt writes

Every secondary index is another B-tree that INSERT, UPDATE and DELETE must maintain. A write to a row with six secondary indexes can mean six tree modifications, page splits, redo log records and undo entries, plus more dirty pages to flush. The cost shows up as slower writes, a lower buffer pool hit rate and more storage. Indexes on frequently changed columns are the worst case, because updating an indexed value is a delete plus an insert in that tree. I compare INSERT and UPDATE throughput before and after adding an index, and watch Innodb_rows_inserted, Innodb_rows_updated and Innodb_buffer_pool_reads. To find dead indexes, query performance_schema.table_io_waits_summary_by_index_usage for rows with COUNT_READ = 0 and a non-null INDEX_NAME; those are candidates to drop. On write-heavy tables I keep the index set minimal and let a few well-chosen composite indexes do the work.

  • Each secondary index adds tree maintenance, redo and undo work on every write
  • Updating an indexed column is a delete plus an insert in that index
  • Find unused indexes with performance_schema.table_io_waits_summary_by_index_usage
  • Watch Innodb_buffer_pool_reads; a rising count means index pages are evicting data

Make the query sargable in PHP

The best index is useless if the SQL hides the column. WHERE DATE(created_at) = ? or WHERE LOWER(email) = ? forces a scan; compare the raw column to a computed value instead, or add a generated column and index that. Keep the column on one side of the operator and avoid leading wildcards such as LIKE "%term": a trailing wildcard LIKE "term%" can use a B-tree. In PDO, bind values with execute([$id]) or bindValue so the optimizer sees a stable statement shape, and log the final SQL with its bound parameters when a plan surprises you. If you build queries through a WordPress $wpdb wrapper, use $wpdb->prepare and declare indexes in dbDelta alongside the table schema. I keep index definitions in versioned migrations so the plan tested locally is the one that reaches production.

  • Wrap the parameter, not the column: created_at >= ? AND created_at < ?
  • LIKE "term%" can use an index; LIKE "%term" cannot
  • Use $wpdb->prepare for custom tables and declare indexes in dbDelta
  • Store index definitions in migrations so environments do not drift

A worked example from a catalogue build

Suppose a catalogue screen in a custom PHP app loads orders for one account, newest first, and displays only status and created_at. I start with the slow query log entry, run EXPLAIN FORMAT=JSON and see type = ALL with rows in the hundreds of thousands. I add one composite index on (account_id, created_at, status). Re-running EXPLAIN should show type = ref or range, a much smaller rows estimate, and Using index in Extra. If the write path slows noticeably, I check whether status is updated often; when it is, I drop status from the index and accept a primary-key lookup for that one column. That is the trade-off I document for clients: read speed is bought with write cost, and the right balance depends on the workload. I write up decisions like this on webdev-saif.com, where I work as Saif Al Jahan, a freelance PHP developer in Mymensingh, Bangladesh.

Frequently asked questions

What is database indexing for PHP applications?

It is the practice of creating B-tree indexes in MySQL so the SQL your PHP code issues examines fewer rows. You define the indexes in the database, not in PHP, but PHP decides the query shape: which columns are filtered, sorted and selected. The work is to choose composite column order, confirm with EXPLAIN that the optimizer uses the index, and keep the index set small enough that writes stay fast.

How do I know which index to add?

Start with the slow query log and pt-query-digest to find the statements costing the most time, then run EXPLAIN or EXPLAIN ANALYZE on each one. Look at type, key, rows and Extra. Add an index that matches the filter and sort columns in that specific statement, rerun EXPLAIN to confirm the rows estimate drops, and keep it only if the write path stays acceptable.

What is the difference between a composite index and a covering index?

A composite index is one index over several columns; its column order decides which queries can seek into it. A covering index is any index, composite or single-column, that contains every column a query needs, so MySQL reads the index without touching the table row. In EXPLAIN, a covering index shows Using index in the Extra column.

Why can adding an index make my app slower?

Because every INSERT, UPDATE and DELETE has to update each index as well as the table. A table with several secondary indexes does several B-tree modifications per write, with page splits, redo and undo records. Wide indexes also push data pages out of the buffer pool. If an index is rarely read but constantly maintained, dropping it is usually the faster choice.

Does an index help a LIKE '%term%' search?

No. A leading wildcard gives the B-tree no prefix to seek on, so MySQL scans the index or table. LIKE 'term%' can use a B-tree index because the prefix is known. For substring or full-text search, use a FULLTEXT index with MATCH ... AGAINST, or a dedicated search engine, rather than expecting a normal index to help.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .