Skip to content
ImagineWorld

PostgreSQL

node_idnode-book_ai-ready-postgresql-18_chapter-13-postgresql
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titlePostgreSQL
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Postgres provides a rich set of analytics functions that help users perform advanced data analysis directly within the database. They can quickly extract insights, create reports, and perform advanced calculations, such as running totals, rankings, moving averages, and complex summaries.

Ideally, the analytics functions are applied to an analytics-optimized data model, such as a star schema, that was replicated from one or more transactional systems and denormalized to support efficient querying.

Analytics functions usually do not modify data, except to produce intermediate results, and they follow the same format as simple SELECT queries but offer more powerful grouping, aggregation, subquerying, and windowing capabilities.

In this chapter, we will build on the star schema developed in Chapter 12*,* Transforming the Data for Analytics and walk you step by step through groups, aggregates, window functions, and common table expressions.

The chapter covers the following topics:

  • PostgreSQL analytics functions and how they help with reporting/insights
  • Grouping and aggregate calculations (such as totals, averages, and counts)
  • Advanced grouping for subtotals: GROUPING SETS, ROLLUP, CUBE
  • Window functions (ranking, running totals, percentiles, and comparisons)
  • CTEs and recursive CTEs for simplifying complex queries and working with hierarchies

All examples in the chapter are available in the GitHub repo under  psql_scripts/sample_scripts/chapter_ 13``.sql.

PostgreSQL’s analytics functions help us assemble and organize extensive record sets into groups and hierarchical groups, calculate aggregates, such as sums or averages, work with windows into the data, and execute complex calculations and recursions:

  • Groups and a ggregates allow us to assemble records with shared data values in one or more columns (e.g., all blue shirts) and to calculate aggregates (e.g., total sales).
  • Grouping s ets make it easy to specify multiple groups, for example, all shirts, all shirts and colors, and all shirts and sizes and colors, and calculate the same aggregates in one query.
  • Rollups take a list of groups, for example, category, color, and size, and automatically generate a hierarchy of grouping sets and calculate aggregates over those sets.
  • Cubes are like rollups, except that they create multiple hierarchies and permutations, and not just one.
  • Window f unctions place individual records in the context of the dataset and allow the calculation of percentiles, rankings, and so on.
  • Common t able e xpressions (CTE s) help us simplify complex queries by decomposing them into simple building blocks. Recursive CTEs allow us to work with hierarchical datasets, such as bills of materials or organizational structures.

All our analytics examples build on the star schema that we defined in Chapter 12*,* Transforming the Data for Analytics (see Figure 13.1). This will make the queries shorter, as we don’t have to repeat all the joins in every query, and much faster, as we leverage the precalculated dimensions and facts, and their analytics-focused indexes.

Groups and aggregates are fundamental analytics building blocks. Sets of rows are defined by shared values in columns (or expressions on columns), and aggregates (SUM, MIN, MAX, etc.) are calculated based on those groups of rows.

This sample query shows which brand has products in specific price ranges, how much was sold, and the total sales turnover, but only for those products originating in the USA, and total sales exceeding 10,000. This query uses two dimensions (dim_product and dim_date) for filtering and one dimension (brand and category from dim_product) for aggregation:

SELECT
brand, category,
FORMAT ('%2s - %s',
DIV(current_price, 10) *10,
(DIV(current_price, 10)+1)*10) AS price_range,
COUNT(*) nbr_products,
ROUND(AVG(current_price),2) AS avg_price,
SUM (fact_sales.sales_amount) AS total
FROM dim_product
NATURAL JOIN fact_sales
JOIN dim_date ON fact_sales.date = dim_date.date_key
WHERE co_alpha3_code = 'USA' AND year = 2025
GROUP BY brand, category, price_range
HAVING SUM(fact_sales.sales_amount) > 10000
ORDER BY brand, category, price_range ASC;

When we execute that query in our central analytics database, we get a report that leverages the facts at the center of the star schema and uses the dimensions for filtering and aggregation:

brand | category |price_range|nbr_products|avg_price|total
----------------+-----------+-----------+------------+---------+--------
Calvin Klein |Accessories|80 - 90 | 304 | 82.16 |24976.64
Diesel |Pants |90 - 100 | 3556 | 98.58 |350550.48
Gap |Pants |90 - 100 | 1259 | 98.44 |123935.96
Gap |Polos |130 - 140 | 1070 | 131.36 |140555.20
Gap |Shirts |30 - 40 | 6013 | 31.72 |190737.50
Nike |Polos |130 - 140 | 334 | 131.14 |43800.76
Nike |Sportswear |20 - 30 | 814 | 27.44 |22336.16
Polo Ralph Laure|Pants |90 - 100 | 299 | 98.41 |29424.59
Tommy Hilfiger |Accessories|80 - 90 | 302 | 82.06 |24782.12
Tommy Hilfiger |Shirts |30 - 40 | 579 | 31.72 |18365.88
…

The WHERE clause filters out records (alpha3_code = 'USA' AND year = 2025). The HAVING clause filters out groups. HAVING SUM (fact_sales.sales_amount) > 10000 filters out all groups that do not have sufficient total sales.

PostgreSQL provides several functions for arithmetic aggregates:

  • AVG returns the average value
  • COUNT returns the number of values
  • COUNT DISTINCT returns the number of unique values
  • MAX returns the maximum value
  • MIN returns the minimum value
  • SUM returns the sum of all or distinct values (SUM (DISTINCT ...))

Other aggregate functions, such as ARRAY_AGG or JSONB_OBJECT_AGG, compile values into arrays or documents, but are rarely used for analytics.

In our preceding example, we used the GROUP BY clause with three individual columns that defined one grouping of the data: brand, category, and price_range.

The clause offers several refinements that allow us to create hierarchical groups with subtotals for each group:

  • GROUP BY GROUPING SETS: Arbitrary groups of columns
  • GROUP BY ROLLUP: Hierarchical groups of columns
  • GROUP BY CUBE: All permutations of a set of columns

Subtotals are a standard capability in business reports. Before this capability was introduced in PostgreSQL 9.5, users had to resort to complex queries or third-party tools to create them. Let’s take a look at each one and show why they have helped make PostgreSQL a potent tool for analytics.

GROUP BY GROUPING SETS allows us to create several groups in the same query. For example, we can modify the preceding query to group by brand and price range, by brand, and by all. For each grouping, we will get the corresponding aggregates:

SELECT
brand, category,
FORMAT ('%2s - %s',
DIV(current_price, 10) *10,
(DIV(current_price, 10)+1)*10) AS price_range,
COUNT(*) nbr_products,
ROUND(AVG(current_price),2) as avg_price,
SUM (fact_sales.sales_amount) as total
FROM dim_product
NATURAL JOIN fact_sales
WHERE co_alpha3_code = 'USA'
GROUP BY
GROUPING SETS ((brand, category, price_range), (brand, category), (brand), ())
HAVING SUM(fact_sales.sales_amount) > 5000
ORDER BY brand, category, price_range ASC NULLS LAST;

This query provides us the same report, but this time, with a hierarchical set of subtotals for b r and, category, and price _ range – the groups defined in the GROUPING SETS clause:

brand | category | price_range | nbr_products | avg_price | total
-------------+------------+-------------+--------------+-----------+-----
Calvin Klein | Accessories| 80 - 90 | 304 | 82.16 | 24976.64
Calvin Klein | Accessories| | 304 | 82.16 | 24976.64
Calvin Klein | Shirts | 30 - 40 | 304 | 31.79 | 9664.16
Calvin Klein | Shirts | | 304 | 31.79 | 9664.16
Calvin Klein | | | 608 | 56.98 | 34640.80
Diesel | Pants | 90 - 100 | 3556 | 98.58 | 350550.48
Diesel | Pants | | 3556 | 98.58 | 350550.48
Diese | | | 3556 | 98.58 | 350550.48
…

(At the bottom, … indicates that this is a subset of the query output.)

The NULL LAST clause in ORDER BY helps us make sure that the subtotals appear as the last row of that grouping.

The rollup simplifies the definition of the grouping sets. When we define a rollup for A, B, and C, we automatically get the grouping sets (A, B, C), (A, B), (A), and (), where () denotes all records:

SELECT
brand, category,
FORMAT ('%2s - %s',
DIV(current_price, 10) *10,
(DIV(current_price, 10)+1)*10) AS price_range,
COUNT(*) nbr_products,
ROUND(AVG(current_price),2) as avg_price,
SUM (fact_sales.sales_amount) as total
FROM dim_product
NATURAL JOIN fact_sales
WHERE co_alpha3_code = 'USA'
GROUP BY
ROLLUP (brand, category, price_range)
HAVING SUM(fact_sales.sales_amount) > 10000
ORDER BY brand, category, price_range ASC NULLS LAST;

This query provides us with the same report, also with a hierarchical set of subtotals for b r and, category, and price _ range. Still, this time, the groups were automatically defined by the ROLLUP clause rather than specified manually with the GROUPING SETS clause:

brand | category | price_range | nbr_products | avg_price | total
-------------+------------+-------------+--------------+-----------+------
Calvin Klein |Accessories | 80 - 90 | 304 | 82.16 | 24976.64
Calvin Klein |Accessories | | 304 | 82.16 | 24976.64
Calvin Klein | | | 608 | 56.98 | 34640.80
Diesel |Pants | 90 - 100 | 3556 | 98.58 | 350550.48
Diesel |Pants | | 3556 | 98.58 | 350550.48
Diesel | | | 3556 | 98.58 | 350550.48
Gap |Pants | 90 - 100 | 1259 | 98.44 | 123935.96
Gap |Pants | | 1259 | 98.44 | 123935.96
Gap |Polos | 130 - 140 | 1070 | 131.36 | 140555.20
Gap |Polos | | 1070 | 131.36 | 140555.20
Gap |Shirts | 30 - 40 | 6013 | 31.72 | 190737.50
Gap | Shirts | | 6013 | 31.72 | 190737.50
Gap | | | 8342 | 54.57 | 455228.66
…

(At the bottom, … indicates that this is a subset of the query output.)

Rollups are most often used to aggregate data in hierarchical relationships, for example, by year, quarter, and month:

SELECT
year, quarter, month,
SUM (fact_sales.sales_amount) AS total
FROM dim_date
JOIN fact_sales ON fact_sales.date = dim_date.date_key
WHERE year IN (2025)
GROUP BY
ROLLUP (year, quarter, month)
ORDER BY year, quarter, month ASC NULLS LAST;

This query provides a hierarchical set of subtotals for year, quarter, and month, with the grouping hierarchy defined by the ROLLUP clause:

year | quarter | month | total
------+---------+-------+------------
2025 | 1 | 1 | 154197.24
2025 | 1 | 2 | 121519.18
2025 | 1 | 3 | 148577.30
2025 | 1 | | 424293.72
2025 | 2 | 4 | 139753.92
2025 | 2 | 5 | 150402.01
2025 | 2 | 6 | 136852.22
2025 | 2 | | 427008.15
...

(At the bottom, … indicates that this is a subset of the query output.)

Whereas rollups help us analyze data in hierarchical relationships, cubes generate all permutations.

The rollup of (A, B, C) gives us four grouping sets:

  • (A, B, C)
  • (A, B)
  • (A)
  • ()

Cubes give us all eight possible permutations:

  • (A, B, C)
  • (A, B)
  • (A, C)
  • (B, C)
  • (A)
  • (B)
  • (C)
  • ()
SELECT
brand, category,
FORMAT ('%2s - %s',
DIV(current_price, 10) *10,
(DIV(current_price, 10)+1)*10) AS price_range,
COUNT(*) nbr_products,
ROUND(AVG(current_price),2) as avg_price,
SUM (fact_sales.sales_amount) as total
FROM dim_product
NATURAL JOIN fact_sales
WHERE co_alpha3_code = 'USA'
GROUP BY
CUBE (brand, category, price_range)
HAVING SUM(fact_sales.sales_amount) > 10000
ORDER BY brand, category, price_range ASC NULLS LAST;

This provides additional groups and aggregates, for example, for category and price _ range:

brand | category | price_range | nbr_products | avg_price | total
----------------+-------------+-------------+--------------+-----------+----
| Accessories | 80 - 90 | 666 | 82.11 | 54685.46
| Accessories | | 666 | 82.11 | 54685.46
| Pants | 90 - 100 | 5105 | 98.53 | 503017.02
| Pants | | 5105 | 98.53 | 503017.02
| Polos | 130 - 140 | 1438 | 131.31 | 188825.06
| Polos | | 1438 | 131.31 | 188825.06
| Shirts | 30 - 40 | 6922 | 31.72 | 219590.93
| Shirts | | 6922 | 31.72 | 219590.93
| Sportswear | 20 - 30 | 1069 | 27.42 | 29312.85
| Sportswear | | 1069 | 27.42 | 29312.85
| | 130 - 140 | 1438 | 131.31 | 188825.06
| | 20 - 30 | 1069 | 27.42 | 29312.85
| | 30 - 40 | 6922 | 31.72 | 219590.93
| | 80 - 90 | 666 | 82.11 | 54685.46
| | 90 - 100 | 5105 | 98.53 | 503017.02
| | | 15200 | 65.49 | 995431.32

(Near the top, … indicates that this is a subset of the query output.)

Window functions differ significantly from groupings. A window function performs a calculation across a set of table rows that are somehow related to the current row. Window functions do not group rows into a single output row, unlike aggregate functions. They put a row into a context defined by a window over some or all the rows of the table.

For example, if we want to compare the price of a product with the average price of all products for the same brand, we place the current row, with the price of the current product, in the context of all rows for that brand.

In the following example, OVER (PARTITION BY brand) defines the window of rows (the context), with which we compare the current row – in that case, all the rows that refer to the same brand. This helps us put the price of an individual product into the context of the average prices for that brand:

SELECT DISTINCT brand, label, current_price AS price,
ROUND(AVG(current_price) OVER (PARTITION BY brand),2) AS avg_brand
FROM dim_product
ORDER by brand, label ASC;

The output shows us the price of the individual products compared to the average price for all products in the window defined by the product’s brand:

brand | label | price | avg_brand
-------------------+-----------------------------------------+--------+-----------
Adidas | Adidas Lifestyle Sneakers | 131.32 | 79.37
Adidas | Adidas Track Pants | 27.42 | 79.37
Aéropostale | Casual Leather Jacket by Aeropostale | 81.96 | 81.96
Boss | Casual Leather Jacket by Boss | 82.16 | 90.14
Boss | Chinos - casual, by Boss | 98.59 | 90.14
Boss | Dress shirt by Boss | 31.93 | 90.14
Boss | Polo shirt, Boss | 131.35 | 90.14
Boss | Sports coat - business casual, by Boss | 98.57 | 90.14
Boss | Trench coat - always perfect, by Boss | 98.37 | 90.14
Brioni | Suit coat - business perfect, by Brioni | 98.43 | 98.43
…

Window functions can also take row order into account, for example, to calculate rank, running totals, and percentiles.

In the following example, we define a window, w, as including all the rows from the beginning up to the current row in descending order by brand sales. The window, w, is then used to calculate the running total (line 4), the cumulative percentage (lines 5–8), and order the sales totals (last line), showing the cumulative percentage of total sales (see Figure 13.2):

SELECT RANK() OVER (ORDER BY bs.total_brand_sales DESC) AS rank,
bs.brand,
bs.total_brand_sales AS brand_sales,
SUM(bs.total_brand_sales) OVER w AS running_total,
ROUND(
(SUM(bs.total_brand_sales) OVER w /
SUM(bs.total_brand_sales) OVER ()) * 100, 2)
AS pct_sales
FROM
(SELECT d.brand, SUM(f.sales_amount) AS total_brand_sales
FROM dim_product d
NATURAL JOIN fact_sales f
GROUP BY d.brand) AS bs
-- define a window 'w' to be used in the calculations
-- the window orders by total_brand_sales in descending order
-- and includes all rows from the start of the result set to the current row
WINDOW w AS (ORDER BY bs.total_brand_sales DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
ORDER BY bs.total_brand_sales DESC;

Figure 13.2: Sliding window of the PostgreSQL window function

This provides us a view of the percentage of the sales that a specific product (and all those before it in the list) constitutes of the total:

rank | brand | total_brand_sales | running_total | pct_sales
------+-------------------+-------------------+---------------+-----------
1 | Boss | 488713.41 | 488713.41 | 28.07
2 | Diesel | 410599.62 | 899313.03 | 51.65
3 | Gap | 376663.70 | 1275976.73 | 73.28
4 | Zara | 70783.50 | 1346760.23 | 77.34
5 | Nike | 64346.92 | 1411107.15 | 81.04
6 | Brioni | 58861.14 | 1469968.29 | 84.42
7 | Adidas | 49023.24 | 1518991.53 | 87.23
8 | Tommy Hilfiger | 44856.10 | 1563847.63 | 89.81
9 | Calvin Klein | 32934.02 | 1596781.65 | 91.70
10 | Polo Ralph Lauren | 32376.89 | 1629158.54 | 93.56
11 | Uniqlo | 28461.06 | 1657619.60 | 95.19
12 | Aéropostale | 28112.28 | 1685731.88 | 96.81
13 | Lacoste | 27504.32 | 1713236.20 | 98.39
14 | Eaton | 19848.78 | 1733084.98 | 99.53
15 | Under Armour | 8211.00 | 1741295.98 | 100.00

Window functions are compelling analytics tools, as they allow us to put rows into context – something that is very difficult to do otherwise.

SQL queries can become very complex, often involving multiple levels of nested subqueries, which are hard to understand and maintain.

CTEs help the developer simplify complex queries by decomposing them and reusing prior results. They are especially useful when the same base query (or intermediate result) is referenced multiple times within a larger query or function. CTEs allow the definition of base queries that create temporary, named result sets that flow into a main query – comparable to views that exist only in the context of one query.

The query shown previously can be rewritten as a CTE, and the subquery can be moved into a named base query (brand_sales):

WITH brand_sales
AS (
-- the temp table expression to calculate total sales per brand
SELECT brand, sum(sales_amount) AS total_brand_sales
FROM dim_product dp
NATURAL JOIN fact_sales
GROUP BY brand
ORDER BY total_brand_sales DESC
)
-- main query to rank brands by sales and calculate running totals and percentages
SELECT
RANK() OVER (ORDER BY total_brand_sales DESC) AS rank,
brand, total_brand_sales,
SUM(total_brand_sales) OVER w AS running_total,
ROUND( (SUM(total_brand_sales) OVER w / SUM(total_brand_sales) OVER ()) * 100, 2) AS pct_sales
FROM brand_sales
WINDOW w AS (ORDER BY total_brand_sales DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
ORDER BY total_brand_sales DESC;

This not only improves code readability but also allows us to test the base queries separately!

Table 13.1 describes the general structure of a CTE:

WITHCreates the context for the CTE
aux1 AS ( SELECT … FROM … WHERE … ),Define the first auxiliary statement, which results in a temporary table, aux1, visible only in the context of the CTE
aux2 AS ( SELECT … FROM … WHERE … ),Second auxiliary statement (optional)
…More auxiliary statements (optional)
SELECT … FROM aux1, … WHERE …Principal statement referring to the temporary tables resulting from the auxiliary statements

Table 13.1: The building blocks of a recursive CTE

CTEs are powerful tools that experienced developers use frequently. Besides simplifying complex queries, they can also be used to write recursive queries that iterate through bills of materials or organizational hierarchies.

Recent PostgreSQL releases have addressed some historical performance concerns with CTEs. Before version 12, CTEs were often problematic because each auxiliary query was planned separately, leading to a suboptimal overall plan for the CTE. Today, the planner is smart enough to generate plans that are optimized for the whole CTE. The developer can use the MATERIALIZED clause to control that behavior.

The optional RECURSIVE modifier transforms WITH from a simple syntax feature into a tool that makes it easy to create recursive queries. With RECURSIVE, a WITH query can reference its own output. While recursion can also be implemented using SQL/PL functions, WITH RECURSIVE keeps the logic within a single query.

Exactly like a recursive math function, the recursive CTE consists of a base case and a recursive step that builds initially on the base case and then on its own successive results.

This is a very simple recursive CTE. The base case adds one row to the n column in the temporary sum_to_10 table. The recursive step adds n+1 (initially = 2) to the temporary table and keeps on going until n > 10. The result is a record set with 10 rows:

WITH RECURSIVE sum_to_10 AS (
SELECT 1 AS n
UNION ALL
SELECT n+1 FROM sum_to_10 WHERE n < 10
)
SELECT sum(n) FROM sum_to_10;

Table 13.2 shows the building blocks for a recursive CTE.

WITH RECURSIVE cte_name

Create the context of the CTE, declare it as recursive, and define its temporary working table (corresponding to the name of the CTE).

AS(

SELECT columns FROM table1

WHERE condition

Non-recursive base term evaluated first. The result is placed in the working table.

UNION [ALL]

Include all remaining rows in the result of the recursive query and add them to the working table.

UNION removes duplicates; UNION ALL keeps duplicates.

SELECT columns FROM cte_name

WHERE recursive_condition

Recursive term. The recursive condition and the calculations for the columns can refer to the working table.

)

SELECT columns FROM cte_name;

Primary statement executed against the temporary working table.

Table 13.2: The building blocks of a recursive CTE

The following query illustrates recursive CTEs. It uses the hierarchical organizational structure defined in the auxiliary.sales_organization table (see also Figure 13.3) to calculate each employee’s organizational level.

Figure 13.3: Sample sales organization defined in the auxiliary.sales_organization table

The definition of a recursive CTE starts with the non-recursive base term. In our example, the base term identifies the top of the hierarchy (those without a manager) and adds them to the temporary working table called sales_hierarchy.

The recursive term joins to the temporary table to identify all employees reporting to managers who are already in that table. New records are added to the temporary table, and the process continues until the recursive term returns no more new records:

WITH RECURSIVE sales_hierarchy AS (
-- identify top managers (those without a manager)
SELECT employee_id, first_name, last_name,
territory_id, manager_id, 1 AS level
FROM auxiliary.sales_organization
WHERE manager_id IS NULL
UNION ALL
-- recursively join to find employees under each manager
SELECT so.employee_id, so.first_name,
so.last_name, so.territory_id, so.manager_id, sh.level + 1 AS level
FROM auxiliary.sales_organization so
JOIN sales_hierarchy sh ON so.manager_id = sh.employee_id
)
SELECT employee_id, first_name, last_name, manager_id
FROM sales_hierarchy ORDER BY level, employee_id;

The output shows how the query traverses the hierarchy. The first row (employee E001) is the result of the non-recursive base term. The next four rows are the initial recursions built on the base term:

employee_id | first_name | last_name | sales_target | manager_id
-------------+------------+-----------+--------------+------------
E001 | John | Smith | 0 |
E002 | Jane | Doe | 0 | E001
E003 | Jim | Brown | 0 | E001
E004 | Emily | Davis | 0 | E001
E005 | Michael | Wilson | 0 | E001
E006 | Sarah | Johnson | 0 | E002
E007 | David | Lee | 150007 | E002
E008 | Laura | Garcia | 150008 | E003
E009 | Robert | Martinez | 150009 | E003
E010 | Linda | Rodriguez | 150010 | E004
E011 | James | Hernandez | 150011 | E004
E012 | Barbara | Lopez | 150012 | E005
E013 | William | Gonzalez | 150013 | E005
E014 | Elizabeth | Wilson | 150014 | E006
E015 | Richard | Anderson | 150015 | E006

Note that the recursive part refers to records that have been previously added to the temporary table (in this example, the recursive term joins with the temporary table and increases the value of sh.level by 1).

In the preceding example, we traversed the structure top down. Some questions, such as calculating the manager’s cumulative sales target, require a bottom-up approach. The sales targets at lower levels are first aggregated into a temporary table before the final aggregation:

WITH RECURSIVE bottom_up AS (
-- leaves of the hierarchy (those without subordinates)
SELECT employee_id, first_name, last_name, manager_id, sales_target
FROM auxiliary.sales_organization
WHERE NOT EXISTS
(SELECT 1 FROM auxiliary.sales_organization so
WHERE so.manager_id = auxiliary.sales_organization.employee_id)
UNION ALL
-- aggregate sales targets up the hierarchy
SELECT so.employee_id, so.first_name, so.last_name, so.manager_id,
so.sales_target + bu.sales_target
FROM auxiliary.sales_organization so
JOIN bottom_up bu ON so.employee_id = bu.manager_id
)
SELECT DISTINCT employee_id, first_name, last_name, manager_id,
sum(sales_target) OVER (PARTITION BY employee_id) AS total_sales_target
FROM bottom_up
ORDER BY total_sales_target DESC;

In this case, the non-recursive base term identified eight employees without direct reports (E007, E008, …, E015), and then recursion built up from there:

employee_id | first_name | last_name | manager_id | total_target
-------------+------------+-----------+------------+--------------
E001 | John | Smith | | 1350099
E002 | Jane | Doe | E001 | 450036
E006 | Sarah | Johnson | E002 | 300029
E005 | Michael | Wilson | E001 | 300025
E004 | Emily | Davis | E001 | 300021
E003 | Jim | Brown | E001 | 300017
E015 | Richard | Anderson | E006 | 150015
E014 | Elizabeth | Wilson | E006 | 150014
E013 | William | Gonzalez | E005 | 150013
E012 | Barbara | Lopez | E005 | 150012
E011 | James | Hernandez | E004 | 150011
E010 | Linda | Rodriguez | E004 | 150010
E009 | Robert | Martinez | E003 | 150009
E008 | Laura | Garcia | E003 | 150008
E007 | David | Lee | E002 | 150007

CTEs help developers simplify complex queries by breaking them into auxiliary statements that can be developed and tested individually. That feature alone is already handy!

What makes CTEs truly exciting is that they can help us navigate hierarchical (and graph) structures – something that previously required complex coding. In PostgreSQL 14, the SEARCH clause was added to give developers control over depth-first versus breadth-first search, and CYCLE allows detection of cycles when graphs are not strictly hierarchical.

The SEARCH clause can be used to change the tree traversal from the default breadth-first to depth-first. For example, the addition of SEARCH DEPTH FIRST BY employee_id SET ordercol changes the sequence at which nodes are visited and gives us a new ordercol column to track the traversal:

WITH RECURSIVE hierarchy AS (
…
) SEARCH DEPTH FIRST BY employee_id SET ordercol
SELECT employee_id, first_name, last_name, manager_id, ordercol FROM hierarchy
ORDER BY employee_id;

This changes the traversal of the hierarchy to a depth-first search (subset of the output):

employee_id | first_name | last_name | manager_id | ordercol
-------------+------------+-----------+------------+----------------------
E001 | John | Smith | | {(E001)}
E002 | Jane | Doe | E001 | {(E001),(E002)}
E003 | Jim | Brown | E001 | {(E001),(E003)}
E004 | Emily | Davis | E001 | {(E001),(E004)}
E005 | Michael | Wilson | E001 | {(E001),(E005)}
E006 | Sarah | Johnson | E002 | {(E001),(E002),(E006)}
...

A simple example illustrates the use of the CYCLE clause. Adding CYCLE employee_id SET is_cycle USING path ensures that cycles are detected:

-- sample table for a cyclic data structure
CREATE TABLE test_cycle ( employee_id TEXT PRIMARY KEY, manager_id TEXT );
INSERT INTO test_cycle VALUES ('E001', 'E002');
INSERT INTO test_cycle VALUES ('E002', 'E003');
INSERT INTO test_cycle VALUES ('E003', 'E001');
-- CTE to detect cycles in the hierarchy using the CYCLE clause
WITH RECURSIVE hierarchy AS (
SELECT employee_id, manager_id
FROM test_cycle
--WHERE manager_id IS NULL
UNION ALL
SELECT tc.employee_id, tc.manager_id
FROM test_cycle tc JOIN hierarchy h ON tc.manager_id = h.employee_id )
CYCLE employee_id SET is_cycle USING path
SELECT employee_id, manager_id, is_cycle, path FROM hierarchy ORDER BY path;

This gives us two additional columns, is_cycle and path, which we can use to get visibility into the traversal:

employee_id | manager_id | is_cycle | path
-------------+------------+----------+-------------------------------
E001 | E002 | f | {(E001)}
E003 | E001 | f | {(E001),(E003)}
E002 | E003 | f | {(E001),(E003),(E002)}
E001 | E002 | t | {(E001),(E003),(E002),(E001)}
E002 | E003 | f | {(E002)}
E001 | E002 | f | {(E002),(E001)}
E003 | E001 | f | {(E002),(E001),(E003)}
E002 | E003 | t | {(E002),(E001),(E003),(E002)}
E003 | E001 | f | {(E003)}
E002 | E003 | f | {(E003),(E002)}
E001 | E002 | f | {(E003),(E002),(E001)}
E003 | E001 | t | {(E003),(E002),(E001),(E003)}

Groups, aggregations, window functions, common table expressions, and recursions – PostgreSQL provides us with a wealth of capabilities to analyze data. They all leverage well-designed star schemas with their facts and dimensions to make it easy to write highly effective queries.

While a well-designed analytics-focused schema makes data analysis easier and more efficient, the techniques and capabilities we reviewed here can also be applied directly to normalized schemas. This will mean that we have more complex join statements, but groups, aggregates, CTEs, window functions, and recursions also have their place in the transactional world.

In the next chapter, we will expand our focus from tabular to text data. We will learn how to index, search, and query data in text-focused data columns.