Analyzing and optimizing MariaDB slow queries with ChatGPT

KI-Buster Blog · Databases & AI

Analyze and Optimize MariaDB Slow Queries with ChatGPT: Finding Real Performance Bottlenecks

A website suddenly feels noticeably slower, a dashboard takes forever, and the database CPU is running hot – but often the cause isn't MariaDB itself, it's a handful of inefficient SQL queries. This practical guide shows how to systematically find and safely fix slow queries using the MariaDB slow query log, EXPLAIN/ANALYZE, and ChatGPT.

Published on November 3, 2026

A website that used to load in half a second suddenly takes five seconds. A dashboard takes forever to show its data. Your database server's CPU is running at full tilt, even though nothing changed on the hardware side.

The first suspect: MariaDB is too slow.

But often the problem isn't the database software itself. A handful of inefficient SQL queries can scan thousands of rows unnecessarily, do full table scans, or sort huge amounts of data.

This is exactly where ChatGPT becomes useful.

With the MariaDB slow query log, the SQL execution plan, and a targeted AI analysis, you can investigate performance problems systematically – without immediately buying more RAM, extra CPU cores, or a new server.

In this practical guide you'll learn how to identify slow MariaDB queries, use ChatGPT sensibly for root-cause analysis, and verify optimizations in a controlled way.

1. What are slow queries in MariaDB?

A slow query is a SQL query whose execution takes longer than a defined threshold.

MariaDB can log such queries automatically. This is what's known as the slow query log.

An example:

SELECT *
FROM orders
WHERE customer_id = 1542
ORDER BY created_at DESC;

On a table with 100 rows, this query is probably unproblematic.

With five million orders, the same query can take considerably longer – especially if a suitable index is missing. MariaDB may have to examine a very large number of rows and then sort them.

That doesn't mean every slow query is badly written, though. Locks, high server load, slow storage, or an unfavorable cache situation can also affect runtime.

How do you recognize problematic SQL queries?

Typical signs include:

  • High execution times for what should be simple queries
  • A very high ratio of examined rows to returned rows
  • Frequent full table scans
  • Expensive sort operations
  • Missing or unsuitable indexes
  • Nearly identical queries executed repeatedly
  • Long waits caused by locks

Queries that individually take only a few milliseconds but run several thousand times per minute are especially critical.

Keep in mind: It's not just the single slowest query that matters. Often, the most frequently executed inefficient query causes the largest overall load.

2. Enabling the MariaDB slow query log

Before ChatGPT can analyze anything, we need solid data. The slow query log is one of the most important sources of that data.

Step 1: Check the current configuration

Connect to your MariaDB instance:

mariadb -u root -p

Then check the relevant settings:

SHOW GLOBAL VARIABLES
WHERE Variable_name IN (
'slow_query_log',
'slow_query_log_file',
'long_query_time',
'log_output',
'log_queries_not_using_indexes'
);

On newer MariaDB versions, variables with the log_slow_query prefix may be relevant in addition to, or instead of, these. Always check the documentation for the server version you're actually running.

Step 2: Turn on the slow query log at runtime

On MariaDB versions that support the classic variable names:

SET GLOBAL slow_query_log = ON;
SET GLOBAL long_query_time = 1;

This enables logging and sets the global threshold to one second.

Important: Existing database sessions may keep using their previous session value for long_query_time. For reproducible tests, open a new connection or explicitly set the session value.

SET SESSION long_query_time = 1;

So the global value alone doesn't guarantee that every already-running application session is immediately logged with the new threshold.

Step 3: Check the log file

SHOW GLOBAL VARIABLES
LIKE 'slow_query_log_file';

On Linux you can then watch the file:

sudo tail -f /var/log/mysql/mariadb-slow.log

The path is an example. Use the location actually configured on your system.

Step 4: Make the configuration permanent

Depending on your distribution and MariaDB version, you can store the settings in a file under /etc/mysql/mariadb.conf.d/, for example. For versions with the classic parameters:

[mariadb]
slow_query_log = 1
long_query_time = 1
log_output = FILE

On current versions, the corresponding log_slow_query parameters need to be considered instead.

Changes to the configuration file usually only take effect after the service restarts. For a production database server, you shouldn't force a restart just for an initial slow-query analysis.

Practical tip: On a heavily loaded production system, start with a moderate threshold. Very low values can generate huge log volumes and extra I/O.

3. Understanding the slow query log: these values matter

A typical entry can look something like this, simplified:

# Query_time: 4.823
# Lock_time: 0.002
# Rows_sent: 25
# Rows_examined: 1854200

SELECT *
FROM orders
WHERE customer_id = 1542
ORDER BY created_at DESC
LIMIT 25;

The four most important pieces of information:

Slow query log metrics and what they mean
MetricMeaning
Query_timeTotal query duration in seconds
Lock_timeLogged wait time for certain locks
Rows_sentNumber of rows returned
Rows_examinedNumber of rows examined

Something stands out immediately here: in this example, the database examines more than 74,000 rows for every row it returns (1,854,200 examined versus 25 returned).

That's a clear sign the query deserves closer inspection. It isn't proof of a missing index by itself, though. Data selectivity, sorting, and the actual execution plan all play a role too.

4. Analyzing slow queries with ChatGPT

This is where ChatGPT comes in. Instead of rewriting SQL queries on a hunch, you can use the AI to investigate possible causes in a structured way.

The most important principle here: ChatGPT provides hypotheses and optimization suggestions. MariaDB provides the measurements you use to verify them.

Example: a good prompt for slow-query analysis

You are an experienced MariaDB database administrator and SQL performance expert.

Analyze the following slow SQL query using the slow query log and the EXPLAIN execution plan.

Tasks:
1. Identify possible performance causes.
2. Check whether existing indexes are used sensibly.
3. Suggest suitable index or SQL optimizations.
4. Explain possible side effects on INSERT, UPDATE, DELETE, and storage requirements.
5. Provide concrete SQL commands for testing.
6. Describe how the optimization should be measured before and after the change.
7. Explicitly flag assumptions and missing information.

Important: Do not recommend unverified changes for the production system.

MariaDB version: [VERSION]
Table definition and indexes: [SHOW CREATE TABLE]
Slow query log: [ANONYMIZED LOG EXCERPT]
EXPLAIN: [EXECUTION PLAN]

This prompt is far more useful than a simple question like "Why is my database slow?". It forces the analysis to take the available information into account, surface assumptions explicitly, and make changes measurable.

What data should you give ChatGPT?

For a meaningful analysis, these are especially useful:

  • Anonymized slow query log excerpts
  • The affected SQL query
  • SHOW CREATE TABLE for the tables involved
  • Existing indexes
  • EXPLAIN or ANALYZE results
  • Approximate table and data sizes
  • MariaDB version and relevant server settings

A note on privacy: SQL logs can contain customer names, email addresses, tokens, and other sensitive information. Only use data you're actually allowed to send to the chosen AI service under your organization's privacy and data policies.

5. EXPLAIN: finding out what MariaDB is really doing

The most important next step is examining the execution plan. EXPLAIN shows which access path MariaDB is likely to use for a query.

EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 1542
ORDER BY created_at DESC
LIMIT 25;

A simplified result might look like this:

Simplified EXPLAIN output without a suitable index
FieldExample value
typeALL
possible_keysNULL
keyNULL
rows1854200
ExtraUsing where; Using filesort

This output is a warning sign: type = ALL means MariaDB is planning a full table scan. key = NULL shows that no index is being used for this access. Using filesort means an additional sort operation is required – though that doesn't necessarily mean it's actually writing to disk.

EXPLAIN FORMAT=JSON

For a more detailed analysis you can also use the JSON output:

EXPLAIN FORMAT=JSON
SELECT *
FROM orders
WHERE customer_id = 1542
ORDER BY created_at DESC
LIMIT 25;

This structured output is particularly well suited for ChatGPT, since it can include additional information on access paths, join processing, and estimated costs.

ANALYZE instead of just EXPLAIN

MariaDB also offers:

ANALYZE FORMAT=JSON
SELECT *
FROM orders
WHERE customer_id = 1542
ORDER BY created_at DESC
LIMIT 25;

Unlike EXPLAIN, this actually runs the query, so real runtime information and additional measurements are captured.

Important: Don't use ANALYZE carelessly on expensive queries or write statements. The analysis does real database work and can create significant load for unsuitable queries.

6. Practical example: optimizing a slow SQL query step by step

Let's assume an application manages several million orders. The following query runs frequently:

SELECT id, order_number, total_amount
FROM orders
WHERE customer_id = 1542
ORDER BY created_at DESC
LIMIT 25;

Without a suitable index, MariaDB may have to search large parts of the table.

Solution: consider a composite index

One possible optimization:

CREATE INDEX idx_orders_customer_date
ON orders (customer_id, created_at);

Why this column order? The query first filters by customer_id and then sorts by created_at. A composite index can support both requirements.

Instead of examining every order, MariaDB can ideally jump straight to the relevant part of the index and read the needed entries in the right order. Whether that actually happens is shown only by the new execution plan.

Before-and-after comparison

The following table shows a purely hypothetical, illustrative result – not a measured benchmark.

Illustrative example: effect of a suitable index
MetricBeforeAfter
Query time4.82 s0.03 s
Rows examined1,854,20025
Access typeALLref/range
Extra sortYesNo

Improvements like this are possible, but by no means guaranteed. The actual effect depends on data distribution, existing indexes, query frequency, and system load, among other things.

Additional indexes also need storage space and can slow down write operations. That's why every index recommendation should include a review of its side effects.

7. Analyzing large slow query logs automatically

On a heavily used database server, thousands or even millions of log entries can accumulate every day. Pasting all of that into ChatGPT wouldn't be practical or efficient.

It's better to first group the queries and sort them by relevance.

Using mariadb-dumpslow

MariaDB ships the mariadb-dumpslow tool for this (the older name mysqldumpslow still works too).

The ten queries with the highest average runtime:

mariadb-dumpslow -s at -t 10 \
/var/log/mysql/mariadb-slow.log

The ten most frequently logged query patterns:

mariadb-dumpslow -s c -t 10 \
/var/log/mysql/mariadb-slow.log

The queries with the most rows examined in total:

mariadb-dumpslow -s ae -t 10 \
/var/log/mysql/mariadb-slow.log

The tool groups similar queries together and typically abstracts away concrete numbers and literal strings. That creates a much more compact dataset for the AI analysis.

Which queries should you optimize first?

The single slowest query isn't necessarily the biggest problem. An example:

Example: total load of three different queries
QueryCalls/dayAverageTotal time
A108 s80 s
B20,0000.2 s4,000 s
C100,0000.05 s5,000 s

Even though query A takes the longest individually, B and C cause a much higher cumulative execution time. Note that total time is the sum of individual runtimes, not automatically the time you'd save on the server. Parallel execution and different resource loads need to be taken into account.

A good prioritization therefore considers frequency, total runtime, rows examined, and the business importance of each query.

8. Five typical SQL performance problems ChatGPT can spot

Problem 1: SELECT * loads unnecessary data

SELECT *
FROM customers
WHERE status = 'active';

If only the name and email address are needed, the following query is often better:

SELECT name, email
FROM customers
WHERE status = 'active';

This transfers fewer columns. Depending on the index, MariaDB may even be able to serve the query entirely from an index.

Problem 2: Functions block efficient index use

SELECT *
FROM orders
WHERE YEAR(created_at) = 2026;

A possible alternative:

SELECT *
FROM orders
WHERE created_at >= '2026-01-01'
AND created_at < '2027-01-01';

With a suitable index, this form often enables a more efficient range access. Whether MariaDB already optimizes the original form also depends on the version in use.

Problem 3: An unsuitable index

A single index on customer_id doesn't optimally support every combination of filtering and sorting. For frequently used queries, a composite index can make sense. What matters is the order of the columns, their selectivity, and the actual query pattern.

Problem 4: Unnecessarily large JOIN operations

SELECT c.name, o.order_number
FROM customers c
JOIN orders o
ON c.id = o.customer_id
WHERE c.status = 'active';

For large tables, check whether the join columns are properly indexed and how MariaDB actually joins the tables. An index on orders.customer_id can help, but it's no blanket guarantee.

Problem 5: OFFSET on large datasets

SELECT *
FROM orders
ORDER BY id
LIMIT 25 OFFSET 500000;

MariaDB may have to step through a very large number of entries before reaching the 25 rows you actually want. For sequential page navigation, keyset pagination can be a better fit:

SELECT *
FROM orders
WHERE id > 500000
ORDER BY id
LIMIT 25;

Here, 500000 must be the ID of the last row on the previous page – not the number of rows to skip. This technique is especially suited to next/previous navigation, not as a direct replacement for arbitrary page numbers.

9. ChatGPT as an ongoing performance assistant

ChatGPT's biggest strength isn't suggesting a single index. It gets interesting once you bring several pieces of information together: slow query log, SQL execution plans, MariaDB status variables, table structure, index definitions, and changes after a deployment.

ChatGPT can draw possible connections from that and put together a structured investigation plan.

A complete analysis workflow

  1. Capture slow queries: Collect representative logs during both normal and elevated load.
  2. Group queries: Use mariadb-dumpslow to identify frequent, resource-intensive SQL patterns.
  3. Get execution plans: Run EXPLAIN FORMAT=JSON and examine the indexes used.
  4. Have ChatGPT analyze it: Work out possible causes, index suggestions, and alternative SQL queries.
  5. Verify in a test environment: Apply changes one at a time and check SQL results for equivalence.
  6. Compare performance: Measure runtimes, row counts, execution plans, and the impact on write operations.
  7. Roll out in a controlled way: Move changes into production with a backup, rollback plan, and monitoring in place.

This workflow also works well for recurring performance reviews. A key benefit: the optimization becomes documented and traceable.

10. Optimizing MariaDB without endangering production

On a database with many concurrent connections, caution matters more than making the fastest possible change.

A CREATE INDEX on a very large table can cause extra CPU, memory, and I/O load. Depending on the MariaDB version, table structure, and DDL method used, locks can also occur. That's why you shouldn't apply index changes to a production system without proper verification.

Check before every change

  • Does an index that already serves the same purpose exist?
  • How large is the affected table?
  • What effect does the new index have on write operations?
  • Does the MariaDB version in use support a suitable online DDL method?
  • Is there a current, verified backup and a practical way back?
  • Has the change succeeded in a comparable test environment?

For online DDL there are options such as ALGORITHM and LOCK, among others. Which combination is actually supported depends on the specific operation and version.

It's also important that a transaction can't simply roll back a DDL statement like CREATE INDEX. A rollback plan therefore needs to explicitly cover undoing the schema change.

11. Slow queries aren't always an index problem

A slow query can also be caused by other bottlenecks. For example:

Possible causes beyond missing indexes
CausePossible investigation
High CPU loadCheck CPU utilization and parallel queries
Slow storageMeasure I/O latency and IOPS
Lock contentionInvestigate InnoDB transactions and lock wait times
Stale optimizer statisticsCompare statistics with the actual data distribution
Too many parallel queriesAnalyze connections, threads, and application load
Memory pressureCheck buffer pool usage and memory pressure

Useful SQL commands include, for example:

SHOW GLOBAL STATUS LIKE 'Threads_running';
SHOW GLOBAL STATUS LIKE 'Slow_queries';
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_reads';

For a current view of running queries:

SHOW FULL PROCESSLIST;

And to inspect InnoDB's state:

SHOW ENGINE INNODB STATUS\G

These snapshots should ideally be supplemented with continuous monitoring. For sporadic problems especially, single status queries are often not enough.

A bigger buffer pool, more RAM, or a higher maximum connection count is no substitute for a clean SQL analysis.

12. Privacy: can I upload production MariaDB logs to ChatGPT?

That depends on the data they contain, your contractual terms, the ChatGPT environment you're using, and your organization's internal policies.

Slow query logs can contain complete SQL statements and therefore personal or confidential values. MariaDB's documentation explicitly notes that slow query logs can contain sensitive content and need to be protected accordingly.

Before transferring log files to an external AI service, check whether that transfer is actually permitted. For the technical analysis, anonymized SQL queries, execution plans, and abstracted statistics are often enough.

Example:

SELECT *
FROM customers
WHERE email = 'customer@example.com';

Better:

SELECT *
FROM customers
WHERE email = '<ANONYMIZED_EMAIL>';

For a real performance investigation, also make sure the replacement values share similar properties with the original data. Different selectivity can lead to different execution plans.

If even anonymized data can't be processed externally, a locally run AI model may be an option. For help weighing cloud versus local AI, see Which AI Should Companies Use? Cloud, Local or Hybrid? (Read article).

13. Checklist: optimizing MariaDB slow queries systematically

  • Checked MariaDB version and slow-log variables
  • Enabled the slow query log with a suitable threshold
  • Collected and anonymized representative log data
  • Prioritized queries by frequency and total load
  • Examined EXPLAIN and, where useful, ANALYZE output
  • Took existing indexes and table structures into account
  • Checked ChatGPT's suggestions for plausibility
  • Measured changes in a test environment
  • Considered write load, locks, and storage requirements
  • Prepared a rollback plan and set up monitoring

Frequently Asked Questions (FAQ)

How do I find slow SQL queries in MariaDB?

Enable the MariaDB slow query log and set a suitable threshold. You can then use mariadb-dumpslow to identify particularly slow or frequently executed queries.

Can ChatGPT automatically optimize SQL queries?

ChatGPT can analyze SQL queries, spot likely issues, and suggest optimized variants. Whether they're actually faster has to be verified with MariaDB execution plans and reproducible measurements.

What is the difference between EXPLAIN and ANALYZE?

EXPLAIN shows the planned execution path of a SQL query. ANALYZE additionally runs the query and returns actual execution statistics, letting you compare the optimizer's estimates with real measurements.

What is a sensible value for long_query_time?

It depends on the application. One second is a reasonable starting point. For latency-critical applications, lower values can make sense. Under high load, the extra logging volume should also be considered.

Should every slow SQL query get its own index?

No. Every additional index needs storage space and adds maintenance overhead for write operations. Indexes should be planned based on actual query patterns and the existing index set.

Can I analyze slow queries without a restart?

Yes. Many relevant logging settings can be changed while the server is running. However, with existing database sessions and different MariaDB versions, the respective scope of each setting must be taken into account.

Is ChatGPT suitable for analyzing production databases?

Yes, as a supporting analysis tool. The database itself remains the authoritative source for measurements and execution plans. Production changes must still be reviewed and approved by responsible administrators.

Conclusion: ChatGPT helps with root-cause analysis – MariaDB provides the evidence

MariaDB performance problems are rarely solved by a single configuration parameter. More often it's inefficient SQL queries, missing or unsuitable indexes, poor execution plans, or too many concurrent database operations that slow a system down.

The slow query log, mariadb-dumpslow, EXPLAIN, and ANALYZE already provide powerful tools. ChatGPT complements them by making technical information easier to understand, structuring possible causes, and suggesting alternative solutions.

The most important rule: don't optimize on a hunch – measure, analyze, change something specific, and measure again. Following this approach lets you speed up MariaDB databases sustainably, without taking unnecessary risks in production.

Related Articles on KI-Buster

Debug HAProxy Errors with ChatGPT: Logs, Backends, and Timeouts (Read article)

Debug Docker Compose Errors with ChatGPT: A Systematic Approach (Read article)

Analyze Apache and Nginx Logs with ChatGPT: Spot Errors, Bots, and Attacks Faster (Read article)

Which AI Should Companies Use? Cloud, Local or Hybrid? (Read article)

Sources and Technical References

The following official MariaDB documentation was used to verify version-dependent commands and diagnostic procedures:

MariaDB: Slow Query Log

MariaDB: mariadb-dumpslow

MariaDB: EXPLAIN FORMAT=JSON

MariaDB: ANALYZE FORMAT=JSON

Editorial note: All SQL examples were created for demonstration purposes. Performance figures in the example are illustrative, not measured benchmarks. Before production use, review the MariaDB version, table structure, and the impact on the running system. Editorial currency: November 3, 2026.