PostgreSQL Foundations·A database you can operate

Performance basics

Read query plans with EXPLAIN ANALYZE and add the indexes and maintenance your queries need.

Intermediate 13 min read Lesson 5 of 300 Challenge included
What you will be able to do
  • Read a plan with explain analyze.
  • Tell a sequential scan from an index scan.
  • Add an index to remove a full scan.
  • Run vacuum and analyze to keep the planner accurate.

In plain English

EXPLAIN ANALYZE is a statement that runs your query and prints a plan showing what the database actually did and how long it took. A sequential scan reads every row in a table, while an index scan uses an index, a sorted lookup structure, to jump straight to the matching rows. A missing index means the database has no shortcut for your query, so it falls back to reading everything. VACUUM reclaims space from deleted rows and keeps tables healthy, while ANALYZE refreshes the statistics the planner uses to choose a good plan.

Step by step

  1. 1Run explain analyze in front of your query to see its plan.
  2. 2Look for a Seq Scan, which means every row is being read.
  3. 3Create an index on the columns in your where clause.
  4. 4Run analyze so the planner knows about your data.
  5. 5Run vacuum to reclaim space from deleted and updated rows.
explain.sqlSQL
create table lessons (
  id integer generated always as identity primary key,
  course_id integer not null,
  title text not null
);

explain analyze
select title
from lessons
where course_id = 7;

create index lessons_course_idx on lessons (course_id);

analyze lessons;

vacuum lessons;

Common mistakes

  • Reading a plan from EXPLAIN without ANALYZE can mislead you, because the row estimates are guesses until the query actually runs.
  • Adding an index to a column no query filters on wastes storage and slows every insert.
  • Skipping vacuum lets dead rows pile up and tables bloat, which makes scans slower.
  • Assuming an index always wins is wrong, because on small tables a sequential scan is often cheaper.
Your turn

Find a missing index

Easy

A query filters lessons by course_id and its plan shows a Seq Scan. Write the index that turns it into an index scan.

SQL · starter
explain analyze
select title
from lessons
where course_id = 7;
Check your understanding before moving on.
Knowledge checkQuestion 1

What does a sequential scan do?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 5 of 300 · 0% of course