A comprehensive demonstration of how PostgreSQL and SQL queries can answer critical growth and marketing questions for SaaS businesses
This repository demonstrates the power of PostgreSQL for SaaS analytics by providing a realistic database schema, sample data, and comprehensive SQL queries that answer key growth questions for a project management SaaS application.
Run the entire project with a single command: docker compose up
The SQL queries included in this project are inspired by a large scale real-world project I developed for an enterprise client.
You are most welcome to use this code in your commercial projects, all that I ask in return is that you credit my work by providing a link back to this repository. Thank you & Enjoy!
- π³ One-Command Setup -
docker compose upgets everything running - π Interactive Jupyter Notebook - Visual analytics with Plotly charts
- ποΈ Realistic Database - 1000+ users, 12 months of behavioral data
- π° 50+ SQL Queries - All critical SaaS metrics covered
- π Beautiful Visualizations - MRR trends, cohort retention, conversion funnels
- π― Production-Ready Schema - Optimized indexes and relationships
- π Multi-dimensional Analysis - Channel, geographic, and plan-based insights
The easiest way to get started:
git clone <your-repo-url>
cd postgres_demo
docker compose upThat's it! This single command will:
- β Start PostgreSQL with sample data (1000+ users, 12 months history)
- β Launch Jupyter notebook with interactive analytics
- β Set up all necessary Python libraries for visualization
- β Make everything accessible via your browser
Access the services:
- π Jupyter Notebook: http://localhost:8888 (Interactive analytics dashboard)
- ποΈ PostgreSQL: localhost:5432 (Direct database access)
- π§ pgAdmin (optional):
docker compose --profile pgadmin upβ http://localhost:8080
- Docker and Docker Compose installed
- 2GB free disk space
- Web browser
If you prefer to install PostgreSQL locally:
./setup_database.shThis script will:
- β Create a PostgreSQL database with sample data
- β Set up realistic user journeys and subscription patterns
- β Generate schema documentation and diagrams
- β Verify the installation with key metrics
If you prefer manual setup:
-
Create the database:
CREATE DATABASE saas_analytics_demo; CREATE USER saas_user WITH PASSWORD 'demo_password'; GRANT ALL PRIVILEGES ON DATABASE saas_analytics_demo TO saas_user;
-
Load the schema:
psql -U saas_user -d saas_analytics_demo -f schema.sql
-
Import sample data:
psql -U saas_user -d saas_analytics_demo -f sample_data.sql
-
Generate schema diagram:
python3 generate_erd.py
Our schema models a realistic SaaS project management application with three subscription tiers:
- π₯ Users - Customer accounts with signup attribution
- π³ Subscriptions - Plan history and billing information
- π Projects - User-created projects (core product value)
- β Tasks - Project tasks (engagement indicator)
- π« Team Memberships - Collaboration features
- π° Revenue Events - All financial transactions
- π Analytics Events - User behavior tracking
- π Free - $0/month (3 projects, 1 team member)
- β Basic - $9.99/month (10 projects, 5 team members)
- π Premium - $19.99/month (unlimited projects and team members)
NEW! All analytics queries are now available in an interactive, visual Jupyter notebook!
After running docker compose up, open your browser to http://localhost:8888 to access:
- π Interactive visualizations with Plotly and Matplotlib
- π Step-by-step analysis of all key SaaS metrics
- π Beautiful charts for MRR, churn, conversion, and retention
- π― Complete conversion funnels with visual flow
- π Geographic and channel performance analysis
- π‘ Customer Lifetime Value (LTV) calculations
The notebook (notebooks/SaaS_Analytics_Demo.ipynb) covers:
- Key Metrics Overview Dashboard
- Revenue & MRR Analytics
- Conversion & Upgrade Analysis
- Retention & Churn Tracking
- Engagement & Activation Metrics
- Marketing Channel Performance
- Customer Lifetime Value
- Complete Conversion Funnel
-- Monthly Recurring Revenue by Plan
SELECT
p.name as plan,
SUM(CASE
WHEN s.billing_cycle = 'monthly' THEN s.mrr
WHEN s.billing_cycle = 'annual' THEN s.mrr / 12
END) as monthly_recurring_revenue
FROM subscriptions s
JOIN plans p ON s.plan_id = p.id
WHERE s.status = 'active'
GROUP BY p.name;-- Free to Paid Conversion Analysis
WITH conversion_funnel AS (
SELECT
COUNT(DISTINCT u.id) as total_signups,
COUNT(DISTINCT CASE WHEN s.plan_id != 1 THEN u.id END) as paid_conversions
FROM users u
LEFT JOIN subscriptions s ON u.id = s.user_id AND s.status = 'active'
)
SELECT
total_signups,
paid_conversions,
ROUND(paid_conversions * 100.0 / total_signups, 2) as conversion_rate_pct
FROM conversion_funnel;-- Cohort Retention by Plan
SELECT
DATE_TRUNC('month', u.created_at) as cohort_month,
p.name as plan,
COUNT(DISTINCT u.id) as cohort_size,
COUNT(DISTINCT CASE
WHEN u.last_login_at >= DATE_TRUNC('month', u.created_at) + INTERVAL '1 month'
THEN u.id
END) * 100.0 / COUNT(DISTINCT u.id) as retention_1_month_pct
FROM users u
JOIN subscriptions s ON u.id = s.user_id
JOIN plans p ON s.plan_id = p.id
WHERE s.status = 'active'
GROUP BY DATE_TRUNC('month', u.created_at), p.name
ORDER BY cohort_month DESC;Run these queries in analytics_queries.sql to get instant insights:
| Metric | Description |
|---|---|
| π° MRR Growth | Monthly recurring revenue trends |
| π Conversion Rates | Free-to-paid conversion analysis |
| π Churn Analysis | Customer retention and churn patterns |
| π€ ARPU by Plan | Average revenue per user segmentation |
| π― Activation Funnel | User onboarding and activation rates |
| π Geographic Performance | Revenue and conversion by country |
| π± Channel Attribution | Marketing channel effectiveness |
This database schema and query collection can answer 50+ critical SaaS questions, including:
- What's our MRR growth rate by plan?
- Which plan contributes most to revenue?
- What's the average LTV by customer segment?
- What percentage of free users upgrade to paid?
- How long does it take users to upgrade?
- Which features drive plan upgrades?
- How does churn vary by plan?
- What's our cohort retention at 30/60/90 days?
- Which user behaviors predict churn?
- Which acquisition channels bring the best customers?
- Where are the biggest funnel drop-offs?
- How do engagement patterns differ by plan?
See key_questions.md for the complete list of analytics questions.
postgres_demo/
βββ π README.md # This file
βββ π key_questions.md # Comprehensive list of analytics questions
βββ ποΈ schema.sql # Complete PostgreSQL schema
βββ π sample_data.sql # Realistic sample data generation
βββ π analytics_queries.sql # 50+ analytical SQL queries
βββ πΌοΈ generate_erd.py # Schema diagram generator
βββ βοΈ setup_database.sh # One-command setup script
βββ π docker-compose.yml # Docker setup (optional)
βββ π schema_diagram.png # Visual database schema
For a completely isolated setup using Docker:
# Start PostgreSQL with Docker
docker-compose up -d
# Run setup (connects to Docker instance)
./setup_database.sh- Extend the schema in
schema.sqlwith new tables or columns - Update sample data in
sample_data.sqlto populate new fields - Write queries in
analytics_queries.sqlto analyze the new data - Regenerate ERD with
python3 generate_erd.py
Edit the plans table in schema.sql:
INSERT INTO plans (name, price_monthly, price_annual, max_projects, max_team_members, features) VALUES
('enterprise', 49.99, 499.90, -1, -1, '{"priority_support": true, "sso": true, "custom_integrations": true}');- Replace sample data with actual customer data
- Connect to your existing user authentication system
- Integrate with payment processors (Stripe, PayPal, etc.)
- Add ETL processes for ongoing data updates
- SaaS Metrics 2.0 - David Skok's comprehensive SaaS metrics guide
- The SaaS Growth Playbook - Growth strategies and metrics
- PostgreSQL Performance Tuning - Optimizing analytical queries
- Time-series analysis for trend detection
- Cohort analysis for retention insights
- Predictive modeling for churn prevention
- Real-time dashboards with materialized views
- Data warehousing patterns for analytics at scale
We welcome contributions! Here's how you can help:
- π Report issues - Found a bug or have a suggestion?
- π Improve queries - More efficient SQL or additional analytics
- π Add metrics - New KPIs or industry-specific measurements
- π§ Enhance tooling - Better setup scripts or visualization tools
git fork <repo-url>
git clone <your-fork>
cd postgres_demo
# Make your changes
# Test thoroughly
git commit -m "Add new churn prediction query"
git push origin feature/churn-prediction
# Open a pull requestβ Kindly star this repository if it helped you understand SaaS analytics with PostgreSQL, Thanks & much appreciated, Warm regards, Danny.
