Basics
- How to Insert
- How to Update
- How to Delete
- How to Trim Strings
- How to Use substring()
- How to Use substring() with RegEx to Extract a String
- How to Replace Substrings
- How to Modify Arrays
- How to Compare Arrays
- How to Concatenate Strings
- How to Convert the Case of a String
- How to Create an Array
- How to Insert Data Into an Array
- How to Query Arrays
- How to Use string_agg()
Database Management
- How to Create a Table
- How to Drop a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Change a Column Name
- How to Add a Default Value
- How to Remove a Default Value From a Column
- How to Add a Not Null Constraint
- How to Remove a Not Null Constraint
- How to Add an Index
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Reset Sequence
- How to Drop a Column
Dates and Times
Analysis
- How to Use nullif()
- How to Use Lateral Joins
- How to Calculate Percentiles
- How to Get the First Row per Group
- How to Use generate_series to Avoid Gaps in Data
- How to Do Type Casting
- How to Write a Common Table Expression
- How to Import a CSV using Copy
- How to Compare Two Values When One Is Null
- How to Use Coalesce
- How to Write a Case Statement
- How to Use Filter to Have Multiple Counts
- How to Calculate Cumulative Sum-Running Total
- How to Query a JSON Column
How to Use Lateral Joins in PostgreSQL
Lateral joins in PostgreSQL are a powerful feature that allows subqueries on the right side of a join to reference columns from the left side. This enables more flexible and efficient query designs.
What is a Lateral Join?
A lateral join lets you run a subquery for each row of the left-hand table in a join. Itβs written using the LATERAL keyword, which tells PostgreSQL that the subquery can reference columns from the main query.
When to Use Lateral Joins
- When you need to perform a subquery that depends on each row from the main table.
- When using functions like
jsonb_array_elements()orunnest()that need row context. - To simplify complex queries with correlated subqueries.
Basic Syntax
SELECT *
FROM table1
JOIN LATERAL (
SELECT ...
FROM table2
WHERE table2.column = table1.column
) subquery ON true;Example 1: Top Order per Customer
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
JOIN LATERAL (
SELECT *
FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.total DESC
LIMIT 1
) o ON true;This query fetches each customer with their highest total order.
Example 2: Unnesting JSON Arrays
SELECT p.id, p.name, tag
FROM products p,
LATERAL jsonb_array_elements_text(p.tags) AS tag;
This example extracts each tag from a JSONB array stored in the tags column.
Why Use Lateral Joins?
- They simplify query structure compared to correlated subqueries.
- They often improve performance by avoiding repeated calculations.
- They allow combining set-returning functions with row-level context.
Things to Watch Out For
- Always use
ON trueif the join condition is embedded in the subquery. - Lateral joins may have performance implications on large datasets β test and analyze your queries.
Summary
Lateral joins are an advanced but essential feature for writing expressive, efficient SQL in PostgreSQL. They allow you to perform row-dependent subqueries and simplify complex queries.
Try adding lateral joins to your toolset β they can save you from convoluted workarounds and boost your SQL power!
Turn this PostgreSQL query into a scheduled report
DataReportive runs your SQL queries on a schedule and delivers the results via email, PDF, Excel, or HTML. Set up your reports once and get fresh data delivered automatically.
Automate PostgreSQL reporting with DataReportive
Turn your PostgreSQL queries into scheduled reports delivered to your team or customers.