I have an application that I noticed suddenly decreased in speed when copying from the live database to a test database. Both databases are on the same server, and the test database was created from a mysqldump of the live data. So they are identical, on the same instance.
When I explain a slow query on the two databases, one is using indexes and the other is not. This is happening on more than one query type, but I will show one example:
Here is the query I'm running:
SELECT * FROM product
INNER JOIN product_category pc
ON product.id = pc.product_id
INNER JOIN category c
ON c.id = pc.category_id
WHERE
(c.discount_amount > 0 OR c.discount_percent > 0)
AND (c.`discount_start_date` <= NOW() OR c.`discount_start_date` IS NULL)
AND (c.`discount_end_date` >= NOW() OR c.`discount_end_date` IS NULL)
Here is the EXPLAIN result from the live database:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|---|---|---|---|---|---|---|---|---|---|
| 1 | SIMPLE | c | index_merge | PRIMARY,category_discount_start_date,category_discount_end_date,category_discount_amount,category_discount_percent | category_discount_amount,category_discount_percent | 8,8 | NULL | 10 | Using sort_union(category_discount_amount,category_discount_percent); Using where |
| 1 | SIMPLE | pc | ref | category_id,product_id | category_id | 4 | lollipop_site.c.id | 19 | |
| 1 | SIMPLE | product | eq_ref | PRIMARY | PRIMARY | 4 | lollipop_site.pc.product_id | 1 |
and here is the EXPLAIN result from the test database:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|---|---|---|---|---|---|---|---|---|---|
| 1 | SIMPLE | product | ALL | PRIMARY | NULL | NULL | NULL | 1 | |
| 1 | SIMPLE | pc | ALL | category_id,product_id | NULL | NULL | NULL | 1 | Using where; Using join buffer (flat, BNL join) |
| 1 | SIMPLE | c | eq_ref | PRIMARY,category_discount_start_date,category_discount_end_date,category_discount_amount,category_discount_percent | PRIMARY | 4 | lollipop_sandbox.pc.category_id | 1 | Using where |
I am using MariaDB inside docker version is 10.7.3-MariaDB-1:10.7.3+maria~focal.
I'm hoping someone can shed some light onto why the server is using a different query plan for the same query on the same data just being in different databases.
Note this query was previously using WHERE id IN (SELECT product_id FROM... style query and I converted it as recommended by other stackoverflow answers. This install has a number of those queries that are also having this problem.