TigerData logo
TigerData logo
  • Product

    Tiger Cloud

    Robust elastic cloud platform for startups and enterprises

    Agentic Postgres

    Postgres for Agents

    TimescaleDB

    Postgres for time-series, real-time analytics and events

  • Docs
  • Pricing

    Pricing

    Enterprise Tier

  • Developer Hub

    Changelog

    Benchmarks

    Blog

    Community

    Customer Stories

    Events

    Support

    Integrations

    Launch Hub

  • Company

    Contact us

    About

    Timescale

    Partners

    Security

    Careers

Log InTry for free
Home
AWS Time-Series Database: Understanding Your OptionsStationary Time-Series AnalysisThe Best Time-Series Databases ComparedTime-Series Analysis and Forecasting With Python Alternatives to TimescaleWhat Are Open-Source Time-Series Databases—Understanding Your OptionsWhy Consider Using PostgreSQL for Time-Series Data?Time-Series Analysis in RWhat Is Temporal Data?What Is a Time Series and How Is It Used?Is Your Data Time Series? Data Types Supported by PostgreSQL and TimescaleUnderstanding Database Workloads: Variable, Bursty, and Uniform PatternsHow to Work With Time Series in Python?Tools for Working With Time-Series Analysis in PythonGuide to Time-Series Analysis in PythonUnderstanding Autoregressive Time-Series ModelingCreating a Fast Time-Series Graph With Postgres Materialized Views
Understanding PostgreSQLOptimizing Your Database: A Deep Dive into PostgreSQL Data TypesUnderstanding FROM in PostgreSQL (With Examples)How to Address ‘Error: Could Not Resize Shared Memory Segment’ How to Install PostgreSQL on MacOSUnderstanding FILTER in PostgreSQL (With Examples)Understanding GROUP BY in PostgreSQL (With Examples)PostgreSQL Join Type TheoryA Guide to PostgreSQL ViewsStructured vs. Semi-Structured vs. Unstructured Data in PostgreSQLUnderstanding Foreign Keys in PostgreSQLUnderstanding PostgreSQL User-Defined FunctionsUnderstanding PostgreSQL's COALESCE FunctionUnderstanding SQL Aggregate FunctionsUsing PostgreSQL UPDATE With JOINHow to Install PostgreSQL on Linux5 Common Connection Errors in PostgreSQL and How to Solve ThemUnderstanding HAVING in PostgreSQL (With Examples)How to Fix No Partition of Relation Found for Row in Postgres DatabasesHow to Fix Transaction ID Wraparound ExhaustionUnderstanding LIMIT in PostgreSQL (With Examples)Understanding PostgreSQL FunctionsUnderstanding ORDER BY in PostgreSQL (With Examples)Understanding WINDOW in PostgreSQL (With Examples)Understanding PostgreSQL WITHIN GROUPPostgreSQL Mathematical Functions: Enhancing Coding EfficiencyUnderstanding DISTINCT in PostgreSQL (With Examples)Using PostgreSQL String Functions for Improved Data AnalysisData Processing With PostgreSQL Window FunctionsPostgreSQL Joins : A SummaryUnderstanding OFFSET in PostgreSQL (With Examples)Understanding PostgreSQL Date and Time FunctionsWhat Is Data Compression and How Does It Work?What Is Data Transformation, and Why Is It Important?Understanding the Postgres string_agg FunctionWhat Is a PostgreSQL Left Join? And a Right Join?Understanding PostgreSQL SELECTSelf-Hosted or Cloud Database? A Countryside Reflection on Infrastructure ChoicesUnderstanding ACID Compliance Understanding percentile_cont() and percentile_disc() in PostgreSQLUnderstanding PostgreSQL Conditional FunctionsUnderstanding PostgreSQL Array FunctionsWhat Characters Are Allowed in PostgreSQL Strings?Understanding WHERE in PostgreSQL (With Examples)What Is a PostgreSQL Full Outer Join?What Is a PostgreSQL Cross Join?What Is a PostgreSQL Inner Join?Data Partitioning: What It Is and Why It MattersStrategies for Improving Postgres JOIN PerformanceUnderstanding the Postgres extract() FunctionUnderstanding the rank() and dense_rank() Functions in PostgreSQL
Guide to PostgreSQL PerformanceHow to Reduce Bloat in Large PostgreSQL TablesDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables A Guide to Data Analysis on PostgreSQLA Guide to Scaling PostgreSQLGuide to PostgreSQL SecurityHandling Large Objects in PostgresHow to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Use PostgreSQL for Data TransformationOptimizing Array Queries With GIN Indexes in PostgreSQLPg_partman vs. Hypertables for Postgres PartitioningPostgreSQL Performance Tuning: Designing and Implementing Your Database SchemaPostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesDetermining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)Top PostgreSQL Drivers for PythonWhen to Consider Postgres PartitioningGuide to PostgreSQL Database OperationsUnderstanding PostgreSQL TablespacesWhat Is Audit Logging and How to Enable It in PostgreSQLGuide to Postgres Data ManagementHow to Index JSONB Columns in PostgreSQLHow to Monitor and Optimize PostgreSQL Index PerformanceSQL/JSON Data Model and JSON in SQL: A PostgreSQL PerspectiveA Guide to pg_restore (and pg_restore Example)PostgreSQL Performance Tuning: How to Size Your DatabaseAn Intro to Data Modeling on PostgreSQLExplaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?A PostgreSQL Database Replication GuideHow to Compute Standard Deviation With PostgreSQLHow PostgreSQL Data Aggregation WorksBuilding a Scalable DatabaseRecursive Query in SQL: What It Is, and How to Write OneGuide to PostgreSQL Database DesignHow to Use Psycopg2: The PostgreSQL Adapter for Python
Best Practices for Scaling PostgreSQLHow to Design Your PostgreSQL Database: Two Schema ExamplesHow to Handle High-Cardinality Data in PostgreSQLHow to Store Video in PostgreSQL Using BYTEABest Practices for PostgreSQL Database OperationsHow to Manage Your Data With Data Retention PoliciesBest Practices for PostgreSQL AggregationBest Practices for Postgres Database ReplicationHow to Use a Common Table Expression (CTE) in SQLBest Practices for Postgres Data ManagementBest Practices for Postgres PerformanceBest Practices for Postgres SecurityBest Practices for PostgreSQL Data AnalysisTesting Postgres Ingest: INSERT vs. Batch INSERT vs. COPYHow to Use PostgreSQL for Data Normalization
PostgreSQL Extensions: amcheckPostgreSQL Extensions: Unlocking Multidimensional Points With Cube PostgreSQL Extensions: hstorePostgreSQL Extensions: ltreePostgreSQL Extensions: Secure Your Time-Series Data With pgcryptoPostgreSQL Extensions: pg_prewarmPostgreSQL Extensions: pgRoutingPostgreSQL Extensions: pg_stat_statementsPostgreSQL Extensions: Install pg_trgm for Data MatchingPostgreSQL Extensions: Turning PostgreSQL Into a Vector Database With pgvectorPostgreSQL Extensions: Database Testing With pgTAPPostgreSQL Extensions: PL/pgSQLPostgreSQL Extensions: Using PostGIS and Timescale for Advanced Geospatial InsightsPostgreSQL Extensions: Intro to uuid-ossp
Columnar Databases vs. Row-Oriented Databases: Which to Choose?Data Analytics vs. Real-Time Analytics: How to Pick Your Database (and Why It Should Be PostgreSQL)How to Choose a Real-Time Analytics DatabaseUnderstanding OLTPOLAP Workloads on PostgreSQL: A GuideHow to Choose an OLAP DatabasePostgreSQL as a Real-Time Analytics DatabaseWhat Is the Best Database for Real-Time AnalyticsHow to Build an IoT Pipeline for Real-Time Analytics in PostgreSQL
When Should You Use Full-Text Search vs. Vector Search?HNSW vs. DiskANNA Brief History of AI: How Did We Get Here, and What's Next?A Beginner’s Guide to Vector EmbeddingsPostgreSQL as a Vector Database: A Pgvector TutorialUsing Pgvector With PythonHow to Choose a Vector DatabaseVector Databases Are the Wrong AbstractionUnderstanding DiskANNA Guide to Cosine SimilarityStreaming DiskANN: How We Made PostgreSQL as Fast as Pinecone for Vector DataImplementing Cosine Similarity in PythonVector Database Basics: HNSWVector Database Options for AWSVector Store vs. Vector Database: Understanding the ConnectionPgvector vs. Pinecone: Vector Database Performance and Cost ComparisonHow to Build LLM Applications With Pgvector Vector Store in LangChainHow to Implement RAG With Amazon Bedrock and LangChainRetrieval-Augmented Generation With Claude Sonnet 3.5 and PgvectorRAG Is More Than Just Vector SearchPostgreSQL Hybrid Search Using Pgvector and CohereImplementing Filtered Semantic Search Using Pgvector and JavaScriptRefining Vector Search Queries With Time Filters in Pgvector: A TutorialUnderstanding Semantic SearchWhat Is Vector Search? Vector Search vs Semantic SearchText-to-SQL: A Developer’s Zero-to-Hero GuideNearest Neighbor Indexes: What Are IVFFlat Indexes in Pgvector and How Do They WorkBuilding an AI Image Gallery With OpenAI CLIP, Claude Sonnet 3.5, and Pgvector
Understanding IoT (Internet of Things)A Beginner’s Guide to IIoT and Industry 4.0Storing IoT Data: 8 Reasons Why You Should Use PostgreSQLMoving Past Legacy Systems: Data Historian vs. Time-Series DatabaseWhy You Should Use PostgreSQL for Industrial IoT DataHow to Choose an IoT DatabaseHow to Simulate a Basic IoT Sensor Dataset on PostgreSQLFrom Ingest to Insights in Milliseconds: Everactive's Tech Transformation With TimescaleHow Ndustrial Is Providing Fast Real-Time Queries and Safely Storing Client Data With 97 % CompressionHow Hopthru Powers Real-Time Transit Analytics From a 1 TB Table Migrating a Low-Code IoT Platform Storing 20M Records/DayHow United Manufacturing Hub Is Introducing Open Source to ManufacturingBuilding IoT Pipelines for Faster Analytics With IoT CoreVisualizing IoT Data at Scale With Hopara and TimescaleDB
What Is ClickHouse and How Does It Compare to PostgreSQL and TimescaleDB for Time Series?Timescale vs. Amazon RDS PostgreSQL: Up to 350x Faster Queries, 44 % Faster Ingest, 95 % Storage Savings for Time-Series DataWhat We Learned From Benchmarking Amazon Aurora PostgreSQL ServerlessTimescaleDB vs. Amazon Timestream: 6,000x Higher Inserts, 5-175x Faster Queries, 150-220x CheaperHow to Store Time-Series Data in MongoDB and Why That’s a Bad IdeaPostgreSQL + TimescaleDB: 1,000x Faster Queries, 90 % Data Compression, and Much MoreEye or the Tiger: Benchmarking Cassandra vs. TimescaleDB for Time-Series Data
Alternatives to RDSWhy Is RDS so Expensive? Understanding RDS Pricing and CostsEstimating RDS CostsHow to Migrate From AWS RDS for PostgreSQL to TimescaleAmazon Aurora vs. RDS: Understanding the Difference
5 InfluxDB Alternatives for Your Time-Series Data8 Reasons to Choose Timescale as Your InfluxDB Alternative InfluxQL, Flux, and SQL: Which Query Language Is Best? (With Cheatsheet)What InfluxDB Got WrongTimescaleDB vs. InfluxDB: Purpose Built Differently for Time-Series Data
5 Ways to Monitor Your PostgreSQL DatabaseHow to Migrate Your Data to Timescale (3 Ways)Postgres TOAST vs. Timescale CompressionBuilding Python Apps With PostgreSQL: A Developer's GuideData Visualization in PostgreSQL With Apache SupersetMore Time-Series Data Analysis, Fewer Lines of Code: Meet HyperfunctionsIs Postgres Partitioning Really That Hard? An Introduction To HypertablesPostgreSQL Materialized Views and Where to Find ThemTimescale Tips: Testing Your Chunk Size
Postgres cheat sheet
HomeTime series basicsPostgres basicsPostgres guidesPostgres best practicesPostgres extensionsPostgres for real-time analytics
Sections

Postgres overview

Understanding PostgreSQLOptimizing Your Database: A Deep Dive into PostgreSQL Data Types

Postgres errors

How to Address ‘Error: Could Not Resize Shared Memory Segment’ 5 Common Connection Errors in PostgreSQL and How to Solve ThemHow to Fix No Partition of Relation Found for Row in Postgres DatabasesHow to Fix Transaction ID Wraparound Exhaustion

Install postgres

How to Install PostgreSQL on LinuxHow to Install PostgreSQL on MacOS

Postgres clauses

Understanding FROM in PostgreSQL (With Examples)Understanding FILTER in PostgreSQL (With Examples)Understanding HAVING in PostgreSQL (With Examples)Understanding GROUP BY in PostgreSQL (With Examples)Understanding LIMIT in PostgreSQL (With Examples)Understanding ORDER BY in PostgreSQL (With Examples)Understanding WINDOW in PostgreSQL (With Examples)Understanding PostgreSQL WITHIN GROUPUnderstanding DISTINCT in PostgreSQL (With Examples)Understanding WHERE in PostgreSQL (With Examples)Understanding OFFSET in PostgreSQL (With Examples)

Postgres joins

PostgreSQL Joins : A SummaryWhat Is a PostgreSQL Full Outer Join?What Is a PostgreSQL Cross Join?What Is a PostgreSQL Inner Join?What Is a PostgreSQL Left Join? And a Right Join?PostgreSQL Join Type TheoryStrategies for Improving Postgres JOIN Performance

Postgres operations

A Guide to PostgreSQL ViewsData Partitioning: What It Is and Why It MattersWhat Is Data Compression and How Does It Work?Self-Hosted or Cloud Database? A Countryside Reflection on Infrastructure Choices

More

Understanding ACID Compliance Structured vs. Semi-Structured vs. Unstructured Data in PostgreSQLUnderstanding Foreign Keys in PostgreSQL

Postgres functions

Understanding PostgreSQL FunctionsPostgreSQL Mathematical Functions: Enhancing Coding EfficiencyUsing PostgreSQL String Functions for Improved Data AnalysisData Processing With PostgreSQL Window FunctionsUnderstanding PostgreSQL Date and Time FunctionsUnderstanding the Postgres string_agg FunctionUnderstanding PostgreSQL User-Defined FunctionsUnderstanding PostgreSQL's COALESCE FunctionUnderstanding SQL Aggregate FunctionsUnderstanding percentile_cont() and percentile_disc() in PostgreSQLUnderstanding PostgreSQL Conditional FunctionsUnderstanding PostgreSQL Array FunctionsUnderstanding the Postgres extract() FunctionUnderstanding the rank() and dense_rank() Functions in PostgreSQL

Postgres statements

Understanding PostgreSQL SELECTUsing PostgreSQL UPDATE With JOINWhat Characters Are Allowed in PostgreSQL Strings?

Data analysis

What Is Data Transformation, and Why Is It Important?

Products

Time Series and Analytics AI and Vector Enterprise Plan Cloud Status Support Security Cloud Terms of Service

Learn

Documentation Blog Forum Tutorials Changelog Success Stories Time Series Database

Company

Contact Us Careers About Brand Community Code Of Conduct Events

Subscribe to the Tiger Data Newsletter

By submitting, you acknowledge Tiger Data's Privacy Policy

2025 (c) Timescale, Inc., d/b/a Tiger Data. All rights reserved.

Privacy preferences
LegalPrivacySitemap

Published at Aug 2, 2023

Join Types

PostgreSQL Join Type Theory

Abstract yellow shapes over a black background.

How does the PostgreSQL parser chooses which JOIN types to use? Join us for a session on JOIN theory.

In a previous article, we mentioned that PostgreSQL came about because some mathematicians wanted to map set theory to a file system. There is a lot to explain about how that ended up working. That explanation is still relevant today to understand how the PostgreSQL parser picks a join method or join types. 

This article will go over the high-level strategy of the PostgreSQL parser for choosing join types.  You can look forward to some subsequent articles that explain in more detail where and when different types of joins are helpful and provide the most efficiency.

If you don't know what set theory is or how basic joins map to set theory, there are some really good articles already out there. We won't bother to reproduce work that has been well done in the past. This article will explain in a bit more practical detail how the query planner deals with the complexity of SQL join theory.

How a Query Planner Works 

The basic working of a database planner is not as complex as you might think. The objective is to take apart an SQL statement and turn it into a list of functions that will produce the requested result.

Let's take a look at a fairly simple statement that gives us most of the elements that the parser uses:

SELECT fields, cols, tuples, list, item FROM relation INNER JOIN _data ON (relation.dataid) = (data.id) WHERE criteria = 1 and more_criteria = 4

In this statement, we have a section that is called the "selection list":

SELECT fields, cols, tuples, list, item

This is the list of items to retrieve from the physical data storage.

More importantly to our join types discussion, we have the "scan list":

FROM relation INNER JOIN _data

This tells the parser which storage the selection list comes from.

Then we have the "qualifications list," which is:

ON (relation.dataid) = (data.id) WHERE criteria = 1 and more_criteria = 4

The qualifications list narrows the search to specific data the caller is interested in.

Each entity in the "scan list" is called a "scan node." When we look at this from an execution point of view, there are several ways in which the parser can retrieve the data the user requested (the selection list) from the scan node(s):

1. Retrieve all of the data and apply the criteria in memory.

2. Scan the tables while applying the criteria directly to each row.

3. Use an index to retrieve only the requested data.

4. Scan the table while using the index to eliminate rows.

5. Index-only scan (requires the selection list to exist in the index).

6. Build a hash of the criteria, then scan the data and apply the hash in memory.

7. Ways I forgot to mention...

8. More ways being thought up by developers all the time...

And now, we get to the magic related to our article title. This is where the parser has to decide on the most efficient way to relate the data together based on the qualifications.

ON (relation.dataid) = (data.id)

It does this by picking a join type, an algorithm written in C that performs the checking required to see if the data is indeed related in the way the user requested.

Generally, we think of these criteria as being equality joins. That is the most common way data is related in a basic relational model—but it is by far not the only way to structure a relationship. The data may fall within a range, a list, a distribution, a non-equality, or just let everything match everything else (Cartesian).

For the sake of simplicity and brevity, we will concern ourselves here with joins based on equality. In further articles, we'll tackle some of the more complex types of joins.

Join Types

There are four basic join types in PostgreSQL. That is, four basic algorithms to match data from one set to another.

1. Nested Loop

2. Hash

3. Subselect

4. Merge

These functions are listed in pg_catalog.pg_proc. This is the system table where the implementations of all of the functions of PostgreSQL reside. The query parser is largely a strategy-picking mechanism that maps your query to the functions in this table.

Each of these computational strategies for joining tables has merits and drawbacks. We have often been asked which method is "best."  If there were a clear answer to that question, the "worst" ones would be removed from the list of options. Why would the PostgreSQL Global Development Group (PGDG) bother to maintain "bad" options?

A better question would be, "Which is best for this case?". We will attempt to make some recommendations in future articles about where each type of join is appropriate. For now, let's just look at how each join is called by the parser.

  • Nested Loop: named by the most basic implementation using two for loops (typically for i, for j).  At its most basic, it is an exhaustive search of all rows.

  • Hash: make a lookup table and use it to match multiple criteria at once.

  • Subselect: look in a secondary table for a value to match the primary table.

  • Merge: zipper two tables together by common keys that are previously ordered.

The Sherlock Parser

The PostgreSQL query planner will produce an exhaustive list of all combinations of scan types and join types that *could* fulfill the query request. This can be a very extensive list. It will then eliminate the most expensive items from the list until only one path to accomplish the query remains.  

We call this a "least cost optimizer." The idea is that whatever is left over, however unlikely, is the truth.

Let's take a look at just how complex this join operation is. For starters, there is no guarantee which table in the scan list comes first in the algorithm. The table that comes first in the evaluation is called the "driving" table.  

You could have:

digraph "G" { node [shape=rectangle label="SCAN\nNode"] a [label="JOIN\nNode"] b [label="SCAN\nNode\n'relation'"] c [color=blue style=filled label="SCAN\nNode\n'data'"] a -> b; a -> c; }

image

or

digraph "G" { node [shape=rectangle label="SCAN\nNode"] a [label="JOIN\nNode"] b [color=blue style=filled label="SCAN\nNode\n'relation'"] c [label="SCAN\nNode\n'data'"] a -> b; a -> c; }

image

This doesn't seem so significant until you realize that this "driving table" concept extends to any number of relations. So, the join order complexity is rising at a rate of $N!$.

In practice, implementing the join strategy (which is at the heart of database query planning) is one of the most expensive things the query parser has to deal with. You will see the effect of this later as we begin to look at EXPLAIN plans of the individual join types.

The more tables that are involved, the higher the complexity. This is why PostgreSQL has a limit (by default 13 scan nodes) of how many relations can be involved in a join before the planner goes into "Genetic Query Optimizer" (GEQO) mode.   

In this mode, the relations are only evaluated from left to right and only once. This dramatically reduces the number of plans but also eliminates some very good plans without ever really evaluating them. If you have ever created a very complex query that suddenly performs miserably when adding one more table, chances are you have invoked the wrath of the GEQO.

geqo=on geqo_threshold=12

The default join in PostgreSQL is the INNER JOIN. OUTER JOIN must be specified if you want all elements from a set. A semi-join can be accomplished with an EXISTS clause and an anti-join with EXCEPT, NOT IN, or <> (not equals).

The parser also performs a few other permutations before creating the list of possible plans.  This is done by the "query rewriter," which is a component that attempts to rewrite the SQL based on equivalent statements. 

Some of the things that could be affected by the query re-writer are:

1. A subselect may also be expressed as a join

2. A NOT IN (list) may also be expressed as <> ANY(list)

3. SQL functions get pulled in line to the calling SQL

4. And a lot more

They can affect the join selection strategy by turning one type of join into a completely different type of join.

The EXPLAIN Plan

Most of the process of picking a join strategy is invisible to the caller. Using the EXPLAIN keyword, we can only see the winner of the least cost optimization process. All of the alternative plans of execution have already been whittled away from the plan list. We can affect the plan by manually rewriting the query in different forms, which can influence the parser to make different planning decisions.

PostgreSQL does not implement query hints, and there is quite a bit of inertia in the PGDG to prevent that from ever happening. Query hints are comments or statements that intentionally affect the query parser without changing the text of the query.  

In other database systems, they are used to intentionally select specific indexes, evaluations, and (apropos of this article) join types. The PGDG eschews this idea for several reasons. For starters, the performance of indexes and joins may change in the field.  

At specific data sizes, a nested loop may be the appropriate strategy. As the data grows, this could change positively to a hash join. Indexes and tables become bloated over time due to multi-version concurrency control (MVCC) semantics.

An index that worked perfectly in design may not be so perfect in the field. Even when the user improves query performance using a specific technique at design time, there is no guarantee that the technique will continue to be the best choice in production. And it generally won't.

There is also a philosophical argument against query hints. That is, a query parser is specifically designed to turn declarative language into imperative processes. The whole idea is that you declare what you want, and allow the engine to decide the best method to provide the specified result.

"Influencing" the parser is a direct betrayal of that system. It makes any future improvements to the system no longer apply to your case and defeats any improvements from the query planner itself.

Not (So Much) Conclusions

This information is provided to give you something of a background for further articles about join theory and why specific joins are selected. The eventual objective is to understand why the query planner made particular choices. To get to that objective, it helps to know how the query parser actually performs the task of making a choice.

In short, the query is hacked into pieces that are mapped to functions in a list. The highest-cost functions are trimmed from the list. What is left is expressed as an execution plan. The execution plan is sent to the executor to be performed, and the results are sent back to the caller.

Check out this article for more strategies to improve your PostgreSQL JOIN performance.

Read More

1. This Stackoverflow Post went completely bonkers over a simple question: tsql - LEFT JOIN vs. LEFT OUTER JOIN in SQL Server - Stack Overflow

2. This blog post explains set theory fairly well: Set Theory: the Method To Database Madness | by Vaidehi Joshi | basecs | Medium

On this page