100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Database

The Query Planner and Cost Estimation

Understand how PostgreSQL's planner generates candidate execution plans and estimates their cost so it can pick the cheapest one.

Query PlanningAdvanced10 min readJul 10, 2026
Analogies

What the Planner Actually Does

For every SQL statement, PostgreSQL's planner enumerates multiple candidate execution strategies, such as scanning a table sequentially versus via an index, or joining two tables with a hash join versus a nested loop, and assigns each candidate an estimated cost. It then picks the plan with the lowest estimated total cost, not necessarily the plan that is actually fastest, because the choice depends entirely on how accurate the underlying statistics and cost model assumptions are for that specific query and data distribution.

🏏

Cricket analogy: A team selector weighs multiple possible playing XIs for a Wankhede pitch, spinner-heavy versus pace-heavy, and picks the combination projected to concede the fewest runs, just as the planner picks the plan with the lowest projected cost.

The Cost Model: seq_page_cost, random_page_cost, and cpu_tuple_cost

The planner's cost formula combines a handful of tunable GUCs: seq_page_cost (default 1.0) models reading one sequential 8KB page, random_page_cost (default 4.0) models reading one page via a non-sequential access pattern such as an index lookup, and cpu_tuple_cost, cpu_index_tuple_cost, and cpu_operator_cost model per-row and per-operation CPU work. On modern SSD-backed systems, random access is nowhere near four times as expensive as sequential access, so lowering random_page_cost toward 1.1-2.0 is a common, well-justified tuning step that makes the planner favor index scans more realistically.

🏏

Cricket analogy: Assuming a spinner always costs four times more runs per over than a pacer on any pitch, even a raging turner at Chepauk, is like leaving random_page_cost at its default 4.0 on fast SSD storage where random access is nearly as cheap as sequential.

How Statistics Drive Selectivity Estimates

ANALYZE (run automatically by autovacuum's analyze threshold, or manually) samples table rows to build pg_statistic entries: most-common-value lists with frequencies, histogram boundaries for the rest of the distribution, and n_distinct estimates. The planner uses these to estimate selectivity, the fraction of rows a WHERE clause will match, and multiplies that fraction by table row count to get an estimated row count for each node; when a predicate involves correlated columns the default assumption of independence between columns can produce badly wrong selectivity unless extended statistics (CREATE STATISTICS) are defined.

🏏

Cricket analogy: A team's scouting report on a batsman's dismissal patterns against left-arm spin, built from sampled match footage, is like pg_statistic's histograms, and assuming that batsman's shot selection is unrelated to the match situation, when it clearly is, mirrors the planner's flawed independence assumption.

sql
-- Inspect the planner's current cost settings
SHOW seq_page_cost;
SHOW random_page_cost;
SHOW cpu_tuple_cost;

-- A common, well-justified tuning step on SSD-backed systems
ALTER SYSTEM SET random_page_cost = 1.1;
SELECT pg_reload_conf();

-- Refresh statistics for a table after bulk load
ANALYZE VERBOSE orders;

-- Create extended statistics when the planner misjudges correlated columns
CREATE STATISTICS orders_country_region_stats (dependencies)
  ON country, region FROM orders;
ANALYZE orders;

You can inspect the raw statistics the planner relies on directly: SELECT * FROM pg_stats WHERE tablename = 'orders' AND attname = 'order_date';. This shows most_common_vals, most_common_freqs, and histogram_bounds, the exact inputs feeding selectivity estimation.

When the Planner Gets It Wrong

Even a perfectly accurate cost model can produce a bad real-world plan when default_statistics_target is too low for a skewed column, when a query uses a function on an indexed column without a matching expression index, or when correlated predicates across columns are assumed independent. In these cases the fix is rarely to fight the planner with query hints, which PostgreSQL deliberately does not support; instead you refresh statistics with ANALYZE, raise default_statistics_target for that column, add extended statistics, or restructure the predicate so the planner's model actually applies.

🏏

Cricket analogy: A captain who keeps setting an off-side field because that is what the coaching manual says, ignoring that this particular batsman is a strong leg-side player, is like a planner using a stale or too-coarse statistics target for a skewed column.

PostgreSQL intentionally has no query hint syntax like some other databases. Attempts to 'force' a plan (disabling enable_seqscan globally, for example) are session-wide, blunt instruments meant for diagnosis only, never for permanent production tuning; fix the underlying statistics or indexing instead.

  • The planner enumerates candidate plans and picks the one with the lowest estimated cost, not necessarily the actual fastest plan.
  • seq_page_cost, random_page_cost, and cpu_tuple_cost are the core tunable GUCs behind every cost calculation.
  • random_page_cost's default of 4.0 reflects spinning-disk seek penalties and is usually too high for SSD-backed systems.
  • Selectivity estimates come from pg_statistic entries built by ANALYZE: most-common-values, histograms, and n_distinct.
  • The planner assumes independence between columns by default, which breaks down for correlated predicates unless extended statistics are created.
  • default_statistics_target controls histogram/MCV granularity per column and can be raised for skewed columns.
  • PostgreSQL has no query hints; fix bad plans via ANALYZE, statistics targets, extended statistics, or indexing, not by forcing plan shapes.

Practice what you learned

Was this page helpful?

Topics covered

#Database#PostgreSQLAdvancedStudyNotes#TheQueryPlannerAndCostEstimation#Query#Planner#Cost#Estimation#SQL#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse