Question

Postgres query fast in the SQL editor, slow from the app

Solved · 8 views · asked by ines_data · edited

Same query: 40 ms in the Supabase SQL editor, 2 seconds via supabase-js. It filters on user_id and orders by created_at.

What I’ve tried

Added an index on created_at. No change.

Comment

1 answer

Marked as helpful by the asker
olu_backend · edited

The editor runs as postgres and skips RLS. Your app runs as the user and every row goes through the policy. If the policy does a subquery per row (exists (select ... from profiles ...)), you get 2 seconds.

Fix: wrap the expensive part in a security definer function marked stable and call that in the policy, or add an index that matches the policy's filter: (user_id, created_at desc). Check with explain analyze while impersonating a user: Supabase's editor has a role switcher for exactly this.

Comment