When you might want to use optimizer hints
This article was written by Oleg Smirnov, MariaDB Server engineer, and is shared here on his behalf. All credit for the research, the examples and the measurements goes to Oleg.

Why optimizers are not perfect
Modern database optimizers (sometimes called planners) are smart, and MariaDB Server is no exception. In fact, these subsystems are sophisticated pieces of technology designed to construct the most efficient execution plan for a query using available information about the database structure and the data it stores. Optimizers evaluate the number of records in tables, usable indexes, distribution of values in columns and a lot more. They apply cost models when enumerating possible plans and choose the best one (within given limitations).
Optimizers rely heavily on up-to-date statistics when evaluating possible plans. The preferred option for MariaDB is the engine-independent variant of statistics, which provides the most advanced set of data for the optimizer to make the right choices.
With all that said, sometimes optimizers end up with suboptimal plans. There are a number of reasons why.
Reasons for suboptimal query plans
Overly large plan search space
The number of possible execution plans grows exponentially with the number of tables joined, and enumerating them all may consume too many server resources. Imagine optimization taking half an hour, and the execution itself only several seconds – that hardly makes sense. It is more reasonable to choose a “good enough” plan in a reasonable amount of time. So, optimizers usually apply some heuristics allowing them to prune non-promising plans early. These heuristics aren’t perfect, so they can prune a partial plan as “non-promising” while in reality it might have led to the optimal final one.
Stale statistics
Database statistics are not updated automatically as data changes. They are re-collected either manually or on a regular basis. If the data changes frequently, statistics may become stale and mislead the optimizer.
Cardinality misestimation
Even up-to-date statistics represent only an approximation of the actual data, assuming uniform distribution and no data correlation between different entities. However, such assumptions don’t always hold, which will be demonstrated in the examples below. A well-known paper “How Good Are Query Optimizers, Really?” identifies cardinality misestimation as the number one factor in producing bad plans.
Cost model imperfection
MariaDB Server made a huge leap with its cost model in version 11.0, but a model is still only a model: it cannot represent the actual hardware timings with absolute accuracy. The model doesn’t know whether you store data on SSD or HDD, how fast your disks and memory are, and so on. Although those costs can be adjusted to match your actual hardware, doing so is difficult and risky.
Compared to cardinality misestimation, the contribution of the cost model is minor – which is probably why tuning the cost constants for specific hardware is so rarely done in practice, on either MySQL or MariaDB.
Optimizer hints
Today, many databases provide a way to influence optimizer decisions with so-called “hints”. Essentially, hints are specially formatted comments embedded right into a query text, so they affect only one particular query. Optimizer hints have no standard syntax, differing from one database to another. However, at some point, MySQL introduced a new syntax based on that of Oracle Database, and compatible databases including MariaDB and TiDB followed the same way. Now MariaDB offers a comprehensive set of hints allowing a developer or a DBA to override default optimizer decisions, such as join ordering, use of indexes, transformation of subqueries, and others.
Fixing optimizer inefficiency is not the only use of hints. They can also be applied when:
- plan stability for a critical query is required;
- diagnosing performance regression after statistics refresh or version upgrade;
- testing specific execution plans manually.
This article demonstrates the use of hints to improve performance when querying for correlated data (“Cardinality misestimation” from the list above).
Optimizer hints demo: correlated data the optimizer cannot see
The story: an online shop. Almost all customers are retail buyers who place a handful of orders each. But 50 accounts are wholesale distributors, 40 are registered in New Zealand. Wholesale distributors place half of all the orders in the system.
Per-column statistics describe each column perfectly:
customers.countryhas 20 distinct values, ‘NZ’ occurs 50 times;orders.customer_idhas 100000 distinct values, 1000000 rows, so 10 orders per customer on average.
Neither of those facts is wrong. What is wrong is combining them: the optimizer multiplies them into “50 NZ customers x 10 orders = 500 orders”, while the true answer is 400059. Country and order count are correlated, but no single-column statistic can express that.
All timings quoted below come from one machine with everything already in the buffer pool. Your absolute numbers will differ; the ratios are what matter.
Sample dataset
CREATE TABLE customers (
id INT PRIMARY KEY,
country CHAR(2) NOT NULL,
segment ENUM('retail','wholesale') NOT NULL,
name VARCHAR(40) NOT NULL,
KEY country (country)
) ENGINE=InnoDB;
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT NOT NULL,
created_at DATETIME NOT NULL,
channel VARCHAR(8) NOT NULL,
amount DECIMAL(10,2) NOT NULL,
KEY customer_id (customer_id),
KEY created_at (created_at),
KEY channel (channel)
) ENGINE=InnoDB;
-- 40 of the 50 wholesale accounts are registered in NZ.
INSERT INTO customers (id, country, segment, name)
SELECT seq, 'NZ', 'wholesale', CONCAT('Wholesale account #', seq)
FROM seq_1_to_40;
-- The other 10 are scattered over ten other countries.
INSERT INTO customers (id, country, segment, name)
SELECT seq, ELT(seq - 40, 'AU','US','GB','DE','JP','CA','FR','NL','SE','IE'),
'wholesale', CONCAT('Wholesale account #', seq)
FROM seq_41_to_50;
-- New Zealand also has 10 ordinary retail customers.
INSERT INTO customers (id, country, segment, name)
SELECT seq, 'NZ', 'retail', CONCAT('Retail customer #', seq)
FROM seq_51_to_60;
-- 99940 retail customers spread evenly over 19 other countries.
INSERT INTO customers (id, country, segment, name)
SELECT seq,
ELT(1 + seq % 19, 'US','CA','MX','BR','AR','GB','IE','FR','DE','ES',
'IT','NL','SE','FI','PL','JP','KR','AU','ZA'),
'retail', CONCAT('Retail customer #', seq)
FROM seq_61_to_100000;
-- Half of all orders belong to the 50 wholesale accounts: 10000 each.
-- Wholesale buys over EDI and by phone, and only accounts 1-5 run retail
-- outlets, so only they ever produce a POS order.
INSERT INTO orders (id, customer_id, created_at, channel, amount)
SELECT seq,
1 + seq % 50,
TIMESTAMP('2020-01-01') + INTERVAL (seq % 157680) * 1000 SECOND,
IF(seq % 997 = 0 AND 1 + seq % 50 <= 5,
'POS', ELT(1 + seq % 3, 'EDI', 'EDI', 'PHONE')),
10000 + seq % 90000
FROM seq_1_to_500000;
-- The other half is spread over the 99950 retail customers: ~5 orders each.
INSERT INTO orders (id, customer_id, created_at, channel, amount)
SELECT 500000 + seq,
51 + seq % 99950,
TIMESTAMP('2020-01-01') + INTERVAL (seq % 157680) * 1000 SECOND,
IF(seq % 47 = 0, 'POS', ELT(1 + seq % 3, 'WEB', 'WEB', 'APP')),
10 + seq % 500
FROM seq_1_to_500000;
-- Collect the best statistics MariaDB can offer. This is the point of the
-- demo: the statistics below are exact, and the plan is still wrong.
ANALYZE TABLE customers, orders PERSISTENT FOR ALL;
-- The data, for reference:
-- customers 100000
-- orders 1000000
-- country='NZ' 50 customers, 400059 orders (8001 each)
-- 19 other countries ~5260 customers each; the 10 that host a
-- distributor have ~36313 orders, the other
-- 9 have ~26313
-- channel='POS' 10688 orders, of which 50 are wholesale
Example 1: plain join. Join order/index hints
The query: POS terminal sales in New Zealand. It returns 51 rows.
ANALYZE SELECT o.id, o.created_at, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ'
AND o.channel = 'POS';
-- +------+-------+------+-------------+------+---------+----------+------------+
-- | id | table | type | key | rows | r_rows | filtered | r_filtered |
-- +------+-------+------+-------------+------+---------+----------+------------+
-- | 1 | c | ref | country | 50 | 50.00 | 100.00 | 100.00 |
-- | 1 | o | ref | customer_id | 10 | 8001.18 | 1.07 | 0.01 |
-- +------+-------+------+-------------+------+---------+----------+------------+
Estimated cost 0.998, actual execution time 238 ms. That is not much to worry about, but this sample is designed to be reproducible, so the query is rather simple (only two tables joined) and the dataset is not too big. Real production tables may be hundreds of times bigger, and the queries may join a lot more tables. In such cases optimizer misestimations may lead to much more serious performance problems.
ANALYZE and its advanced version ANALYZE FORMAT=JSON are very useful tools for investigating performance issues. Whenever you see that predicted rows differs significantly from the actual r_rows measured during execution (or filtered from r_filtered), it’s a clear signal that the optimizer lacks some information to make correct decisions.
Read the second line: the optimizer expected 10 orders per customer (rows) and got 8001 (r_rows) – an 800x miss. It drives the join from customers, walks 400109 index entries and throws away 99.99% of them (r_filtered).
The plan the optimizer passed over is the obvious one: start from orders, where channel='POS' selects just 10688 rows, and look up each customer by primary key. The optimizer rejected it because it expected the other plan to touch only 500 orders.
ANALYZE FORMAT=JSON prints the cost of the chosen plan, which makes the size of the mistake concrete: the cost estimate for the above plan is 0.998 and the one below at 22.3. The optimizer picked the plan it believed to be 22 times cheaper, and it turned out to be 17 times slower.
Fix 1: force the join order.
ANALYZE SELECT /*+ JOIN_PREFIX(o) */
o.id, o.created_at, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ'
AND o.channel = 'POS';
-- +------+-------+--------+---------+-------+----------+------------+
-- | id | table | type | key | rows | r_rows | r_filtered |
-- +------+-------+--------+---------+-------+----------+------------+
-- | 1 | o | ref | channel | 10688 | 10688.00 | 100.00 |
-- | 1 | c | eq_ref | country | 1 | 0.00 | 100.00 |
-- +------+-------+--------+---------+-------+----------+------------+
Estimated cost 22.3, actual execution time 13.7 ms – 17x faster.
JOIN_ORDER(o, c) does the same thing here, and reads more naturally when more than two tables are involved:
ANALYZE SELECT /*+ JOIN_ORDER(o, c) */
o.id, o.created_at, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ'
AND o.channel = 'POS';
JOIN_FIXED_ORDER() takes the order from the FROM clause (the legacy variant of the same hint is STRAIGHT_JOIN):
ANALYZE SELECT /*+ JOIN_FIXED_ORDER() */
o.id, o.created_at, o.amount
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.country = 'NZ'
AND o.channel = 'POS';
Fix 2: attack the index choice instead of the join order.
Both of these get the same good plan, and the same ~13.9 ms: once the optimizer has to reach the orders table through the channel index, driving the join from orders is the only thing left to do.
ANALYZE SELECT /*+ INDEX(o channel) */
o.id, o.created_at, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ'
AND o.channel = 'POS';
ANALYZE SELECT /*+ NO_INDEX(o customer_id) */
o.id, o.created_at, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ'
AND o.channel = 'POS';
Measuring the difference in rows touched, which is more portable than wall-clock time:
FLUSH STATUS;
ANALYZE SELECT o.id, o.amount
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ' AND o.channel = 'POS';
SHOW STATUS WHERE Variable_name LIKE 'Handler_read%' AND Value > 0;
Handler_read_key 51
Handler_read_next 400109
FLUSH STATUS;
ANALYZE SELECT /*+ JOIN_PREFIX(o) */ o.id, o.amount
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NZ' AND o.channel = 'POS';
SHOW STATUS WHERE Variable_name LIKE 'Handler_read%' AND Value > 0;
Handler_read_key 10689
Handler_read_next 10688
400109 index entries walked versus 10688, to return the same 51 rows.
Summary. Best of 3 runs, warm buffer pool, MariaDB 13.1 RelWithDebInfo.
“Time” is r_total_time_ms of the query block, from ANALYZE FORMAT=JSON.
| Hint | Est. cost | Time | Rows walked |
|---|---|---|---|
| (default plan) | 0.998 | 237.9 ms | 400109 |
| (patched with hint) | 22.286 | 13.7 ms | 10688 |
Here the optimizer is not being careless: it estimates the plan costs correctly given what it believes about the data. It believes the 50 NZ customers have 500 orders between them, while in fact they have 400059. A hint is a way of telling it so.
Example 2: the same query as a derived table. MERGE / NO_MERGE hints.
Someone wraps the POS filter in a subquery in the FROM clause, which is how this often arrives in real code – a view, an ORM, or a hand-written “filter first, then join” that the author assumed would be evaluated in that order. Returns the same 51 rows.
ANALYZE SELECT c.name, t.id, t.amount
FROM customers c
JOIN (SELECT id, customer_id, amount
FROM orders
WHERE channel = 'POS') t ON t.customer_id = c.id
WHERE c.country = 'NZ';
-- +--------+------+-------------+------+---------+------------+
-- | table | type | key | rows | r_rows | r_filtered |
-- +--------+------+-------------+------+---------+------------+
-- | c | ref | country | 50 | 50.00 | 100.00 |
-- | orders | ref | customer_id | 10 | 8001.18 | 0.01 |
-- +--------+------+-------------+------+---------+------------+
Estimated cost 1.08, actual execution time 238 ms.
The derived table has disappeared from the plan entirely. Because it is mergeable (no aggregation, no LIMIT, no UNION), it was folded into the outer query block before planning, leaving exactly the Example 1 query and exactly the Example 1 mistake. Let’s ask the optimizer not to merge the derived table t:
ANALYZE SELECT /*+ NO_MERGE(t) */
c.name, t.id, t.amount
FROM customers c
JOIN (SELECT id, customer_id, amount
FROM orders
WHERE channel = 'POS') t ON t.customer_id = c.id
WHERE c.country = 'NZ';
-- +------+-------------+------------+---------+-------+----------+
-- | id | select_type | table | key | rows | r_rows |
-- +------+-------------+------------+---------+-------+----------+
-- | 1 | PRIMARY | c | country | 50 | 50.00 |
-- | 1 | PRIMARY | <derived2> | key0 | 10 | 1.02 |
-- | 2 | DERIVED | orders | channel | 10688 | 10688.00 |
-- +------+-------------+------------+---------+-------+----------+
Actual execution time 8.8 ms – 27x faster, the best of all three examples. The 10688 POS orders are materialized once through the channel index, an automatic key (key0) is built on customer_id, and the 50 NZ customers each take one lookup into it.
Example 3: the same question as a subquery. Semijoin strategy hints.
“Which of our New Zealand customers have ever ordered through a POS terminal?” Returns 6 rows – wholesale accounts 1 to 5, and retail customer #52.
ANALYZE SELECT c.id, c.name
FROM customers c
WHERE c.country = 'NZ'
AND c.id IN (SELECT o.customer_id
FROM orders o
WHERE o.channel = 'POS');
-- +-------+------+-------------+------+---------+------------+---------------+
-- | table | type | key | rows | r_rows | r_filtered | Extra |
-- +-------+------+-------------+------+---------+------------+---------------+
-- | c | ref | country | 50 | 50.00 | 100.00 | |
-- | o | ref | customer_id | 10 | 7073.04 | 0.00 | FirstMatch(c) |
-- +-------+------+-------------+------+---------+------------+---------------+
Estimated cost 1.08, actual execution time 205 ms.
The IN is converted to a semijoin, and the optimizer chooses the FirstMatch strategy: for each NZ customer, scan its orders and stop at the first POS one. On the estimate that is 10 rows per customer. In reality 35 of the 40 NZ distributors have no POS order at all, so for each of those the execution has to walk all 10000 of its orders before it can conclude “no”. That is the 7073.04 average, and 353696 rows walked in total.
Let’s add a hint to switch the transformation strategy to MATERIALIZATION:
ANALYZE SELECT c.id, c.name
FROM customers c
WHERE c.country = 'NZ'
AND c.id IN (SELECT /*+ SEMIJOIN(MATERIALIZATION) */ o.customer_id
FROM orders o
WHERE o.channel = 'POS');
-- +------+--------------+-------------+--------------+-------+----------+
-- | id | select_type | table | key | rows | r_rows |
-- +------+--------------+-------------+--------------+-------+----------+
-- | 1 | PRIMARY | c | country | 50 | 50.00 |
-- | 1 | PRIMARY | <subquery2> | distinct_key | 1 | 0.12 |
-- | 2 | MATERIALIZED | o | channel | 10688 | 10688.00 |
-- +------+--------------+-------------+--------------+-------+----------+
Estimated cost 14.7, actual execution time 8.4 ms – 24x faster.
IMPORTANT: subquery hints go inside the subquery’s own query block, not in the outer SELECT. Use QB_NAME to refer to the block from outside.
Writing it as EXISTS gives a plan, a cost and a time identical to those of the IN form, before and after the hint – MariaDB normalizes one into the other.
ANALYZE SELECT c.id, c.name
FROM customers c
WHERE c.country = 'NZ'
AND EXISTS (SELECT /*+ SEMIJOIN(MATERIALIZATION) */ 1
FROM orders o
WHERE o.customer_id = c.id
AND o.channel = 'POS');
Conclusion
These are just a few examples of how optimizer hints can improve query performance. To learn more about hints in MariaDB, see the documentation – we hope you will find something useful there. If you encounter a bug, or would like to see a new hint implemented, feel free to file a ticket in our ticket tracker, and we’ll be happy to help.
Leave a Reply