AdvancedCTEs & Recursive

Recursive CTE: calculate compound interest over years

The query

SQL
WITH RECURSIVE compound AS (
  SELECT
    1 AS year,
    10000.00 AS principal,
    10000.00 * 0.08 AS interest,
    10000.00 * 1.08 AS balance

  UNION ALL

  SELECT
    year + 1,
    balance AS principal,
    balance * 0.08 AS interest,
    balance * 1.08 AS balance
  FROM compound
  WHERE year < 20
)
SELECT
  year,
  ROUND(principal, 2) AS principal,
  ROUND(interest, 2) AS annual_interest,
  ROUND(balance, 2) AS end_balance
FROM compound;
Tested against PostgreSQL 16

Note

Recursive CTE for financial modeling. Shows 20 years of 8% compound growth without procedural code.