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

Performance

Guide to PostgreSQL Performance

Schema design

PostgreSQL Performance Tuning: Designing and Implementing Your Database Schema

Performance tuning

PostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesHow to Reduce Bloat in Large PostgreSQL TablesPostgreSQL Performance Tuning: How to Size Your Database

Partitioning

Determining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)When to Consider Postgres PartitioningPg_partman vs. Hypertables for Postgres Partitioning

Database design and modeling

An Intro to Data Modeling on PostgreSQLDesigning 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 Guide to PostgreSQL Database Design

Database replication

A PostgreSQL Database Replication Guide

Data analysis

A Guide to Data Analysis on PostgreSQLHow to Compute Standard Deviation With PostgreSQL

Data transformation

How to Use PostgreSQL for Data Transformation

Data aggregation

How PostgreSQL Data Aggregation Works

Scaling postgres

A Guide to Scaling PostgreSQLBuilding a Scalable Database

Database security

Guide to PostgreSQL SecurityWhat Is Audit Logging and How to Enable It in PostgreSQL

Data management

Understanding PostgreSQL TablespacesGuide to Postgres Data ManagementHandling Large Objects in Postgres

Database operations

Guide to PostgreSQL Database Operations

JSON

How to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Index JSONB Columns in PostgreSQLSQL/JSON Data Model and JSON in SQL: A PostgreSQL Perspective

Query optimization

Explaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?Optimizing Array Queries With GIN Indexes in PostgreSQLRecursive Query in SQL: What It Is, and How to Write One

Database tools and libraries

How to Use Psycopg2: The PostgreSQL Adapter for PythonTop PostgreSQL Drivers for Python

Database indexes

How to Monitor and Optimize PostgreSQL Index Performance

Database backups and restore

A Guide to pg_restore (and pg_restore Example)

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 Nov 5, 2024

Recursive Query in SQL: What It Is, and How to Write One

Try for free

Start supercharging your PostgreSQL today.

Recursive Query in SQL—blue round geometric shapes over a black background

Written by Dylan Paulus

As developers, querying in PostgreSQL for hierarchical data is difficult. SQL is a declarative programming language, but our brains are trained to think imperatively. Recursive queries using Common Table Expressions (CTE) simplify writing iterative queries and are essential in traversing hierarchical data, like tree or graph structures.

Throughout this article, we'll explore SQL recursive queries with examples, look at optimizing recursive queries, and discuss advanced techniques. 

What Is Recursion?

Before getting into recursive queries, let's take a step back to understand recursion. Recursion is a method of breaking down a problem into a small, repeatable solution that calls itself. Think of recursion like Russian nesting dolls. To find a specific doll, we open smaller and smaller versions of the same doll until we find the doll we want or there are no more dolls to open.

In programming, we see recursion when a function calls itself. Recursion is classically a solution to finding the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is calculated by summing the previous two numbers starting at one (0, 1, 1, 2, 3, 5, 8, 13, and so on). 

image

The Fibonacci Sequence mapped out

To find the Fibonacci number at a given position, we start by finding the Fibonacci number of the previous two positions. This process continues until we reach position 0 or 1, which always returns 0 or 1, respectively. It's important to remember these base cases as they form the foundation of the sequence.

For example, to find the Fibonacci number at position 5 in the sequence, we first need to find the Fibonacci number at position 4 and 3 (fibonacci(3) + fibonacci(4) = 5). To find the Fibonacci number of position 3, we then need to find the Fibonacci number at positions 1 and 2 (fibonacci(1) + fibonacci(2) = 3). This continues until we reach position 0 (since fibonacci(0) = 0) or 1 (fibonacci(1) = 1).

image

A graph showing calculating Fibonacci numbers at position 5

Using this approach, the solution to finding Fibonacci numbers in Python would be: def fibonacci(number):     if number <= 1:  # Base case         return number     return fibonacci(number - 1) + fibonacci(number - 2) # Recursion

Recursion can be broken down into two parts. The base case and the recursive case.

  • Base case: it defines the starting point of recursion, or in other words, the condition that will break out of recursion.

  • Recursive case: the case where we call the function we're in—this is where the "loop iterates."

Recursive Queries

Like in our favorite programming languages, recursive queries in PostgreSQL allow us to iterate through data or navigate hierarchical data, following a similar pattern and setup with a slightly different approach.

We define a base case and a recursive case by breaking down a query into small, repeatable statements. Recursive queries are defined through Common Table Expressions by starting queries with WITH RECURSIVE statements. The structure of a recursive query looks like:

WITH RECURSIVE [cte name] AS (   [base case]   UNION ALL   [recursive case] ) [primary query]

In recursive queries, the base case is the starting point of recursion. The recursive case is what gets repeated. This happens in recursive queries by joining against the recursive query, and recursion stops when there is nothing else to join against. UNION ALL merges the results in the base case and recursive case.

Finally, outside the Common Table Expression, we have a query that ties the recursive query together. You'll generally see this as a straight SELECT * FROM [recursive_cte_name];.

Like the Python example, we can calculate Fibonacci numbers with recursive queries in PostgreSQL. The syntax looks different from the Python example, note the similarities between the base/recursive cases and the general approach to the solution.

WITH RECURSIVE fibonacci(position, current_value, next_value) AS (     -- Base case: start with position: 1, current_value: 0, and next_value: 1     SELECT          1 as position,         0 as current_value,         1 as next_value             UNION ALL         -- Recursive case: Loop through the fibonacci sequence, ending at position 4.     -- Putting the WHERE clause prevents runaway recursion (infinite loop)    SELECT         position + 1,         next_value,         current_value + next_value     FROM fibonacci -- Where we call "ourself", creating recursion     WHERE position < 5 ) -- Select the results SELECT      position,     current_value as fibonacci_number FROM fibonacci;

Real-World Example Using Recursive Queries

Let's say that our company monitors the electrical usage of residential homes using small IoT sensors. Each sensor is connected to another sensor to monitor voltage usage. The data is modeled in a graph since electrical runs can be split (e.g., the same power source can power lights and receptacles).

image

An example of a graph structure for modeling sensors in a house's electrical system

The SQL tables look like this:

CREATE TABLE sensors (   id                   SERIAL PRIMARY KEY,   name                 VARCHAR(255) NOT NULL,   previous_sensor_id   INTEGER REFERENCES sensors(id) );

CREATE TABLE events (   id            SERIAL PRIMARY KEY,   sensor_id     INTEGER REFERENCES sensors(id),   power_usage   DECIMAL, -- Kilowatt hours   date          TIMESTAMP default now() );

INSERT INTO sensors (name, previous_sensor_id) VALUES ('Breaker', null); -- id is 1 INSERT INTO sensors (name, previous_sensor_id) VALUES ('Bedroom Recepticles', 1); -- id is 2 INSERT INTO sensors (name, previous_sensor_id) VALUES ('Bedroom Light Switch', 1); -- id is 3 INSERT INTO sensors (name, previous_sensor_id) VALUES ('Bedroom Lights', 3); -- id is 4 INSERT INTO sensors (name, previous_sensor_id) VALUES ('Bathroom Lights', 1); -- id is 5

INSERT INTO events (sensor_id, power_usage) VALUES (2, 1.05); INSERT INTO events (sensor_id, power_usage) VALUES (4, 0.3); INSERT INTO events (sensor_id, power_usage, date) VALUES (4, 0.2, now() - interval '1' day); INSERT INTO events (sensor_id, power_usage, date) VALUES (4, 0.28, now() - interval '2' day); INSERT INTO events (sensor_id, power_usage) VALUES (5, 0.13); INSERT INTO events (sensor_id, power_usage, date) VALUES (5, 0.17, now() - interval '1' day);

We are tasked with determining the average power usage for all sensors in a given chain (e.g., Bedroom Lights -> Light Switch -> Breaker) in the past day. To make debugging easier, we will also display the path taken through each sensor. 

Let's first examine the complete query and then break down each step that makes up the complete recursive query.

WITH RECURSIVE power_chain AS (     -- Base case: start with sensors who don't have children     SELECT          s.id,         s.name,         s.previous_sensor_id,         Array[e.power_usage] as power_usages,         ARRAY[s.name]::VARCHAR[] as chain     FROM sensors s     JOIN events e ON s.id = e.sensor_id     WHERE NOT EXISTS (         SELECT 1          FROM sensors child          WHERE child.previous_sensor_id = s.id    )     AND e.date >= NOW() - INTERVAL '1 day'         UNION ALL         -- Recursive case: recurse through parent sensors     SELECT         s.id,         s.name,         s.previous_sensor_id,         e.power_usage || pc.power_usages,         s.name || pc.chain     FROM sensors s     LEFT JOIN events e on s.id = e.sensor_id     JOIN power_chain pc ON s.id = pc.previous_sensor_id ) SELECT     array_to_string(chain, ' <- ') as complete_path,     ROUND((SELECT AVG(s) FROM UNNEST(power_usages) s), 2) as power_usage FROM power_chain WHERE previous_sensor_id IS NULL; 

image

The output table of running the previous recursive query

Base case

SELECT  s.id, s.name, s.previous_sensor_id, Array[e.power_usage] as power_usages, ARRAY[s.name]::VARCHAR[] as chain FROM sensors s JOIN events e ON s.id = e.sensor_id WHERE NOT EXISTS ( SELECT 1  FROM sensors child  WHERE child.previous_sensor_id = s.id ) AND e.date >= NOW() - INTERVAL '1 day'

In the base case, we define how the recursion will start. We start with the sensors that don't have children or, in other words, the root nodes. In this case, it's just the Breaker sensor. You'll notice we include two arrays in the SELECT statement: power_usages and chain. As we traverse the sensor graph, we'll add to these arrays to compute the average power_usage and the path back to the Breaking through chain.

Recursive case

SELECT  s.id, s.name, s.previous_sensor_id, e.power_usage || pc.power_usages, s.name || pc.chain FROM sensors s LEFT JOIN events e on s.id = e.sensor_id JOIN power_chain pc ON s.id = pc.previous_sensor_id

In each recursive case, we follow the path from the breaker back through every possible path (JOIN power_chain pc ON s.id = pc.previous_sensor_id), adding the current sensor's data to power_usages and keeping track of the path in chain.

Query

SELECT      array_to_string(chain, ' <- ') as complete_path,     ROUND((SELECT AVG(s) FROM UNNEST(power_usages) s), 2) as power_usage FROM power_chain WHERE previous_sensor_id IS NULL; 

In the main body of the query, we'll aggregate the two arrays we created in the recursive query. First, we'll combine the chain array into a string showing the complete_path the recursive query took. Last, we take the average of the power_usages to get the average power usage through each recursive path.

Using Lateral Joins

The reason we stored each power_usage in an array in the previous example is that we can't use aggregate functions inside the recursive case (SUM, AVG, etc.). Give it a try. PostgreSQL will return an error that reads ERROR: aggregate functions are not allowed in a recursive query's recursive term.

We can use subqueries, build the data as we recurse (like through the array example), or use lateral joins to get around this. Lateral joins are like subqueries, except they return multiple rows, and they can reference tables in the nearby FROM clause. LATERAL can be thought of as a for-each loop.

Let's look at an example. Instead of taking the average (AVG) of the power_usage across electrical runs, let's sum up the total load. We'll accomplish this by using LATERAL in the recursive case.

WITH RECURSIVE power_chain AS (     -- Base case: start with sensors who don't have children     SELECT          s.id,         s.name,         s.previous_sensor_id,         0::float as power_usage,         ARRAY[s.name]::VARCHAR[] as chain     FROM sensors s     JOIN events e ON s.id = e.sensor_id     WHERE NOT EXISTS (         SELECT 1          FROM sensors child          WHERE child.previous_sensor_id = s.id     )    AND e.date >= NOW() - INTERVAL '1 day'         UNION ALL     -- Recursive case: recurse through parent sensors     SELECT          s.id,         s.name,         s.previous_sensor_id,         pc.power_usage + usage.total,         s.name || pc.chain     FROM sensors s      JOIN power_chain pc ON s.id = pc.previous_sensor_id,     LATERAL (SELECT SUM(e.power_usage) as total FROM events e where e.sensor_id = pc.id) as usage     ) SELECT      array_to_string(chain, ' <- ') as complete_path,     power_usage FROM power_chain WHERE previous_sensor_id IS NULL; 

Base case

The base case in this example has mostly stayed the same. The difference is instead of using an array to gather all the power_usage's, we start with a default power_usage of 0. We'll add to this as we recurse.

Recursive case

The recursive case is similar to the previous example except for the addition of LATERAL. As mentioned, we can think of a lateral join as a for-each loop. Here, we are saying that for each sensor in the chain (for each recursive step), get all the events for the sensor and find the sum of the power_usage. Then, in SELECT, we add the total power_usage of the current sensor to the running total of all the sensors in the chain. 

Query

Finally, we don't need to provide any aggregate functions in the query; the recursive query has already calculated the total power_usage. We can SELECT the power_usage to get the running total.

When to Use Recursive Queries

Recursive queries shine when querying for hierarchical data in a tree or graph-like data structure. These data structures generally don't have a predefined length, and we need to know how deep we need to query ahead of time. On the flip side, using recursive queries can add a performance penalty and can be easily prone to out-of-memory issues due to logic errors in setting up recursive queries or when the dataset is huge.

Advantages of using recursive queries:

  • Make traversing and querying hierarchical data possible

  • More effective than multiple self-joins

  • Can simplify the logic of nested SQL commands (easier to read than using many subqueries)

Disadvantages of using recursive queries:

  • Misdefined recursive queries can cause runaway recursion (recursive queries that don't stop until the system crashes)

  • Recursive queries add a performance hit for large datasets

  • Complex recursive queries can be more difficult to debug

Optimizing Recursive Queries

To combat the disadvantages of using recursive queries, we can take into account some optimization techniques. 

Indexes

Indexes are the cornerstone of all PostgreSQL query optimizations. Ensuring that the columns a recursive query joins against are indexed is a key factor in boosting performance. For instance, in the electrical system example, the columns that would benefit from indexes are previous_sensor_id and sensor_id.

UNION vs. UNION ALL

In all our recursive queries, we have been using UNION ALL as the glue to combine the results of the base case and the recursive case. We have two options here, though, UNION or UNION ALL.

WITH RECURSIVE power_chain AS (     SELECT          s.name     FROM sensors s         UNION ALL -- UNION ALL         SELECT          s.name     FROM sensors s     JOIN power_chain pc ON s.id = pc.previous_sensor_id ) SELECT      name FROM power_chain;  WITH RECURSIVE power_chain AS (     SELECT          s.name     FROM sensors s     UNION -- UNION     SELECT          s.name     FROM sensors s     JOIN power_chain pc ON s.id = pc.previous_sensor_id ) SELECT      name FROM power_chain; 

The difference is that UNION merges the two datasets and then deduplicates the results (like DISTINCT). UNION ALL merges the two datasets together, and that's it; there is no deduplication step. UNION has its use, but for cases where speed is a priority, use UNION ALL.

Configure PostgreSQL Parameters

PostgreSQL has a whole range of configuration parameters] to tweak to improve the performance of queries. Updating work_mem changes the amount of memory allocated for each operation (like sorting), and updating shared_buffers will change how much memory PostgreSQL uses for its pages.

Both of these parameters will improve the efficiency of recursive queries. Directly related to recursive queries is max_stack_depth, which defines how "deep" recursion can go. Increasing max_stack_depth won't improve performance but will allow recursive queries to navigate further before erroring.

Materialized Views

Materialized views can store the results of expensive queries in what can be thought of as a cache. When recursive queries become too slow and costly to run, we can create a materialized view of the results of the recursive query.

Querying the materialized view is fast since the recursive query doesn't need to be run on every query. Materialized views need to be updated manually. Updating the materialized view will incur the performance penalty of slow recursive queries, but refreshing the materialized view can be deferred to times of low traffic. Timescale's continuous aggregates handle refreshing automatically to get around his materialized view limitation.

Alternatives to Recursive Queries

As you know, PostgreSQL is a versatile tool for handling hierarchical data structures like trees or graphs. Recursive queries are just one of the many ways it can loop through iterative data, showcasing its adaptability and power.

LATERAL joins are one way to iterate over results. Another way to loop through data in SQL is to use PL/pgSQL's LOOP operation (PostgreSQL Procedural Language) inside a custom function we create. Though functions are powerful in their own right, you'll see that creating functions can be more tedious than writing a recursive query to iterate through data.

To show off loops, we'll keep the example basic by creating a function that takes in a sensor_id and prints out all the power_usage events for that sensor:

CREATE FUNCTION print_events(sensor_id_in integer) RETURNS integer AS $$ DECLARE     event RECORD; BEGIN     FOR event IN       SELECT * from events e WHERE e.sensor_id = sensor_id_in     LOOP         RAISE NOTICE '%: %', event.sensor_id, event.power_usage;     END LOOP;     RETURN 1; END; $$ LANGUAGE plpgsql;         SELECT * FROM print_events(4);

There are many moving pieces in creating this simple function. First, we define the function, its name, the arguments it's going to take, and what it returns. Next is the DECLARE block, where we set up the variables we're going to use and their types. Finally, the code. This is where we define the logic of the function—in this case, looping through all events.

While this is a basic example, it effectively demonstrates the potential complexity of using functions to loop through data. Functions in PostgreSQL are adept at encapsulating functionality, but when it comes to handling hierarchical data, the true power lies in recursive queries.

Conclusion

As developers, navigating hierarchical data in SQL can be challenging, but recursive queries using Common Table Expressions (CTEs) make it easy.

By breaking down the problem into a base case and recursive case, we can easily traverse tree and graph data structures. While recursive queries may have some performance considerations, techniques like indexing, parameter tuning, and materialized views can help optimize their execution.

As the complexity of our data grows, the ability to effectively harness recursive queries will become increasingly essential in our toolkits as software engineers. By mastering recursive queries, we can write more efficient and maintainable code to solve the ever-evolving data challenges we face.

Read more

  • How to Use a Common Table Expression (CTE) in SQL

  • PostgreSQL Performance Tuning: Key Parameters

  • PostgreSQL Performance Tuning: Optimizing Database Indexes

  • Postgres Materialized Views, The Timescale Way

On this page

    Try for free

    Start supercharging your PostgreSQL today.