
When working with databases, information is often stored in multiple tables instead of one large table. For example, an e-commerce application might store customer information in a customers table and purchase details in an orders table.
But what if you want to display each customer's name alongside their orders? Or find customers who have never placed an order?
This is where PostgreSQL JOINs become useful.
A JOIN allows you to combine rows from two or more tables based on a related column or a specified condition. JOINs are essential for building reports, retrieving related records, creating dashboards, and developing backend applications.
In this guide, you'll learn:
What JOINs are in PostgreSQL.
The different types of PostgreSQL JOINs.
How to use
INNER JOIN,LEFT JOIN,RIGHT JOIN, andFULL OUTER JOIN.How
CROSS JOINandSELF JOINwork.The difference between
ONandUSING.Common JOIN mistakes and performance tips.
Practical examples you can use in real projects.
Let's start with the basics.
What Is a JOIN in PostgreSQL?
A JOIN in PostgreSQL combines rows from two or more tables using a specified relationship or condition.
Consider two tables: customers and orders.
Customers Table
customer_id | name | city |
|---|---|---|
1 | Aman | Delhi |
2 | Priya | Jaipur |
3 | Rahul | Mumbai |
4 | Neha | Pune |
Orders Table
order_id | customer_id | amount |
|---|---|---|
101 | 1 | 1500 |
102 | 2 | 2500 |
103 | 1 | 800 |
104 | 5 | 1200 |
Notice that the customer_id column appears in both tables. It can be used to match customer records with their orders.
For example, to retrieve customers and their orders, you can write:
SELECT
customers.name,
orders.order_id,
orders.amount
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;This query combines rows where the customer_id values match.
The result is:
name | order_id | amount |
|---|---|---|
Aman | 101 | 1500 |
Priya | 102 | 2500 |
Aman | 103 | 800 |
Aman appears twice because he has placed two orders.
Customers without matching orders and orders without matching customers are excluded from this INNER JOIN.
Important: A JOIN does not necessarily produce one row per customer. If a customer has multiple matching orders, the customer can appear multiple times in the result.
Types of PostgreSQL JOINs
PostgreSQL supports several types of JOINs. Each type determines how matching and unmatched rows are handled.
JOIN Type | What It Returns |
|---|---|
| Rows with matching records in both tables |
| Every row from the left table and matching rows from the right |
| Every row from the right table and matching rows from the left |
| All rows from both tables, matched where possible |
| Every possible combination of rows from both tables |
| A table joined to another instance of itself |
Let's examine each type with examples.
1. INNER JOIN in PostgreSQL
An INNER JOIN returns only rows that satisfy the join condition in both tables.
It is one of the most commonly used JOIN types because applications frequently need information that exists in related tables.
Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;The INNER keyword is optional. Writing JOIN without a join type means INNER JOIN.
Example: Retrieve Customers and Their Orders
SELECT
c.customer_id,
c.name,
o.order_id,
o.amount
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;Here, c and o are table aliases. They make the query shorter and easier to read.
Result
customer_id | name | order_id | amount |
|---|---|---|---|
1 | Aman | 101 | 1500 |
2 | Priya | 102 | 2500 |
1 | Aman | 103 | 800 |
Rahul and Neha do not appear because they have no matching orders.
Order 104 also does not appear because its customer_id is 5, which does not exist in the customers table.
When Should You Use INNER JOIN?
Use INNER JOIN when you only want records with a matching relationship.
Common examples include:
Retrieving orders with valid customer records.
Displaying employees alongside their departments.
Showing products that belong to existing categories.
Retrieving students with their enrolled courses.
2. LEFT JOIN in PostgreSQL
A LEFT JOIN, also called a left outer join, returns every row from the left table and matching rows from the right table.
If no matching right-side record exists, PostgreSQL fills the right-side columns with NULL.
Syntax
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;Example: Find All Customers and Their Orders
Suppose you want to display every customer, including customers who have never placed an order.
SELECT
c.customer_id,
c.name,
o.order_id,
o.amount
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id
ORDER BY c.customer_id, o.order_id;Result
customer_id | name | order_id | amount |
|---|---|---|---|
1 | Aman | 101 | 1500 |
1 | Aman | 103 | 800 |
2 | Priya | 102 | 2500 |
3 | Rahul | NULL | NULL |
4 | Neha | NULL | NULL |
Rahul and Neha appear even though they have no orders.
Their order-related columns contain NULL because PostgreSQL could not find matching rows in the right table.
Find Customers Who Have Never Placed an Order
A common real-world use of LEFT JOIN is finding records without a match.
SELECT
c.customer_id,
c.name
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;This query returns customers who have no matching order.
Expected result:
customer_id | name |
|---|---|
3 | Rahul |
4 | Neha |
This technique is often called an anti-join pattern.
You can also use NOT EXISTS for this purpose:
SELECT
c.customer_id,
c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
);Both approaches can solve this problem. The best choice depends on readability and the query's requirements.
When Should You Use LEFT JOIN?
Use LEFT JOIN when the left table represents the records you must preserve.
Examples include:
Finding customers without orders.
Displaying all employees, including employees without assigned projects.
Listing every product with its category, if available.
Showing all students, including students who have not enrolled in a course.
3. RIGHT JOIN in PostgreSQL
A RIGHT JOIN is the reverse of a LEFT JOIN.
It returns every row from the right table and matching rows from the left table. If a right-side row has no match, the left-side columns contain NULL.
Syntax
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;Example: Retrieve All Orders and Their Customers
SELECT
c.customer_id,
c.name,
o.order_id,
o.amount
FROM customers AS c
RIGHT JOIN orders AS o
ON c.customer_id = o.customer_id
ORDER BY o.order_id;Result
customer_id | name | order_id | amount |
|---|---|---|---|
1 | Aman | 101 | 1500 |
2 | Priya | 102 | 2500 |
1 | Aman | 103 | 800 |
NULL | NULL | 104 | 1200 |
Order 104 appears even though it has no matching customer record.
This happens because RIGHT JOIN preserves every row from the orders table, which is the right-side table in this query.
Can You Replace RIGHT JOIN with LEFT JOIN?
Yes. Many developers prefer LEFT JOIN because it makes the table being preserved more obvious.
The previous query can be rewritten as:
SELECT
c.customer_id,
c.name,
o.order_id,
o.amount
FROM orders AS o
LEFT JOIN customers AS c
ON o.customer_id = c.customer_id
ORDER BY o.order_id;This produces the same logical result.
When Should You Use RIGHT JOIN?
Use RIGHT JOIN when you want to preserve all rows from the right table.
However, you can usually rewrite the query with LEFT JOIN by switching the table order. Choose whichever version makes the query easier to understand.
4. FULL OUTER JOIN in PostgreSQL
A FULL OUTER JOIN returns matching rows and preserves unmatched rows from both tables.
When a row has no match on the other side, PostgreSQL fills the missing side's columns with NULL.
Syntax
SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;Example: Combine All Customers and Orders
SELECT
c.customer_id,
c.name,
o.order_id,
o.amount
FROM customers AS c
FULL OUTER JOIN orders AS o
ON c.customer_id = o.customer_id;Result
customer_id | name | order_id | amount |
|---|---|---|---|
1 | Aman | 101 | 1500 |
1 | Aman | 103 | 800 |
2 | Priya | 102 | 2500 |
3 | Rahul | NULL | NULL |
4 | Neha | NULL | NULL |
NULL | NULL | 104 | 1200 |
The result includes:
Customers with matching orders.
Customers without orders.
Orders without matching customers.
This makes FULL OUTER JOIN useful for comparing two datasets and identifying records that exist on only one side.
Example: Find Unmatched Records in Either Table
SELECT
c.customer_id,
c.name,
o.order_id,
o.customer_id AS order_customer_id
FROM customers AS c
FULL OUTER JOIN orders AS o
ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL
OR o.order_id IS NULL;This returns unmatched customer rows and orders that have no matching customer.
When Should You Use FULL OUTER JOIN?
Common use cases include:
Comparing records between two systems.
Identifying missing relationships.
Reconciling imported data.
Comparing customer or product lists.
Finding records that exist in one dataset but not another.
5. CROSS JOIN in PostgreSQL
A CROSS JOIN returns every possible combination of rows from two tables.
Unlike an INNER JOIN, it does not require a matching condition.
This is also known as a Cartesian product.
Syntax
SELECT columns
FROM table1
CROSS JOIN table2;Example: Combine Products and Colors
Imagine you have a products table:
product_name |
|---|
T-Shirt |
Hoodie |
And a colors table:
color |
|---|
Red |
Blue |
Black |
You can combine the two tables:
SELECT
p.product_name,
c.color
FROM products AS p
CROSS JOIN colors AS c;Result
product_name | color |
|---|---|
T-Shirt | Red |
T-Shirt | Blue |
T-Shirt | Black |
Hoodie | Red |
Hoodie | Blue |
Hoodie | Black |
Two products multiplied by three colors produce six rows.
Formula:
Number of result rows = Rows in table 1 × Rows in table 2
If the first table has 100 rows and the second has 200 rows, a CROSS JOIN produces 20,000 combinations.
When Should You Use CROSS JOIN?
A CROSS JOIN can be useful for:
Generating product and color combinations.
Creating combinations of dates and categories.
Building test datasets.
Generating possible schedules or configurations.
Producing all combinations of selected attributes.
Be careful with large tables because the number of combinations can grow quickly.
6. SELF JOIN in PostgreSQL
A self join is a technique in which a table is joined to itself.
It is useful when rows in the same table are related to other rows in that table.
For example, an employee table may store each employee's manager using a manager_id column.
Example: Employees Table
employee_id | employee_name | manager_id |
|---|---|---|
1 | Amit | NULL |
2 | Priya | 1 |
3 | Rahul | 1 |
4 | Neha | 2 |
Here, Amit has no manager, while Priya and Rahul report to Amit. Neha reports to Priya.
Query: Display Employees and Their Managers
SELECT
e.employee_name AS employee,
m.employee_name AS manager
FROM employees AS e
LEFT JOIN employees AS m
ON e.manager_id = m.employee_id
ORDER BY e.employee_id;Result
employee | manager |
|---|---|
Amit | NULL |
Priya | Amit |
Rahul | Amit |
Neha | Priya |
The query references the same table twice using different aliases:
erepresents the employee.mrepresents the manager.
The LEFT JOIN ensures that Amit still appears even though he has no manager.
When Should You Use SELF JOIN?
Self joins are useful for:
Employee-manager relationships.
Hierarchical categories.
Comparing rows within the same table.
Finding related records.
Representing parent-child relationships.
7. JOIN Using Multiple Conditions
Sometimes a single column is not enough to identify matching records.
For example, a table may store product prices for different stores. To match the correct price, you might need both product_id and store_id.
You can use multiple conditions in the ON clause.
Example
SELECT
p.product_name,
s.store_name,
p.price
FROM product_prices AS p
INNER JOIN stores AS s
ON p.store_id = s.store_id
AND p.region_id = s.region_id;Both conditions must evaluate to true for a row pair to match.
You can also use other comparison operators when the relationship requires them. For example, a JOIN condition might compare date ranges or numeric values rather than simple equality.
However, make sure the conditions represent the relationship you actually want. Incorrect conditions can create unexpected duplicate rows or exclude valid matches.
8. Using ON vs USING in PostgreSQL
PostgreSQL supports both ON and USING for specifying JOIN conditions.
They serve similar purposes, but they are not identical.
Using ON
The ON clause explicitly defines the relationship between the tables.
SELECT
c.customer_id,
c.name,
o.order_id
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;This approach is flexible and lets you specify conditions involving different column names or multiple expressions.
Using USING
The USING clause is a shorter alternative when both tables have a column with the same name.
SELECT
customer_id,
name,
order_id
FROM customers
INNER JOIN orders
USING (customer_id);When you use USING (customer_id), PostgreSQL matches rows where the two customer_id values are equal. The joined output includes a single shared customer_id column rather than two separate copies.
ON vs USING: Comparison
Feature | ON | USING |
|---|---|---|
Column names must match | No | Yes |
Supports multiple conditions | Yes | Supports multiple shared column names |
Supports complex expressions | Yes | No, it is designed for matching shared column names |
Removes duplicate join columns from output | No, not automatically | Yes, for the listed join columns |
Best for | Flexible join conditions | Simple equality joins on same-named columns |
For most application queries, ON is a flexible default. Use USING when shared column names make the relationship clear.
Avoid relying on NATURAL JOIN in long-lived application code unless you deliberately want every same-named column to become part of the join condition. Schema changes can unintentionally change its behavior.
9. Combining Multiple JOINs in One Query
Real-world applications frequently require data from three or more tables.
For example, an e-commerce report may need customer details, order details, and payment information.
Suppose the database contains:
customersorderspayments
You can join all three tables.
Example: Retrieve Customer Orders and Payments
SELECT
c.name,
o.order_id,
o.amount,
p.payment_method,
p.payment_status
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id
LEFT JOIN payments AS p
ON o.order_id = p.order_id
ORDER BY o.order_id;This query works in two stages:
INNER JOINretrieves orders with matching customers.LEFT JOINattaches matching payment information while preserving orders that have no matching payment record.
The result can include an order whose payment-related columns are NULL.
This pattern is useful for dashboards, transaction reports, and administrative interfaces.
Important: If an order can have multiple payment records, joining the tables may produce multiple rows per order. Always consider the relationship cardinality when designing a query.
10. Filtering Data with JOINs
You can combine JOINs with WHERE, GROUP BY, and ORDER BY to build more useful queries.
Example: Find Orders Above ₹1,000
SELECT
c.name,
o.order_id,
o.amount
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id
WHERE o.amount > 1000
ORDER BY o.amount DESC;This query:
Matches customers with their orders.
Filters orders to include only amounts above ₹1,000.
Sorts the results from highest to lowest amount.
Example: Calculate Total Spending per Customer
SELECT
c.customer_id,
c.name,
COALESCE(SUM(o.amount), 0) AS total_spending
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id
GROUP BY
c.customer_id,
c.name
ORDER BY total_spending DESC;The LEFT JOIN keeps customers who have no orders. The SUM() function calculates each customer's total order amount, and COALESCE() converts a NULL total to zero.
Example result:
customer_id | name | total_spending |
|---|---|---|
1 | Aman | 2300 |
2 | Priya | 2500 |
3 | Rahul | 0 |
4 | Neha | 0 |
This type of query is useful for customer reports and sales dashboards.
11. The Difference Between ON and WHERE with LEFT JOIN
One of the most common mistakes developers make is moving a condition from ON to WHERE without considering how it changes the result.
These two queries may look similar, but they behave differently.
Query A: Filter in ON
SELECT
c.name,
o.order_id,
o.amount
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id
AND o.amount > 1000;This query preserves every customer. It attaches only orders whose amount exceeds ₹1,000.
Customers without a qualifying order still appear, with NULL values in the order columns.
Query B: Filter in WHERE
SELECT
c.name,
o.order_id,
o.amount
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id
WHERE o.amount > 1000;This query filters the joined result after the JOIN. Rows where o.amount is NULL do not satisfy the WHERE condition, so customers without qualifying orders disappear.
For this condition, Query B behaves like an inner join with respect to the order amount filter.
Which One Should You Use?
Put a condition in
ONwhen it determines which right-side records should match while preserving unmatched left-side records.Put a condition in
WHEREwhen you want to filter the final result.
Understanding this difference is especially important when working with optional relationships.
12. PostgreSQL JOIN Performance Tips
JOINs are fundamental to relational database development, but poorly designed queries can become slow or return unexpectedly large result sets.
Here are some best practices.
1. Index Columns Used in JOIN Conditions
Consider this query:
SELECT
c.name,
o.order_id
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;Primary keys and unique constraints create indexes automatically. PostgreSQL also benefits from indexes on frequently used referencing columns when the workload justifies them.
For example:
CREATE INDEX idx_orders_customer_id
ON orders(customer_id);This index may help queries that filter or join using orders.customer_id.
However, indexes are not guaranteed to improve every JOIN. PostgreSQL chooses an execution plan based on statistics, table sizes, available indexes, and other factors.
2. Avoid SELECT * in Production Queries
Instead of retrieving every column:
SELECT *
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;Select only the columns you need:
SELECT
c.name,
o.order_id,
o.amount
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;This makes the query easier to understand and reduces unnecessary data transfer.
3. Use Table Aliases
Aliases help keep queries readable when several tables are involved.
SELECT
c.name,
o.amount
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;They are particularly useful when tables contain columns with identical names.
4. Check Your Query Execution Plan
PostgreSQL provides EXPLAIN and EXPLAIN ANALYZE to help you understand query execution.
EXPLAIN ANALYZE
SELECT
c.name,
o.order_id
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;The output provides information about the execution plan and, with ANALYZE, actual execution statistics.
Use this information to identify expensive operations and determine whether an index or query rewrite would help.
Remember that EXPLAIN ANALYZE executes the query. Take care when analyzing statements that modify data.
5. Avoid Unnecessary CROSS JOINs
A CROSS JOIN can create a very large number of rows because it combines every row from one table with every row from the other.
Before using one, confirm that all combinations are genuinely required.
6. Understand One-to-Many Relationships
If one customer has five orders, joining customers to orders produces five rows for that customer.
This is expected behavior, not necessarily a duplicate-data problem.
If you need one row per customer, consider aggregation, DISTINCT, or a query that selects the specific order you want. Choose the technique based on the required result rather than removing duplicates automatically.
7. Keep Statistics Up to Date
PostgreSQL's query planner relies on table statistics when choosing execution plans.
PostgreSQL normally maintains statistics through automatic maintenance, but large data changes or unusual workloads may require additional attention.
If a JOIN performs poorly, inspect its plan and verify that the planner has useful statistics.
13. Common PostgreSQL JOIN Mistakes
Here are several mistakes developers should watch for.
Mistake 1: Forgetting the JOIN Condition
Forgetting a condition can accidentally create a Cartesian product.
Incorrect for a normal customer-order relationship:
SELECT *
FROM customers
CROSS JOIN orders;This is valid SQL, but it produces every customer-order combination.
For matching customers and orders, use:
SELECT
c.name,
o.order_id
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id;Mistake 2: Using the Wrong JOIN Type
An INNER JOIN removes unmatched rows. If you need to display every customer, even those without orders, use a LEFT JOIN.
Always decide which table's rows must be preserved before choosing a JOIN type.
Mistake 3: Filtering NULL Values Incorrectly
SQL uses three-valued logic: a comparison involving NULL generally evaluates to unknown rather than true or false.
Incorrect:
WHERE o.order_id = NULL;Correct:
WHERE o.order_id IS NULL;Use IS NULL and IS NOT NULL to test for NULL values.
Mistake 4: Accidentally Turning a LEFT JOIN into an Inner Join
Consider:
SELECT
c.name,
o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON c.customer_id = o.customer_id
WHERE o.amount > 1000;Customers without matching orders are excluded because the WHERE condition removes rows where o.amount is NULL.
If your goal is to preserve all customers while matching only qualifying orders, put the condition in the ON clause instead.
Mistake 5: Ignoring Duplicate Matches
A JOIN can produce multiple rows when multiple records match.
For example, if a customer has three orders, that customer appears three times in a customer-order JOIN.
Before using DISTINCT, check whether the multiple rows are valid results of a one-to-many relationship.
14. Which PostgreSQL JOIN Should You Choose?
Use this quick reference when writing queries.
Requirement | Recommended JOIN |
|---|---|
Return only matching records |
|
Keep all records from the first table |
|
Keep all records from the second table |
|
Keep records from both tables, whether matched or not |
|
Generate all possible combinations |
|
Compare related rows within one table |
|
For most application queries, INNER JOIN and LEFT JOIN cover many common requirements.
Choose the JOIN type based on the result you need, not simply because one type appears more frequently in examples.
Frequently Asked Questions (FAQs)
1. What is a JOIN in PostgreSQL?
A JOIN combines rows from two or more tables using a specified condition. It allows you to retrieve related information from multiple tables in a single query.
2. What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only matching rows. LEFT JOIN returns every row from the left table and adds matching rows from the right table. If no right-side match exists, the right-side columns contain NULL.
3. What is the difference between LEFT JOIN and RIGHT JOIN?
A LEFT JOIN preserves all rows from the left table, while a RIGHT JOIN preserves all rows from the right table. You can usually rewrite a RIGHT JOIN as a LEFT JOIN by reversing the table order.
4. What is a FULL OUTER JOIN in PostgreSQL?
A FULL OUTER JOIN returns matching rows and unmatched rows from both tables. Missing values on either side are represented by NULL.
5. Can PostgreSQL JOIN more than two tables?
Yes. You can combine multiple tables by chaining JOIN clauses together. For example, you can join customers to orders and then join orders to payments.
6. What is the difference between ON and USING?
ON lets you define a flexible join condition. USING is shorthand for equality matching when both tables have the same join-column name. USING also returns the shared join column only once.
7. Does a JOIN create duplicate rows?
A JOIN can produce multiple rows for one record when multiple rows in the other table match it. This is normal for one-to-many relationships.
8. Which JOIN is fastest in PostgreSQL?
There is no universally fastest JOIN type. Performance depends on the data, query conditions, indexes, table statistics, and execution plan. Choose the correct JOIN semantics first, then optimize using tools such as EXPLAIN ANALYZE.
9. How can I find records that do not have a match?
A common method is to use LEFT JOIN with an IS NULL filter on a right-side column that cannot be NULL for a real matching row. You can also use NOT EXISTS.
10. Are JOINs better than subqueries?
Neither approach is always better. JOINs are often clear when combining related tables, while subqueries and EXISTS can be more natural for existence checks or other specific operations. Compare readability and execution plans for your workload.
Conclusion
PostgreSQL JOINs are essential for retrieving related data from relational tables. They allow you to combine customer records with orders, employees with departments, products with categories, and many other types of related information.
The most important JOIN types to understand are:
INNER JOIN: Returns matching rows.
LEFT JOIN: Preserves all rows from the left table.
RIGHT JOIN: Preserves all rows from the right table.
FULL OUTER JOIN: Preserves unmatched rows from both tables.
CROSS JOIN: Produces every possible row combination.
SELF JOIN: Joins a table to itself.
You should also understand how ON, USING, and WHERE affect query results, particularly when working with outer joins.
Start by practicing INNER JOIN and LEFT JOIN with small datasets. Then explore multiple-table joins, self joins, aggregation, and query optimization.
Once you understand how PostgreSQL JOINs work, you'll be able to write more powerful SQL queries and build more effective database-driven applications.
Official Resource
For additional examples and technical details, read the official PostgreSQL documentation on JOINs and table expressions.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


