Use a reusable SQL function to return per-customer SaaS subscription prices directly inside PostgreSQL.
Keeping pricing logic in the database lets engineering, finance, and analytics teams share one trusted source of truth. It also removes duplicated business logic from application code and scheduled jobs.
The function outputs the total subscription price based on plan name, seat count, and currency. You can embed it in SELECT, INSERT, or UPDATE statements, or expose it through a view or API.
Use CREATE OR REPLACE FUNCTION with a CASE expression for tiered pricing. Store rates in a lookup table for maximum flexibility, or hard-code values for speed. Mark the function IMMUTABLE so PostgreSQL can cache results.
1️⃣ Define input parameters: plan_name TEXT, seat_count INT, currency TEXT DEFAULT 'USD'.
2️⃣ Return NUMERIC(10,2) to avoid rounding errors.
3️⃣ Handle unsupported plans with an EXCEPTION.
Join Customers to Orders, aggregate seat counts, and call price_saas() to compute monthly recurring revenue (MRR) or upcoming invoices—all in one query.
Cache lookups in a CTE, index plan_name, and validate seat_count > 0 before calling the function. Version your pricing table so historical invoices always match past rates.
Hard-coding rates in every query: centralize logic in a function or table.
Forgetting to mark IMMUTABLE: PostgreSQL skips optimizations if you leave the setting out.
Introduce a new row in the pricing table or add a CASE branch. Re-run tests and backfill only future invoices to preserve auditability.
Yes. Replace the CASE block with a SELECT FROM pricing WHERE plan_name = $1. This keeps business users out of source control and allows effective-date pricing.
Add a discount_percent column to Orders or Customers, then multiply the function result by (1 - discount_percent) in the calling query.