Databases 3 min read

Mastering SQL EXPLAIN: How to Analyze and Optimize Queries

This guide explains how to use the SQL EXPLAIN statement to analyze query execution plans, detailing each output column such as id, select_type, table, possible_key, key, key_len, type, rows, and extra, and interpreting their meanings for effective optimization.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Mastering SQL EXPLAIN: How to Analyze and Optimize Queries

Usage

To analyze a SQL statement, prepend EXPLAIN to the query, e.g.,

EXPLAIN SELECT * FROM user;

Result Fields Explanation

id : Query identifier.

select_type : Type of SELECT, possible values include:

simple – no subqueries

primary – contains subqueries or derived tables

subquery – subquery not in FROM

derived – subquery in FROM

union

union result

table : Table the row refers to; can be a table name, alias, derived, or null.

possible_key : Keys that could be used.

key : Key actually used.

key_len : Length of the key (shorter is better).

type : Join type, ordered from best to worst:

system

const

eq_ref

ref

fulltext

ref_or_null

index_merge

unique_subquery

index_subquery

range

index

ALL

ALL indicates a full table scan, which is inefficient. index scans index nodes sequentially. range performs range scans. ref uses an index to locate a range. eq_ref locates a single row via index. const and system represent constant-time lookups, often seen with primary key queries.

ref : Relationship between tables in a join.

rows : Estimated number of rows examined.

extra : Additional information, such as:

using index – the query uses only the index

using where – a WHERE clause is applied

using temporary – a temporary table is created

using filesort – a filesort operation is performed

range checked for each record – each record is checked against a range

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SQLquery optimizationindexesexplain
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.