Performance Tuning

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Tuning MySQL is mostly three activities: make sure the data and the hot indexes fit in memory, choose how much durability to pay for, and remove the handful of queries that cause most of the load. This page does each against a real server and shows the measured effect. The server is mysql:latest in Docker (version 26.10.0, 10 CPUs and about 8 GB RAM available to the container) with the shop example (see Getting Started) plus a sales table with one million generated rows (about 62 MiB of data). Absolute numbers depend on the machine, the container runtime and the disk; compare the ratios, and measure on your own hardware. The query-level method is in Diagnosing slow queries, plans in Query Planning & EXPLAIN and indexes in Indexing.

flowchart TD A["Find the load: statement digests, sys views"] --> B{"Few statements dominate?"} B -- yes --> C["Fix queries and indexes (EXPLAIN)"] B -- no --> D["Look at server limits: memory, I/O, connections"] C --> E["Measure again"] D --> E E --> F{"Goal met?"} F -- no --> A F -- yes --> G["Record the change and the numbers"]

Defaults worth knowing

The values the image started with, read in one query. Most defaults are conservative and safe; the ones that most often need an explicit decision are the buffer pool, the redo log size and the connection limit.

SELECT @@innodb_buffer_pool_size/1024/1024 bp_mib, @@innodb_redo_log_capacity/1024/1024 redo_mib,
       @@innodb_flush_log_at_trx_commit, @@sync_binlog, @@innodb_flush_method,
       @@innodb_io_capacity, @@innodb_io_capacity_max, @@max_connections, @@thread_cache_size,
       @@sort_buffer_size, @@join_buffer_size, @@tmp_table_size, @@temptable_max_ram,
       @@innodb_log_buffer_size, @@innodb_dedicated_server;
bp_mib 128, redo_mib 100, innodb_flush_log_at_trx_commit 1, sync_binlog 1, innodb_flush_method O_DIRECT,
innodb_io_capacity 10000, innodb_io_capacity_max 20000, max_connections 151, thread_cache_size 9,
sort_buffer_size 262144, join_buffer_size 262144, tmp_table_size 16777216, temptable_max_ram 1073741824,
innodb_log_buffer_size 67108864, innodb_dedicated_server 0

(The one result row from the client is condensed here into name value pairs.) innodb_dedicated_server=ON lets MySQL size the buffer pool, redo log and flush method from the RAM it detects, which is a sensible starting point when the server is the only thing on the machine.

The buffer pool

InnoDB caches table and index pages in the buffer pool. When the working set fits, reads are memory reads; when it does not, every miss is a disk read. innodb_buffer_pool_size is the single most important memory setting. A common starting point is 50-75 percent of RAM on a dedicated database host; it is also why the default of 128 MiB is far too small for production.

Hit ratio

Two counters give the hit ratio: Innodb_buffer_pool_read_requests (logical reads) and Innodb_buffer_pool_reads (logical reads that had to go to disk):

SELECT ROUND(100 * (1 - (SELECT variable_value FROM performance_schema.global_status WHERE variable_name='Innodb_buffer_pool_reads')
                  / (SELECT variable_value FROM performance_schema.global_status WHERE variable_name='Innodb_buffer_pool_read_requests')), 3) AS hit_ratio_pct;
SELECT object_name, allocated, data, pages FROM sys.innodb_buffer_stats_by_table WHERE object_schema='shop' LIMIT 4;
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_pages_%';
+---------------+
| hit_ratio_pct |
+---------------+
|        99.976 |
+---------------+
+-------------+------------+------------+-------+
| object_name | allocated  | data       | pages |
+-------------+------------+------------+-------+
| sales       | 56.61 MiB  | 51.96 MiB  |  3623 |
| t_dur       | 352.00 KiB | 293.26 KiB |    22 |
+-------------+------------+------------+-------+
Innodb_buffer_pool_pages_data    7182
Innodb_buffer_pool_pages_free    1010
Innodb_buffer_pool_pages_total   8192

A ratio above 99 percent is healthy for an OLTP workload; what matters is the trend and the absolute number of misses, not the percentage alone. The hit ratio hides a problem when the pages that are cached are the wrong ones (a one-off table scan evicting hot pages; InnoDB’s midpoint insertion mitigates this). sys.innodb_buffer_stats_by_table shows which objects occupy the pool.

Resizing it online

The pool can be resized while the server runs, in multiples of innodb_buffer_pool_chunk_size (128 MiB here). It cannot go below one chunk: asking for 32 MiB was ignored with Size did not change (old size = new size = 134217728. Nothing to do.

SET GLOBAL innodb_buffer_pool_size = 536870912;
SHOW STATUS LIKE 'Innodb_buffer_pool_resize_status';
SELECT @@innodb_buffer_pool_size/1048576 AS pool_mib, @@innodb_buffer_pool_chunk_size/1048576 chunk_mib;
| Innodb_buffer_pool_resize_status | Completed resizing buffer pool at 261110 19:31:51. |
| pool_mib | chunk_mib |
| 512.0000 |  128.0000 |

With a table larger than the pool (sales_wide, four million rows, 246 MiB) a repeated full scan was run at 128 MiB and again at 512 MiB:

SELECT SUM(amount) FROM sales_wide WHERE note LIKE '%99%';   -- warm up, then measure the second run
Pool Time (ms) Disk reads Logical reads

128 MiB

409

516

38,663

512 MiB

369

0

25,940

The effect on time is small here because the container’s disk is fast and the scan reads sequentially with read-ahead (read-ahead reads are not counted in Innodb_buffer_pool_reads); on spinning disks, network storage or random access the difference grows by orders of magnitude. The 0 disk reads is the number to look for. Several buffer pool instances (innodb_buffer_pool_instances) reduce mutex contention on big pools with many cores.

Redo log and durability

Every committed change is written to the redo log before it is acknowledged, and the data pages themselves are flushed later by checkpointing. The redo log’s total size is innodb_redo_log_capacity and it is dynamic:

SET GLOBAL innodb_redo_log_capacity = 1073741824;
SHOW STATUS LIKE 'Innodb_redo_log_resize_status';
SELECT file_name, start_lsn, end_lsn FROM performance_schema.innodb_redo_log_files;
| Innodb_redo_log_resize_status | OK |
| ./#innodb_redo/#ib_redo39 | 127723520 | 130998272 |

Too small a redo log forces frequent checkpoints and can stall writers. The error log of this server recorded the symptom during a heavy rebuild with the default 100 MiB: Redo log writer is waiting for a new redo log file. Consider increasing innodb_redo_log_capacity (warning MY-014089) and Threads are unable to reserve space in redo log (MY-014084), the latter also during the one-million-row load below. The load itself took about 2.0 seconds at both 100 MiB and 1 GiB here, so the larger log only matters for sustained or bursty write loads, and the warnings are what to monitor. Size it so that checkpointing never stalls writers under your peak write load; compare Innodb_redo_log_checkpoint_lsn with Innodb_redo_log_current_lsn over time to see how much of the log is in use.

Flushing the log: durability against speed

Two settings decide when a commit is safe on disk:

  • innodb_flush_log_at_trx_commit controls the redo log: 1 (default) writes and flushes to disk at each commit; 2 writes to the operating system at each commit and flushes about once a second; 0 writes and flushes about once a second. With 2 a crash of the operating system or the machine can lose up to a second of committed transactions (a mysqld crash alone does not); with 0 a mysqld crash can too.

  • sync_binlog controls the binary log: 1 (default) flushes it to disk at each commit group; 0 leaves it to the operating system.

With both at 1 each commit performs a synchronous flush for the redo log and the binary log, which is fully durable and the slowest. A stored procedure inserted 3,000 rows one autocommit transaction at a time under each combination:

SET GLOBAL innodb_flush_log_at_trx_commit = 1; SET GLOBAL sync_binlog = 1;
SET @t = NOW(6); CALL ins_n(3000);
SELECT ROUND(3000/(TIMESTAMPDIFF(MICROSECOND,@t,NOW(6))/1000000)) AS commits_per_sec;
Setting Commits per second Lost on OS crash

innodb_flush_log_at_trx_commit=1, sync_binlog=1

1,842

nothing

innodb_flush_log_at_trx_commit=1, sync_binlog=0

10,338

last binary log events, not the data

innodb_flush_log_at_trx_commit=2, sync_binlog=0

67,568

up to about 1 second of commits

innodb_flush_log_at_trx_commit=0, sync_binlog=0

96,463

up to about 1 second of commits

The loop uses a stored procedure, so the per-commit client round trip is excluded; real applications see smaller ratios. The point is the order of magnitude between a synchronous flush at every commit and none. The right setting is a business decision: keep both at 1 for money and orders; consider relaxed settings for a replica (it can be rebuilt from its source), a staging or analytics copy, or a bulk load that can be redone. With sync_binlog=0 a source crash can leave replicas or a recovery with a binary log that is behind the data, so do not relax it on a source whose binary log feeds replication or point-in-time recovery. Group commit batches the flushes of concurrent transactions, which is why throughput under many concurrent connections is far better than the single-session figure above.

flowchart LR C["COMMIT"] --> LB["Redo log buffer"] LB -->|"trx_commit=1: write and fsync"| RL["Redo log on disk"] LB -->|"trx_commit=2: write, fsync each second"| OS["OS cache"] C --> BL["Binary log"] BL -->|"sync_binlog=1: fsync"| BD["Binary log on disk"] RL -.->|"checkpoint"| DP["Data pages"]

Other I/O settings: innodb_flush_method is O_DIRECT here, bypassing the operating system cache for data files (the buffer pool is the cache), which avoids double buffering and is the usual choice on Linux. innodb_io_capacity (10000) and innodb_io_capacity_max (20000) tell the background flushing how much I/O the storage can take; set them from the real IOPS of your disks, not higher. innodb_doublewrite protects against torn pages and should stay on; the redo log buffer (innodb_log_buffer_size, 64 MiB) rarely needs changing.

Connections

Each connection is a thread with its own buffers. max_connections (151) is the ceiling, and hitting it makes new clients fail. Reproducing it with the limit lowered to 2 and two sessions of an unprivileged account sleeping:

SET GLOBAL max_connections = 2;
$ mysql -utuner -p... -e 'SELECT 1'
ERROR 1040 (08004): Too many connections
Connection_errors_max_connections  1
Max_used_connections               3

(Max_used_connections reached 3 because accounts with the CONNECTION_ADMIN privilege are allowed one extra connection beyond the limit, so an administrator can still log in to fix the situation.) Look at the usage with these counters:

SHOW GLOBAL STATUS LIKE 'Max_used_connections';
SHOW GLOBAL STATUS LIKE 'Connections';
SHOW GLOBAL STATUS LIKE 'Threads_created';
SELECT ROUND(100 * (SELECT variable_value FROM performance_schema.global_status WHERE variable_name='Threads_created')
                 / (SELECT variable_value FROM performance_schema.global_status WHERE variable_name='Connections'), 2) AS thread_miss_pct;
Max_used_connections 1, Connections 43, Threads_created 1, thread_miss_pct 2.33

thread_cache_size keeps finished connection threads for reuse, so a low Threads_created relative to Connections means the cache is doing its job. Raising max_connections is not a cure for connection storms: thousands of mostly idle threads cost memory and cause contention. Put a pool in the application (the usual fix), and for many application instances a proxy such as ProxySQL or MySQL Router to multiplex connections to a smaller number of server sessions. Keep slow queries and idle-in-transaction sessions in check, since they hold connections and locks.

Per-session buffers and temporary tables

Some memory is allocated per session or per query, so a large value multiplied by many connections is a way to run out of memory. Set them modestly globally and raise them per session for the one query that needs it.

sort_buffer_size

A sort that does not fit in sort_buffer_size spills to temporary files and merges them in passes. Sort_merge_passes counts the passes. Sorting a million rows of the four-million-row sales_wide:

SELECT note FROM sales_wide ORDER BY note DESC LIMIT 5 OFFSET 1000000;
SHOW SESSION STATUS WHERE variable_name IN ('Sort_merge_passes','Sort_rows','Created_tmp_files');
sort_buffer_size Time (ms) Sort_merge_passes Created_tmp_files

262144 (default, 256 KiB)

764

194

4

268435456 (256 MiB, session only)

556

1

2

A large buffer is not free: it is allocated per sort. Prefer an index that provides the order (see Indexing) so there is nothing to sort. The join_buffer_size setting (also 256 KiB) works the same way for joins that cannot use an index (block nested loop and hash joins) and is also allocated per join; fix the missing index rather than growing it.

Temporary tables

GROUP BY, DISTINCT, UNION and some sorts use internal temporary tables, held in memory by the TempTable engine until they exceed tmp_table_size (16 MiB), after which they go to disk. Created_tmp_disk_tables counts the spills. A high-cardinality aggregate over the million-row sales table:

EXPLAIN FORMAT=TREE SELECT note, COUNT(*) FROM sales GROUP BY note ORDER BY COUNT(*) DESC LIMIT 3;
SELECT note, COUNT(*) c FROM sales GROUP BY note ORDER BY c DESC LIMIT 1;
SHOW SESSION STATUS LIKE 'Created_tmp%';
-> Limit: 3 row(s)
    -> Sort: COUNT(*) DESC, limit input to 3 row(s) per chunk
        -> Table scan on <temporary>
            -> Aggregate using temporary table
                -> Table scan on sales  (cost=102299 rows=996113)
Session setting Time (ms) Created_tmp_disk_tables

tmp_table_size 16 MiB (default)

3021

1

tmp_table_size and max_heap_table_size 1 GiB

475

0

The spilled version took six times as long. As with the sort buffer, the better fix is usually a query or index change (aggregate fewer rows, add a covering index so the grouping is satisfied from the index), and a larger tmp_table_size only where the temporary results are legitimately big. sys.statements_with_temp_tables lists the statements that create them, with their disk counts.

A tuning workflow with performance_schema and sys

Start from measurements: what is the server spending time on? The sys schema answers this directly (details in Administration). On the sales table four indexes were added (idx_cust on customer_id, idx_cust_sku on customer_id, sku, idx_created on created_at and idx_note on note), the digest statistics were cleared, and a small workload ran:

SELECT COUNT(*) FROM sales WHERE customer_id = 'c-1' AND sku = 'A-2';
SELECT COUNT(*), SUM(amount) FROM sales WHERE sku = 'B-7';
SELECT COUNT(*) FROM sales WHERE sku = 'C-3';
SELECT COUNT(*) FROM sales WHERE amount > 450;
SELECT COUNT(*) FROM sales WHERE created_at >= '2024-06-01' AND created_at < '2024-06-02';

Step 1: which statements scan whole tables?

SELECT LEFT(query, 70) AS query, db, exec_count, total_latency, no_index_used_count, rows_examined_avg
FROM sys.statements_with_full_table_scans WHERE db='shop' ORDER BY total_latency DESC LIMIT 5;
+-------------------------------------------------------------------+------+------------+---------------+---------------------+-------------------+
| query                                                             | db   | exec_count | total_latency | no_index_used_count | rows_examined_avg |
+-------------------------------------------------------------------+------+------------+---------------+---------------------+-------------------+
| SELECT COUNT ( * ) , SUM ( `am ... ) FROM `sales` WHERE `sku` = ? | shop |          1 | 71.59 ms      |                   1 |           1000000 |
| SELECT COUNT ( * ) FROM `sales` WHERE `amount` > ?                | shop |          1 | 60.52 ms      |                   1 |           1000000 |
| SELECT LEFT ( QUERY , ? ) AS Q ... ull_table_scans` ) `t` LIMIT ? | shop |          1 | 1.68 ms       |                   1 |                 9 |
+-------------------------------------------------------------------+------+------------+---------------+---------------------+-------------------+

The two real findings: sku = ? alone scans a million rows because sku is only the second column of idx_cust_sku and cannot be used on its own, and amount > ? has no index at all. (The third row is the tuning query itself.) The fix is a decision about the workload: an index on sku (or sku, amount) if these queries are frequent, a different query otherwise.

Step 2: which indexes are never used, or redundant?

SELECT * FROM sys.schema_unused_indexes WHERE object_schema='shop';
SELECT table_name, redundant_index_name, redundant_index_columns, dominant_index_name, dominant_index_columns
FROM sys.schema_redundant_indexes WHERE table_schema='shop';
SELECT table_name, index_name, rows_selected, select_latency FROM sys.schema_index_statistics
WHERE table_schema='shop' AND table_name='sales' ORDER BY rows_selected DESC;
+---------------+-------------+--------------------+
| object_schema | object_name | index_name         |
+---------------+-------------+--------------------+
| shop          | order_items | fk_items_product   |
| shop          | orders      | fk_orders_customer |
| shop          | sales       | idx_cust           |
| shop          | sales       | idx_note           |
+---------------+-------------+--------------------+
+------------+----------------------+-------------------------+---------------------+------------------------+
| table_name | redundant_index_name | redundant_index_columns | dominant_index_name | dominant_index_columns |
+------------+----------------------+-------------------------+---------------------+------------------------+
| sales      | idx_cust             | customer_id             | idx_cust_sku        | customer_id,sku        |
+------------+----------------------+-------------------------+---------------------+------------------------+
+------------+--------------+---------------+----------------+
| table_name | index_name   | rows_selected | select_latency |
+------------+--------------+---------------+----------------+
| sales      | idx_cust_sku |       1250005 | 170.15 ms      |
| sales      | idx_created  |          2787 | 202.71 us      |
| sales      | PRIMARY      |             0 |   0 ps         |
| sales      | idx_cust     |             0 |   0 ps         |
| sales      | idx_note     |             0 |   0 ps         |
+------------+--------------+---------------+----------------+

idx_cust is redundant (the prefix of idx_cust_sku serves the same lookups) and idx_note was never used; both cost write time and memory and are candidates for DROP INDEX (or ALTER INDEX ... INVISIBLE first, to test safely). Foreign-key indexes show up as unused only because no workload touched them; do not drop those on that evidence alone, and judge unused-ness over a full business cycle, since the counters restart at server start.

Step 3: change one thing, measure again. Re-run the workload, compare the digest figures, keep a record. Make one change at a time so the effect can be attributed.

Partitioning

Partitioning splits one table into several physical pieces by a rule on a column. Its main benefits are pruning (queries restricted on the partition key read only the relevant pieces) and cheap data lifecycle (dropping an old partition is instant, where deleting millions of rows is not). It is not a general speed-up and does not replace indexes. In InnoDB every unique key, including the primary key, must contain the partition column, so created_at joins the primary key here. Foreign keys are not supported on partitioned tables.

CREATE TABLE sales_part (
  id int NOT NULL, customer_id varchar(10) NOT NULL, sku varchar(10) NOT NULL,
  amount decimal(10,2) NOT NULL, created_at datetime NOT NULL, note varchar(60) NOT NULL,
  PRIMARY KEY (id, created_at)
)
PARTITION BY RANGE COLUMNS (created_at) (
  PARTITION p2024q1 VALUES LESS THAN ('2024-04-01'),
  PARTITION p2024q2 VALUES LESS THAN ('2024-07-01'),
  PARTITION p2024q3 VALUES LESS THAN ('2024-10-01'),
  PARTITION p2024q4 VALUES LESS THAN ('2025-01-01'),
  PARTITION pmax    VALUES LESS THAN (MAXVALUE)
);
INSERT INTO sales_part SELECT * FROM sales;
SELECT partition_name, table_rows FROM information_schema.partitions
WHERE table_schema='shop' AND table_name='sales_part' ORDER BY partition_ordinal_position;
| p2024q1 | 253625 |
| p2024q2 | 252984 |
| p2024q3 | 256413 |
| p2024q4 | 236336 |
| pmax    |      0 |

The partitions column of the traditional EXPLAIN shows which partitions are read. (This server’s default explain_format is TREE, which names the partitions inside its text; FORMAT=TRADITIONAL shows the column.) A query on one month reads one partition, a query on another column reads all of them:

EXPLAIN FORMAT=TRADITIONAL SELECT COUNT(*) FROM sales_part WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01';
EXPLAIN FORMAT=TRADITIONAL SELECT COUNT(*) FROM sales_part WHERE customer_id = 'c-1';
EXPLAIN SELECT COUNT(*) FROM sales_part WHERE DATE(created_at) = '2024-05-01';
| id | select_type | table      | partitions                           | type  | key     | rows   | Extra                    |
|  1 | SIMPLE      | sales_part | p2024q2                              | index | PRIMARY | 252984 | Using where; Using index |
|  1 | SIMPLE      | sales_part | p2024q1,p2024q2,p2024q3,p2024q4,pmax | ALL   | NULL    | 999358 | Using where              |

-> Filter: (cast(sales_part.created_at as date) = '2024-05-01')  (cost=100202 rows=999358)
    -> Covering index scan on sales_part using PRIMARY in partitions (p2024q1,p2024q2,p2024q3,p2024q4,pmax)

(Some columns omitted.) The first query touches 1 of 5 partitions. The second cannot prune: its predicate is on another column, so all five are read. The third wraps the partition column in a function (DATE(created_at)), which defeats pruning, so write range predicates on the bare column. Maintenance operations act on one partition at a time:

ALTER TABLE sales_part DROP PARTITION p2024q1;
SELECT COUNT(*) FROM sales_part;
ALTER TABLE sales_part REORGANIZE PARTITION pmax INTO
  (PARTITION p2025q1 VALUES LESS THAN ('2025-04-01'), PARTITION pmax VALUES LESS THAN (MAXVALUE));
| COUNT(*) |
|   746375 |
partitions now: p2024q2, p2024q3, p2024q4, p2025q1, pmax

Dropping p2024q1 removed 253,625 rows immediately (1,000,000 - 746,375), with no row-by-row delete. List partitioning assigns rows by explicit values, and a value without a partition is an error, not a silent default:

CREATE TABLE sales_region (id int NOT NULL, region varchar(10) NOT NULL, amount decimal(10,2),
  PRIMARY KEY (id, region))
PARTITION BY LIST COLUMNS (region) (PARTITION p_eu VALUES IN ('uk','de','fi'), PARTITION p_us VALUES IN ('us','ca'));
INSERT INTO sales_region VALUES (4,'jp',1);
EXPLAIN FORMAT=TRADITIONAL SELECT * FROM sales_region WHERE region='us';
ERROR 1526 (HY000): Table has no partition for value from column_list
| id | select_type | table        | partitions | type | rows | Extra       |
|  1 | SIMPLE      | sales_region | p_us       | ALL  |    1 | Using where |

Use partitioning for large time-series tables with a retention policy, and always check with EXPLAIN that the queries prune. Many partitions have a cost of their own (open files, metadata), so keep the count in the tens or low hundreds.

Bulk loading

How data gets in matters more than any setting. The same 20,000 rows (exported from sales) were loaded into an empty table four ways, timed from the shell, which includes the client start-up and docker exec overhead, so the ratios understate the server-side difference:

Method Time Rows per second

single-row INSERT statements, autocommit

12.64 s

about 1,600

single-row INSERT statements in one transaction

0.77 s

about 26,000

multi-row INSERT (500 rows per statement), one transaction

0.13 s

about 150,000

LOAD DATA INFILE

0.10 s

about 200,000

The ranking is the point. Each autocommit statement pays a durable commit (the innodb_flush_log_at_trx_commit=1 cost from above), which batching in a transaction removes; multi-row inserts also cut parse and round-trip overhead, and LOAD DATA skips the SQL layer per row.

-- server-side file, readable only from the directory in secure_file_priv (/var/lib/mysql-files/ here)
SELECT id, customer_id, sku, amount, created_at, note FROM sales WHERE id <= 20000
  INTO OUTFILE '/var/lib/mysql-files/bulk20k.tsv';
LOAD DATA INFILE '/var/lib/mysql-files/bulk20k.tsv' INTO TABLE bulk_t;

LOAD DATA LOCAL INFILE reads the file from the client instead and needs local_infile enabled on both sides (it is 0 on this server, because it is a security risk: a malicious server can ask a client for arbitrary files). For a large initial load: load in primary-key order, create secondary indexes after the data (or rely on ALTER TABLE ... ADD INDEX online, which builds them in a sorted bulk pass), keep transactions to a size the redo log handles (tens of thousands to a million rows, not the whole load), and consider relaxing innodb_flush_log_at_trx_commit and sync_binlog only for the duration of a load that can simply be redone. MySQL Shell util.importTable() and util.loadDump() load in parallel (see Backup & Restore).

Schema design hints

  • Use the smallest data type that fits (int rather than bigint where the range allows, decimal(10,2) for money, datetime or timestamp rather than strings). Smaller rows put more rows in each page and more pages in the buffer pool. See Data Types & MySQL-specific SQL.

  • Keep the primary key short and stable. InnoDB stores each row in the primary key’s B-tree and copies the primary key into every secondary index, so a long key (a long string, a random UUID) bloats everything. Prefer an increasing key for insert locality.

  • Index for the query, not for the column. Composite indexes serve the leftmost prefix only, as the sku example above shows; one good composite index beats several single-column ones (see Indexing).

  • Avoid SELECT * on wide tables; JSON, TEXT and BLOB columns are stored off-page and cost extra reads when fetched.

  • Normalise first (Normalization); denormalise deliberately, with a measured reason.

  • Paginate with keyset conditions for deep pages: see Pagination strategies.

  • Archive or partition old data so the working set stays small.

Back to the MySQL Reference; for a one-page summary of the commands used here see the Cheat Sheet.