// troubleshooting guide

Using temporary in MySQL plans

MySQL builds an internal temporary table when it cannot group, de-duplicate or order rows as it reads them. How to see it in EXPLAIN, tell whether the table went to disk, and remove it with an index.

Covers MySQL

The symptom

Using temporary 에서 Extra column of EXPLAIN means MySQL will build an internal temporary table to answer the query. It does that for GROUP BY 그리고 DISTINCT when the rows do not arrive already grouped, for UNION, for some derived tables, and for an ORDER BY on columns of a table other than the first one joined. Together with Using filesort it means the temporary table is also sorted afterwards.

A small temporary table in memory costs little. It gets expensive when it holds many rows or outgrows its memory limit and moves to disk. The query plan viewer points out temporary tables in MySQL and MariaDB plans. The examples use a shop schema with 400,000 orders.

Diagnose it

Find the temporary table in the plan

EXPLAIN SELECT status, COUNT(*) FROM orders GROUP BY status\G
 type: ALL
  key: NULL
 rows: 399054
Extra: Using temporary

The tree format says what the table is for:

EXPLAIN FORMAT=TREE SELECT status, COUNT(*) FROM orders GROUP BY status;

EXPLAIN FORMAT=TREE SELECT DISTINCT customer_id FROM orders;
-> Table scan on <temporary>
    -> Aggregate using temporary table
        -> Table scan on orders  (cost=40266 rows=399054)
-> Table scan on <temporary>  (cost=80172..85162 rows=399054)
    -> Temporary table with deduplication  (cost=80172..80172 rows=399054)
        -> Table scan on orders  (cost=40266 rows=399054)

Aggregate using temporary table keeps one row per group and updates it as rows are read. Temporary table with deduplication keeps one row per distinct value. In both, the size of the temporary table is the number of groups, not the number of rows read.

Check whether it went to disk

Two session counters tell you: Created_tmp_tables counts internal temporary tables, Created_tmp_disk_tables counts the ones that were moved to disk. This query has 400,000 groups:

SET SESSION tmp_table_size = 16 * 1024 * 1024;
FLUSH STATUS;

SELECT reference, COUNT(*) FROM orders
GROUP BY reference ORDER BY COUNT(*) DESC LIMIT 1;

SHOW SESSION STATUS LIKE 'Created_tmp%tables';
| Created_tmp_disk_tables | 1     |
| Created_tmp_tables      | 1     |

The same counters with SHOW GLOBAL STATUS give the ratio for the whole server since it started.

Fix it

Add an index on the grouping columns

If an index stores the rows in GROUP BY order, MySQL reads the index and finishes each group as it passes; no temporary table is needed:

CREATE INDEX orders_status_idx ON orders (status);

EXPLAIN SELECT status, COUNT(*) FROM orders GROUP BY status\G
 type: index
  key: orders_status_idx
 rows: 399054
Extra: Using index

When the query also filters, put the equality filter columns first and the grouping columns after them, the same rule as for an index that avoids a sort.

Group and order by columns of one table

In a join, ORDER BY 또는 GROUP BY on a column of a table that is not read first forces MySQL to collect the joined rows in a temporary table before it can order them. If the same result can be grouped by a column of the driving table (for example its key instead of a column from the joined table), the temporary table goes away. Check the join order in EXPLAIN: the first row is the table read first.

Reduce what goes into the table

Filter before grouping, and keep wide columns out of the grouped result. Fetch long text columns in an outer query that joins back on the key after the grouping is done.

Raise the in-memory limit for the session

When the temporary table is legitimate but spills to disk, give it more memory for that session:

SET SESSION tmp_table_size = 256 * 1024 * 1024;
FLUSH STATUS;

SELECT reference, COUNT(*) FROM orders
GROUP BY reference ORDER BY COUNT(*) DESC LIMIT 1;

SHOW SESSION STATUS LIKE 'Created_tmp%tables';
| Created_tmp_disk_tables | 0     |
| Created_tmp_tables      | 1     |

The settings involved are tmp_table_size, the per-table limit, and temptable_max_ram, the total for all sessions. max_heap_table_size also applies when the server uses the MEMORY engine for internal tables.

When to leave it alone

Leave it when the number of groups is small: a temporary table with five rows, one per status, is not what makes a query slow, even if reading 400,000 rows to fill it is. In that case the scan is the cost, and the fix is a filter or a better access path. UNION 없이 ALL always uses a temporary table to remove duplicates; use UNION ALL when duplicates are impossible or acceptable.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Find Using temporary in the Extra column and identify what needs it: GROUP BY, DISTINCT, UNION or ORDER BY.
  2. Estimate the number of groups or distinct values, which is the size of the temporary table.
  3. Check Created_tmp_disk_tables to see whether it went to disk.
  4. Try an index on the filter columns followed by the grouping columns.
  5. In joins, group and order by columns of the first table read.
  6. Raise tmp_table_size for the session only when the table is needed and too big for memory.

Questions that come up

What does Using temporary mean in MySQL EXPLAIN?

MySQL will create an internal temporary table to hold intermediate results, most often for GROUP BY, DISTINCT or UNION, or to sort a join result. The table is created and dropped automatically within the query.

Is Using temporary always bad?

No. The cost depends on how many rows the temporary table holds and whether it fits in memory. A handful of groups is cheap. Hundreds of thousands of groups, or a table that moves to disk, is where the time goes.

What does Using temporary; Using filesort mean?

The query builds a temporary table and then sorts it. It is typical of GROUP BY followed by ORDER BY on an aggregate, such as ordering groups by their count, and of ordering a join by a column that does not come from the first table.

How do I know if a temporary table went to disk?

Compare the status counters Created_tmp_disk_tables and Created_tmp_tables before and after the query in your session. If the disk counter increased, the table exceeded its memory limit and was converted to an on-disk table.

Does UNION use a temporary table?

UNION does, because it has to remove duplicate rows. UNION ALL returns rows as they come and in most cases needs no temporary table, so prefer it whenever duplicates cannot occur or do not matter.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.