Чтение вывода EXPLAIN и EXPLAIN ANALYZE
Расшифруйте планы запросов PostgreSQL с помощью EXPLAIN, чтобы увидеть, как планировщик выполняет запрос и куда на самом деле уходит время
«Чтение вывода EXPLAIN и EXPLAIN ANALYZE» — бесплатный урок PostgreSQL Performance & Query Optimization на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения PostgreSQL Performance & Query Optimization, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс PostgreSQL Performance & Query Optimization содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Read Query Plans
Before tuning a slow query, see what PostgreSQL actually does. EXPLAIN shows the planner's chosen execution plan as a tree of nodes.
EXPLAIN vs EXPLAIN ANALYZE
EXPLAIN shows estimates only; EXPLAIN ANALYZE actually runs the query and reports real timings and row counts — far more useful for diagnosis.
EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42;The Plan Tree
Read plan trees inside-out and bottom-up: leaf nodes scan data, parents join or aggregate. Each node reports its cost, rows, and width.
The cost Numbers
The cost reads as cost=0.00..18.45: first is startup cost, second is total, both in arbitrary planner units used to compare competing plans.
Sequential Scan
A Seq Scan reads the whole table — fine for small tables or when most rows match, but a red flag on a selective query over a large one.
Index Scan
An Index Scan uses an index to find matching rows, then fetches them from the table. It's the win for selective predicates.
Estimated vs Actual Rows
Compare estimated rows with actual rows. A big mismatch means stale statistics and often a bad plan — run ANALYZE to refresh them, as shown below.
ANALYZE orders;Spotting the Bottleneck
To find the bottleneck, hunt for the node with the largest actual time, or one whose loops multiply its cost. That's where to focus tuning.
BUFFERS for I/O Insight
Add BUFFERS to your EXPLAIN to see how many pages came from cache versus disk — the fast way to spot I/O-bound queries. See the example below.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE total > 100;Join Strategies
Watch the join strategy: Nested Loop, Hash Join, or Merge Join. A Nested Loop over many rows without an index is a classic slow pattern.
Readable Formats
For big plans, switch to FORMAT JSON or a visual tool to explore them more easily. The query below shows the JSON option.
EXPLAIN (ANALYZE, FORMAT JSON)
SELECT * FROM orders;Quick Check
Test what you have learned.
Recap
Recap: read EXPLAIN trees, compare estimates with ANALYZE actuals, tell Seq from Index scans and join types, use BUFFERS, and find the bottleneck node.
Часто задаваемые вопросы
Урок «Чтение вывода EXPLAIN и EXPLAIN ANALYZE» бесплатный?
Да — полный текст урока «Чтение вывода EXPLAIN и EXPLAIN ANALYZE» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс PostgreSQL Performance & Query Optimization, подпишись на CoddyKit PRO. Курс PostgreSQL Performance & Query Optimization содержит 4 уроков всего.
Чему я научусь в уроке «Чтение вывода EXPLAIN и EXPLAIN ANALYZE»?
Расшифруйте планы запросов PostgreSQL с помощью EXPLAIN, чтобы увидеть, как планировщик выполняет запрос и куда на самом деле уходит время Ты практикуешь PostgreSQL Performance & Query Optimization с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать PostgreSQL Performance & Query Optimization?
Предыдущий опыт не требуется. PostgreSQL Performance & Query Optimization на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Чтение вывода EXPLAIN и EXPLAIN ANALYZE»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке PostgreSQL Performance & Query Optimization?
Да. Каждый урок PostgreSQL Performance & Query Optimization включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Основы производительности баз данных
- Обзор архитектуры PostgreSQL
- Основы выполнения запросов
- Чтение вывода EXPLAIN и EXPLAIN ANALYZE