Window Functions Rollups and Funnels Against Supabase Postgres Without an Extract Step

Build Supabase dashboards in plain SQL, and know when to stop.

· 9 min read
Cover illustration for “Window Functions Rollups and Funnels Against Supabase Postgres Without an Extract Step”
Supabase Analytics · November 11, 2026 · 9 min read · 1,979 words

Supabase teams can build analytics and dashboards with window functions, rollups, and funnel queries against their existing Postgres tables, without an extract step. SQL functions, an application server, and a chart library are enough when the data is local and analytical load remains manageable. A governed layer helps when shared metric definitions, external data, or agent access need more than direct SQL can safely offer.

What window functions, rollups, and funnels actually do inside Postgres

Postgres window functions calculate across rows related to the current row without collapsing the result set. A GROUP BY aggregation returns one row per group, while a window function preserves each input row and attaches context from the group. That distinction enables event-level analysis without losing individual records. RANK(), LAG(), LEAD(), and running totals with SUM() OVER all belong to this native SQL toolkit.

The window definition controls which rows enter the calculation. PARTITION BY separates groups, ORDER BY establishes sequence, and frame clauses such as ROWS BETWEEN and RANGE BETWEEN delimit the calculation. Rollups instead summarize records into groups, while funnels use event sequences to measure progression through defined steps. These analytical patterns use features that already exist in Supabase Postgres and need no extension, plugin, or movement of data.

How do you get analytics and dashboards for your Supabase project?

A minimal no-extract stack consists of SQL functions called by the application server and results rendered by a chart library. Each function owns a concern, such as conditional KPIs, a time series, or a conversion funnel. There is no separate pipeline or scheduled sync. The dashboard reads analytical results from the database that already holds the application records, rather than from a second copy that must be kept current.

Inside those functions, Postgres uses count(*) filter (where …) to calculate conditional KPIs in a single scan and percentile_cont to describe latency and response-time distributions. For time series, date_trunc groups events into periods and generate_series supplies periods with no activity. Empty days still belong on the chart. Window functions then provide running totals and week-over-week deltas over those results.

Time and authorization need equally explicit treatment. date_trunc('day', now()) follows the database session’s TimeZone, so the function should accept an IANA timezone parameter and truncate in that timezone to reflect the viewer’s local day. The caller’s identity also governs access. A function without SECURITY DEFINER runs as the calling user, allowing underlying row-level security policies to apply rather than reproducing role-specific scoping inside each analytical function.

Writing funnel queries with LAG and timestamp deltas

A conversion funnel asks how many users finished each step and how long they took to move from one step to the next. Its source table needs a consistent user_id, a step identifier, and an event timestamp. The calculation depends on the order of events: LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time) puts the previous event’s timestamp on each row, and subtracting it from event_time gives the time between those events.

The previous event must also be the step that starts the intended transition, which LAG(step_name) identifies by looking backward, while LEAD() looks forward. A funnel must test the step sequence as well as the elapsed time, because arrival at checkout does not, by itself, describe which preceding step the user completed.

That requirement determines where filtering belongs in the query. The ordered calculation needs the relevant preceding rows before an outer WHERE step_name = 'checkout' filter or a CASE expression selects transitions for counting. Filtering away earlier steps first removes the context that LAG() needs. The resulting query can aggregate conversion counts and apply percentile_cont to the computed deltas for median and p90 transition times. Both outputs use the same defined sequence, with no need for a separate extraction or a second application query.

Where the no-extract approach holds and where it starts to strain

Direct SQL fits early and mid-scale Supabase projects with tables in the low millions of rows, queries against indexed columns, and few concurrent dashboard readers. It is particularly straightforward when every required dataset already lives in Postgres. Ownership is another practical boundary. One engineer can look after the SQL functions and RLS policies without having to get several teams to agree on metric definitions and access rules.

RLS policies built to give each user access to the application fit poorly with a service account that needs to scan everything, and a bypass leaves the team responsible for a security exception. Analytical queries also compete with application traffic for CPU and memory. Postgres’s row-oriented engine is not shaped for large sequential analytical scans, so removing the extract step does not remove the cost of computation.

JSONB and pooler friction also belong in an honest assessment rather than being hidden behind “direct connection” language. Neither SQL expressiveness nor a working connection proves that a workload fits the deployment. Costs can still rise substantially. A compute upgrade or a doubled bill is an infrastructure trade-off that carries a cost even when the architecture stays small. The diagnostic remains measurable interference between workloads, rather than query volume alone, because early-stage complexity can compound faster than demand.

Materialized views as the primary tool for buying time before extraction becomes necessary

Materialized views extend the useful life of a no-extract stack by storing the results of expensive calculations. Instead of recalculating a window query or rollup for each dashboard request, Postgres computes it at refresh time and exposes the stored result for querying. Repeated reads become cheaper. BoldBI’s benchmark found that materialization reduced query times from seconds to sub-second performance, illustrating why this is the primary in-database response to slow recurring dashboards.

For a team facing that bottleneck, the practical pattern is to materialize the aggregation, index its output columns, and schedule REFRESH MATERIALIZED VIEW CONCURRENTLY at an appropriate cadence. The refresh schedule establishes the freshness trade-off. A metric that tolerates lag can avoid repeated live computation, while a time-sensitive metric offers less room to defer the work.

Materialization does not eliminate the underlying analytical workload. Refreshes still run on the primary or a replica, so fewer calculations do not mean lower peak load during refresh. Stored results also go stale between refreshes and cannot supply data absent from Postgres. Security-invoker functions can give callers a consistent way to access data, but the stored result still needs clear rules for authorization. Invoker execution is not, by itself, a guarantee that source-table RLS protects every materialized row.

The pg_duckdb extension as an in-process columnar accelerator

The pg_duckdb extension embeds DuckDB’s columnar, vectorized execution engine inside Postgres. Qualifying analytical queries can use an execution path optimized for analytical processing while the source data remains in Postgres tables. The extension was developed through collaboration between Hydra, DuckDB Labs, and MotherDuck, and targets installations where installing the extension is possible.

That installation requirement limits its relevance to managed deployments. It is a credible option for self-hosted teams with control over their Postgres installation, while availability on managed Supabase projects depends on platform support. Platform support comes before performance evaluation. Where installation is possible, session-level routing can direct qualifying aggregation queries to DuckDB, replacing the standard row-based executor for those queries.

The strongest candidates include dashboard aggregations over large tables, join-heavy cohort analysis, and exploratory queries that outrun available indexes. Some analytical workloads over millions of rows can run dramatically faster through this path. That is not a universal speed guarantee. The extension also lets SQL query external Parquet files from object storage, so teams have a path to a lightweight analytical layer without a full warehouse.

Why agents querying production Postgres directly is the riskiest version of no-extract

Agents inherit the risks of direct analytical SQL but can exercise them more frequently and with less human oversight. Generated SQL is not inherently constrained to indexed paths, so an agent can issue full-table scans against the production primary. Read access can still consume substantial resources. A service-role connection poses a separate risk because it bypasses RLS entirely, putting row-level authorization outside the checks the database normally makes.

Postgres creates new tables with RLS disabled by default. An agent that can access a table before its policies are enabled may therefore read rows it should be barred from, even when the query seems to work correctly. Permissions on newly reachable tables are part of the analytical security boundary as well as a concern for application endpoints.

For teams allowing agent access, the safe pattern has three layers. A dedicated read-only role uses default_transaction_read_only = on, a statement_timeout, and grants limited to required tables. RLS then enforces row-level authorization on every reachable table without a bypass. A governed intermediary gives agents pre-modeled, pre-calculated datasets in place of raw production tables to scan.

An LLM can express date truncation, timezone handling, or null treatment differently across generated queries, producing inconsistent answers to what appears to be the same question. Stable definitions reduce that variation. The central argument for governance is therefore accuracy and reproducibility, alongside protection against slow queries.

How a governed data layer serves both human dashboards and AI agents from the same definitions

A modeled, pre-calculated dataset gives a dashboard and an agent the same rules for their analysis. Both consume a defined metric rather than independently reconstructing it from production records. The definition becomes the common reference point. An “Active User” metric defined once can serve the CEO’s dashboard and an agent’s context window without allowing each interface to choose its own interpretation.

The architectural pattern models Supabase data into governed datasets, including Parquet queried through DuckDB, and exposes them through an MCP server or API. Human interfaces and agents read through that shared access layer. Authorization remains necessary at the access layer, but agents no longer need a production service-role connection to answer analytical questions.

The same layer can model Stripe revenue, CRM stage, and Postgres events together without ETL into a warehouse. This broadens the analytical scope beyond what queries over existing Postgres tables can answer alone. It also changes the no-extract claim. Parquet datasets are derived analytical representations, so this architecture uses copies to separate workloads.

The Model Context Protocol’s specification revision of 2026-07-28 added a stateless protocol core that supports horizontal scaling. A single MCP server can expose modeled datasets to compliant AI clients without bespoke connectors for each client. The protocol standardizes access, while metric meaning still comes from the governed definitions, and Postgres is still the source of truth for the application data.

Deciding when to stay in raw Postgres SQL and when to reach for a governed layer

The decision turns on where a workload belongs. Raw SQL remains appropriate for small to mid-sized tables, indexed queries, few concurrent readers, and analyses confined to data already in Postgres. Team ownership simplifies that choice. Human dashboards built by the team that owns the schema can share SQL functions and policies without introducing another analytical system.

Strictly constrained agent access can remain within that boundary when it uses a dedicated read-only role and tight grants. General analytical agents give teams more reason to use governance because generated queries can put safety and accuracy at risk at any scale. Shared reporting creates another clear trigger. When a dashboard, an agent workflow, and a Slack report must agree, one metric definition is more dependable than several independently written queries.

A governed layer also becomes appropriate when analytical load measurably harms application performance or when payments, CRM, and ad-spend data must join the analysis. Those needs justify additional architecture. They do not justify modeling every possible object before anyone can ask a useful question. The initial scope should cover the five KPIs that measure business health, namely revenue, churn, acquisition cost, activation, and daily active users.

Supabase Postgres remains the ground truth in either design. Extraction is optional overhead while native SQL, workload isolation needs, and consumer permissions fit the task. Once they do not, a governed layer should extend that truth.

More in Supabase Analytics