Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A query on a view orders_summary is slow, while the same query written by hand against the base tables with the filter WHERE customer_id = 42 is fast. The view joins four tables and uses a window function. Explain why the planner may not push the filter down, and how you would fix it.

A view is not slow by itself: PostgreSQL inlines it and normally pushes our WHERE clause down to the base tables. But a window function inside the view must see all the rows of its window before our filter is applied, so the planner may only push customer_id = 42 below it when customer_id is the window's partition key; otherwise it computes the window over every order and filters at the end. We confirm this with EXPLAIN (ANALYZE, BUFFERS) on both forms, and fix it by partitioning by customer_id, using a parameterised SQL function, or restructuring and flattening the view.

Why this question is asked

This is a classic production puzzle: the same filter, written by hand, takes 5 milliseconds, and through the view it takes 5 seconds. It looks like views are slow, and teams sometimes ban them after such an incident. Interviewers ask it because the real cause is a precise rule about when a filter may legally move inside a subquery, and knowing that rule lets us keep views and still get fast plans. In this answer, we will recap how PostgreSQL plans a view, see why a window function blocks the filter, read the two plans, and go through the fixes.

1A Quick Recap: How PostgreSQL Plans a View

When a query uses a view, PostgreSQL replaces the view's name with its stored query, as if we had written a subquery in FROM. The planner then tries to flatten that subquery into the outer query, and when it cannot flatten it, it tries to push outer WHERE conditions down into it. For a simple view of joins, both work: WHERE customer_id = 42 reaches the orders table, and an index on orders.customer_id is used. That is why most views cost nothing extra.

Pushing a filter down is only allowed when it cannot change the result. A filter applied before or after a plain join gives the same rows. But some operations look at a whole group of rows to produce each output row, and for those, removing rows early changes the answer.

2Why a Window Function Blocks the Filter

Suppose the view numbers each customer's orders and computes a running total. The window function needs to see every row in its window, a group of rows defined by PARTITION BY, to compute each value. Here is a version of the view where the window is partitioned by something other than the customer.

SQL
CREATE VIEW orders_summary AS
SELECT o.id, o.customer_id, c.name, p.title, s.status, o.created_at, o.total,
rank() OVER (PARTITION BY o.region ORDER BY o.total DESC) AS region_rank
FROM orders o
JOIN customer c ON c.id = o.customer_id
JOIN product p ON p.id = o.product_id
JOIN shipment s ON s.order_id = o.id;
SELECT * FROM orders_summary WHERE customer_id = 42; -- 4.8 s
Step throughCan the filter move inside the view?
  1. Outer query: WHERE customer_id = 42
  2. Does the view contain LIMIT or OFFSET?
    YesFilter applied after the viewNoNext check
  3. Window functions present?
    YesNext checkNoPush the filter down
  4. customer_id in every PARTITION BY?
    YesPush the filter downNoFilter applied after the view
  5. Index scan on orders.customer_id12 rows

5 steps in order. Play them, or step through them one at a time.

A filter may only move below a window when it selects whole partitions.

region_rank says where an order ranks within its region. If PostgreSQL filtered customer 42 first and then ranked, it would rank customer 42's orders only among themselves, and every rank would be wrong. So the planner must compute the window over all orders of every region, and only then apply our filter. With 20 million orders, that means joining and sorting 20 million rows to return 12.

The planner can push a filter below a window only if the filter uses columns that appear in every window's PARTITION BY. Filtering by a partition key removes whole partitions, and each remaining partition still contains all of its rows, so every value is unchanged. The same reasoning applies to other operations: GROUP BY allows pushing only filters on grouping columns, while DISTINCT ON, LIMIT and some set operations block pushdown for similar reasons.

3Reading the Two Plans

We prove it by comparing plans with EXPLAIN (ANALYZE, BUFFERS), which runs the query and shows each step with its real row counts, times, and the pages it read. The thing to look for is where the condition customer_id = 42 appears.

Java
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders_summary WHERE customer_id = 42;
-- Subquery Scan on orders_summary (actual time=4790..4801 rows=12)
-- Filter: (customer_id = 42) <- applied at the very top
-- Rows Removed by Filter: 19999988
-- -> WindowAgg (actual rows=20000000)
-- -> Sort Sort Method: external merge Disk: 1450MB
-- -> Hash Join ... Seq Scan on orders (rows=20000000)
-- Buffers: shared read=410233
EXPLAIN (ANALYZE, BUFFERS) SELECT ... FROM orders o JOIN ... WHERE o.customer_id = 42;
-- -> Index Scan using orders_customer_idx on orders o (rows=12)
-- Index Cond: (customer_id = 42) <- applied at the base table
-- Buffers: shared hit=61
-- Execution Time: 4.9 ms

Notice the line Rows Removed by Filter: nearly 20 million rows were built only to be thrown away, and the sort spilled 1.4 GB to disk. The hand-written query has no window function, or computes it only over 12 rows, which is why it looked equivalent but is not: if the hand-written version also computed region_rank, it would have to do the same full work. Often the fast version is fast because it silently gives a different answer.

4Fix 1: Partition the Window by the Filter Column

If the business meaning allows it, we partition the window by customer_id. A rank of each order within its customer's orders can be computed from that customer's rows alone, so the planner may push the filter down.

Java
rank() OVER (PARTITION BY o.customer_id ORDER BY o.total DESC) AS customer_rank
SELECT * FROM orders_summary WHERE customer_id = 42;
-- Index Cond: (customer_id = 42) -> 5.3 ms

This is only a fix when customer_rank is what the screen really needs. If the screen needs the regional rank, we must keep the regional window and use one of the other fixes.

5Fix 2: A Function With a Parameter, or a Restructured View

When the window must stay regional, we can put the filter inside the query explicitly. A SQL function taking the customer id as a parameter does that, and a simple LANGUAGE sql function returning a table can be inlined by the planner, so it behaves like a view with a built-in filter. Note that the meaning changes: the rank is now computed among the customer's own rows. If we truly need the customer's position among all orders in the region, that value is inherently expensive and belongs in a precomputed table or materialized view refreshed on a schedule.

SQL
CREATE FUNCTION orders_summary_for(p_customer bigint)
RETURNS TABLE (id bigint, title text, status text, total numeric, customer_rank bigint)
LANGUAGE sql STABLE AS $$
SELECT o.id, p.title, s.status, o.total,
rank() OVER (ORDER BY o.total DESC)
FROM orders o JOIN product p ON p.id = o.product_id
JOIN shipment s ON s.order_id = o.id
WHERE o.customer_id = p_customer
$$;
SELECT * FROM orders_summary_for(42); -- 5.1 ms, filter applied first

Another restructuring is to keep the hot path out of the window entirely: the view exposes plain joined columns, and the rare screen that needs the rank computes it in a separate query. And views stacked on views make all of this worse, because each layer may add a window, a DISTINCT or a GROUP BY that blocks pushdown, and the plans become hard to read. For hot paths we flatten the stack into one view or one query that we can reason about.

6Follow-up questions

Does a materialized view solve this?

It can, when the data may be minutes old. The materialized view stores the window results, and an index on customer_id makes the lookup fast. The cost is refresh time over the whole table and staleness between refreshes, so it suits reports better than screens that must show a just-placed order.

Would adding an index on customer_id help the original view?

No. The index exists already; the planner cannot use it because the filter is not allowed to move below the window. Indexes help only after the plan places the condition at the base table.

7Conclusion

In this answer, we saw that PostgreSQL normally inlines views and pushes filters down, so views are not slow in general. A window function, though, needs every row of its window, so a filter can move below it only when it uses the window's partition key; otherwise the window is computed over the whole table and the filter is applied at the end. EXPLAIN (ANALYZE, BUFFERS) shows exactly where the filter sits. The fixes are to partition by the filter column when that is the right meaning, to use a parameterised SQL function or restructure the view, and to flatten stacked views on hot paths.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would say that views are not slow by themselves: PostgreSQL inlines the view and normally pushes WHERE customer_id = 42 down to the base table. The window function is what changes that.

Then, if they want more

A window function needs all the rows in its window to compute each value, so filtering first would change the result, unless the filter is on the window's partition key, in which case it only removes whole partitions.

If the view partitions by region, for example, the planner has to join and rank every order and only then filter for customer 42.

I would prove it with EXPLAIN ANALYZE BUFFERS on both versions: in the view's plan the filter sits on top of a WindowAgg with millions of rows removed, and in the hand-written query it is an index condition.

I would also point out that the hand-written query is usually fast because it does not compute the same window, so it may not be equivalent. For fixes: if the rank should be per customer, partition by customer_id and pushdown becomes valid.

If not, a LANGUAGE sql function with a customer parameter puts the filter inside, or the view is restructured so the hot path does not include the window, or the expensive value is precomputed. And I would flatten views stacked on views for hot paths.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A query on a view orders_summary is slow, while the same query written by hand against...": https://scrivio-interview-library.netlify.app/databases/stored-code/dd08b782f2/