Query tuning in MariaDB is the process of analyzing and rewriting SQL, indexing, and configuring the server to reduce execution time and resource usage.
Long execution times usually stem from missing indexes, poor query structure, or insufficient buffer sizes. Begin by capturing the execution plan with EXPLAIN
or ANALYZE
to see table scans and join methods.
EXPLAIN
shows how the optimizer intends to execute a statement. Use it before a SELECT, UPDATE, or DELETE to reveal access types, key usage, and estimated rows.
EXPLAIN [EXTENDED] [FORMAT=JSON] your_query;
EXPLAIN FORMAT=JSON
SELECT c.name, SUM(o.total_amount) AS lifetime_value
FROM Customers c
JOIN Orders o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY lifetime_value DESC
LIMIT 10;
Look for "type: ALL" or high "rows" counts in EXPLAIN output. Add composite indexes that match the WHERE, JOIN, and ORDER BY columns in left-to-right order.
CREATE INDEX index_name
ON table_name (col1, col2 [, col3 ...]);
CREATE INDEX idx_orders_customer_date
ON Orders (customer_id, order_date);
Eliminate SELECT *
, move non-sargable functions out of WHERE, and avoid correlated subqueries. Use derived tables or common table expressions (CTEs) for complex aggregations.
Tune innodb_buffer_pool_size
, join_buffer_size
, and query_cache_type
(if using MariaDB <10.1). Monitor with SHOW STATUS LIKE 'Handler%';
and adjust iteratively.
Use covering indexes, keep transactions short, analyze slow logs, avoid wildcard prefixes in LIKE clauses, and regularly update statistics with ANALYZE TABLE
.
Yes. Unlike EXPLAIN, ANALYZE FORMAT=JSON SELECT ...
executes the statement and returns real runtime statistics, making it ideal for fine-grained tuning on a staging copy.
Enable slow_query_log
and set long_query_time
. Review mysqldumpslow
output or use Percona Toolkit's pt-query-digest
for aggregated insights.
The query cache is deprecated and often causes contention. Prefer proper indexing and application-level caching. If you must use it on older versions, keep it small and monitor hit ratios.