# Slow OpenCart Queries: How to Find Them, Which Indexes to Add, and What to Fix in the Code

> Slow queries in OpenCart 3.0 and 4.1 come from N+1 queries in product lists, counters in the menu, tables without indexes, and LIKE searches. Here is how to find them and what to fix.

Джерело: https://opencartcode.com/en/wiki/dev-database/slow-queries-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-28

**Slow [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) queries** almost always have one of a few causes: a table without the right index, a query inside a loop (the classic N+1), counting products for every menu [category](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#category), a search through `LIKE '%…%'` in descriptions, or a service table that has grown to millions of rows. The MySQL slow query log and `EXPLAIN` help you find the culprit, and the fix usually comes down to an index, a cache, or a rewritten loop in the module.

Let's look at how this plays out in OpenCart 3.0 (3.0.4.1 and 3.0.5.1) and 4.1 (4.1.0.4): which indexes the core creates and which it doesn't, which settings load the database, and what to look for in the code of your own modules. The examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling work differently.

## How do you find a slow query in your store?

Before adding indexes, you need to see what is actually slowing things down. The most reliable source is the slow query log of MySQL or MariaDB itself. On a VPS it is enabled in the server configuration or on the fly:

```sql
SET GLOBAL slow_query_log = 1;
SET GLOBAL long_query_time = 0.5;
SET GLOBAL log_queries_not_using_indexes = 1;
SHOW VARIABLES LIKE 'slow_query_log_file';
```

log_queries_not_using_indexes option is useful for a short diagnostic period, but it clutters the log with tiny queries to small lookup tables, so turn it off afterwards. On shared hosting you usually don't have access to these variables; in that case, request the log from support or measure query times in code on a test copy.

Then run each suspicious query through `EXPLAIN` on a copy of the database with real data:

1. Copy the query from the log, substituting your [table prefix](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#table-prefix).
2. Run `EXPLAIN SELECT …` and look at the `type`, `key` and `rows` columns.
3. `type = ALL` on a large table with an empty `key` means a full table scan, which is a candidate for an index.
4. `Using temporary; Using filesort` in `Extra` over thousands of rows means sorting or grouping without a suitable index.
5. Compare `rows` before and after changes: this number, not a feeling, shows whether the index helped.

Also look at **how many** queries a single page makes, not just which ones are long. A hundred queries of 2 ms each add up to the same 200 ms as one slow query, and that is a typical footprint of a loop in a module.

On an OpenCart 3.0 store you can see these numbers without manual logging. The free [OCT Performance Profiler: performance profiler for OpenCart 3](https://opencartcode.com/en/marketplace/product/oct-performance-profiler) module shows a panel at the bottom of the page with time, query count and memory. In the admin it stores a full profile: how much time went to the database, how much to code, which module ran how many queries, and from which line. The profiler is enabled only for your own browser and works without OCMOD or changes to core files, so you can immediately see whether one long query is slowing things down or a hundred short ones inside a loop.

If you don't have access to the MySQL log, for example on shared hosting, you can log queries at the store level. The marketplace opencartcode.com offers the [SQL Query Log for OpenCart](https://opencartcode.com/en/marketplace/product/opencart-sql-query-log) module for this: it helps you see which SQL queries the store runs and find among them the slow ones or those repeated in a loop. Check compatibility with your OpenCart version and the exact feature set on the module's page. Enable the log only for the diagnostic period, because recording every query adds load of its own.

## Which indexes does the core have, and which are missing?

The core mainly indexes the primary keys of composite tables. That is enough for reading a product by id, but not for filtering by other fields. Below are the key tables that most often show up in the log.

| Table | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| `product` | only PK `product_id` | only PK `product_id` |
| `product_description` | PK `(product_id, language_id)`, KEY `name` | same |
| `product_to_category` | PK `(product_id, category_id)`, KEY `category_id` | same |
| `product_to_store` | PK `(product_id, store_id)` | same |
| `product_filter` | PK `(product_id, filter_id)`, no index on `filter_id` | same |
| `order` | only PK `order_id` | PK `order_id` and additional indexes from `db_schema.php` (check the composition via `SHOW INDEX`) |
| `session` | only PK `session_id` | PK, KEY `expire` |
| `seo_url` | KEY `query`, KEY `keyword` | KEY `(key, value)`, `keyword`, `store_id`, `language_id` |
| `customer_online` | only PK `ip` | only PK `ip` |

What follows from this in practice:

- **Filtering by `filter_id`** in `product_filter` cannot use the primary key, because it starts with `product_id`. In a catalog of tens of thousands of products with filters, the `KEY filter_id (filter_id)` index usually makes a noticeable difference.
- **Order lookups by customer** (`customer_id`) in the account area and in admin have no index in 3.0, and neither do lookups by status. For a large order history in 3.0, consider adding `KEY customer_id` and `KEY order_status_id`. In 4.1, `db_schema.php` creates additional indexes for `order`, so before adding your own, check the existing ones via `SHOW INDEX FROM `oc_order`` (with your prefix).
- **The [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) filters `product` by `status` and `date_available`**, but MySQL usually reads the product table through a JOIN on `product_id`, so a separate index on `status` rarely changes anything. Add it only when `EXPLAIN` shows that the query begins specifically with `product`.

The schema of the key tables is described in more detail in the article about [OpenCart database tables](https://opencartcode.com/en/wiki/dev-database/opencart-database-tables), and the structure of product tables is covered in the article about the [product table](https://opencartcode.com/en/wiki/dev-database/tablicia-product-opencart).

> Add an index to a core table on a copy first, verify `EXPLAIN`, and only then apply it on the production server during a quiet period. In 3.0 almost all tables are MyISAM, and `ALTER TABLE` locks the table for the entire rebuild. Record every index you add: during an OpenCart upgrade or schema migration, they are easy to lose.

## Why does the product list in 3.0 make dozens of queries?

**OpenCart 3.0:** `getProducts()` in `catalog/model/catalog/product.php` first selects only `product_id` for the page, then in a loop calls `getProduct()` for each product. Each such call is a separate query with subqueries for discount, special, rewards, rating and review count. A category with 100 products per page means at least 101 queries just for the list, not counting modules.

**OpenCart 4.1:** `getProducts()` selects all fields in one query with the same subqueries and caches the result in the OpenCart cache with the key `product.` + md5 of the SQL. The admin clears the `product` group when a product is saved, so the cache doesn't go stale. This removes N+1, but every unique combination of filters, sorting and page is a separate cache entry.

From this, some practical rules for modules follow:

- Don't call `getProduct()` inside a loop for blocks of 20–50 products in 3.0 unless necessary. If the block shows only the name, price and image, write one query with `IN (...)` in the module's model.
- Don't duplicate the core loop in your module: if the "Featured" block already got its products via `getProducts()`, don't make your own `getProduct()` for each one.
- Cache the results of heavy module queries with a key that accounts for language, store and [customer group](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#customer-group); how the cache works is described in the article about [OpenCart sessions and cache](https://opencartcode.com/en/wiki/dev-architecture/opencart-session).

Example: one query instead of a getProduct() loop

```php
public function getCards(array $product_ids): array {
	$ids = array_filter(array_map('intval', $product_ids));

	if (!$ids) {
		return [];
	}

	$query = $this->db->query("SELECT p.product_id, p.image, p.price, p.tax_class_id, pd.name
		FROM `" . DB_PREFIX . "product` p
		INNER JOIN `" . DB_PREFIX . "product_description` pd
			ON (pd.product_id = p.product_id AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "')
		INNER JOIN `" . DB_PREFIX . "product_to_store` p2s
			ON (p2s.product_id = p.product_id AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "')
		WHERE p.product_id IN (" . implode(',', $ids) . ") AND p.status = '1'");

	return $query->rows;
}
```

product_special (specials) and `product_discount` (quantity discounts). In 4.1, specials and discounts are stored in `product_discount`, so subqueries only go to that table. Another option is to fetch them with a second query for all ids at once. For how to correctly substitute language and store, see the article about [language_id and store_id](https://opencartcode.com/en/wiki/dev-database/language-id-opencart).

## Which store settings load the database?

Two options under System → Settings, on the Option tab, generate the most extra queries on every page.

Option tab: product counts in categories and online visitor tracking · OpenCart 4.1.0.4

### Product counts in categories

The `config_product_count` (Category Product Count) setting is enabled after installation in both branches. Then the menu (`common/menu`) and the category module call `getTotalProducts()` for each category and subcategory: a `COUNT(DISTINCT …)` query with a JOIN on description, store and categories. A menu with 15 sections of 10 subcategories each means about 150 counts on every store page. If you don't need counters in the menu, disable the option; if you do, calculate them once an hour and store them in the cache or in your own table.

### Online visitors

The `config_customer_online` (Customers Online) setting is disabled by default. When enabled, the footer on every page view runs `DELETE` for old records from `customer_online`, based on the condition on `date_added` and `REPLACE` of the current visit. There is no index on `date_added`, so this is a full table scan on every hit. In 3.0 the table is also MyISAM with table-level locking, so under a bot flood the queries queue up. Enable the option only when the report is actually being read, or add an index on `date_added`.

## Which tables grow without limits?

Slow queries often hit not product tables but service tables that nobody cleans up.

- **`session`**. In both branches, catalog sessions are stored in the database by default. Expired sessions are cleaned up by a probabilistic garbage collector: in 3.0 when a session is opened, in 4.1 in `register_shutdown_function`. **OpenCart 3.0:** there is no index on `expire`, so every cleanup scans the whole table. **OpenCart 4.1:** the index exists, but after `DELETE` the driver runs `OPTIMIZE TABLE`, which fully rebuilds a large InnoDB table. Bots without cookies create a new session on every request, so the table can grow very quickly.
- **`customer_activity`, `customer_ip`, `customer_search`** are logs of actions, IPs and search queries. They are useful for reports, but without periodic cleanup by date they take up more space than the entire catalog.
- **Module tables** with statistics, API logs or sync history. Plan an index on the date and cleanup from day one; how to structure this is described in the article about [custom module tables](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-tables), and running regular cleanup in 4.1 is convenient via [OpenCart cron](https://opencartcode.com/en/wiki/dev-extensions/cron-opencart).

Example: check the size of service tables

```sql
SELECT table_name, table_rows, ROUND((data_length + index_length) / 1024 / 1024) AS size_mb
FROM information_schema.tables
WHERE table_schema = DATABASE()
ORDER BY data_length + index_length DESC
LIMIT 15;
```

## Search and filters: where an index won't help

The standard search builds `LIKE` conditions for each word of the query against the product name, and when "Search in product descriptions" is checked, also against `description`. A pattern with a leading percent sign (`'%слово%'`) cannot use a B-tree index, so every search is a full scan of `product_description` for the current language. On a few thousand products this goes unnoticed; on tens of thousands with long descriptions, it takes seconds.

- don't enable description search by default in your custom templates and autocomplete modules;
- in autocomplete, search by name only, with a limit of `LIMIT` and a minimum query length of three characters;
- cache popular queries;
- for large catalogs, move search to a FULLTEXT index in your module's own table or to a separate search engine.

Core filters JOIN on `product_filter` (in 4.1, in "and" mode, also `HAVING COUNT` by the number of selected filters), while third-party filter modules use `product_attribute` or `product_option_value` for each group of conditions. Here the best results come from indexes on the field being filtered (`filter_id`, `attribute_id`) and from limiting the number of simultaneous conditions. Reasons why search fails to find products are a separate topic, covered in the article about [OpenCart search](https://opencartcode.com/en/wiki/catalog/opencart-search).

## Summary

- Start with the slow query log and `EXPLAIN` on a database copy; also count the queries per page.
- The core mainly indexes primary keys: `product_filter.filter_id`, in 3.0 also `order.customer_id`, `order.order_status_id` and `session.expire` are typical index candidates.
- In 3.0, `getProducts()` makes N+1 queries through `getProduct()`; in 4.1, it makes one query with a cache. In modules, don't repeat the core loop.
- Turn off product counters in the menu and online tracking if you don't need them: they cost hundreds of queries and a full table scan on every hit.
- Clean up `session`, activity logs and module tables by date.
- `LIKE '%…%'` An index can't fix search in descriptions; large catalogs need FULLTEXT or a separate search engine.

Next, check your store against this list on a database copy, and the safe assembly of queries in module models is described in the article about [SQL queries without injections](https://opencartcode.com/en/wiki/dev-database/opencart-sql-queries). All articles in this section are on the [OpenCart Database](https://opencartcode.com/en/wiki/dev-database) page.

## FAQ

**Will Converting OpenCart 3.0 Tables from MyISAM to InnoDB Help?**

Often, yes: InnoDB locks individual rows rather than the whole table, so simultaneous writes to service tables don't block reads. Do this on a copy, with a database backup and a check of modules that may rely on MyISAM behavior.

**How many indexes can you add without harm?**

Every index speeds up reads but slows down writes and takes up space. Add only the ones that show up in EXPLAIN for a specific slow query, and remove those that are not used.

**Why does the site slow down only at night?**

Usually because of background tasks: imports, synchronization with accounting systems, generating feeds or sitemaps, and backups. Compare the peak times in the slow query log with your cron schedule.

**Will page caching speed up the store instead of optimizing queries?**

For guests, yes, but the cart, account area, checkout, and admin do not benefit from page caching. Slow queries remain there, so combine caching with fixing the root causes.
