# Postgres SET Clause Stops SQL Function Inlining

> A SET search_path line on a SQL function stopped Postgres from inlining it, and a fast search turned into a sequential scan.

- Author: Curtis Miller
- Published: 2026-11-12
- Categories: postgres, performance, gotchas
- Canonical URL: https://millarian.com/posts/postgres-set-clause-stops-function-inlining/

A search query started timing out. Nothing in it had changed, the table had indexes on every column it filtered by, and both indexes were being ignored. The cause was one line on a SQL function: `set search_path = ''`.

## The setup

The search filter lived in a SQL function, and the query called it in its `WHERE` clause:

```sql
create function matches(l listings, q text, filters jsonb)
returns boolean
language sql stable
set search_path = ''
as $$ select ... $$;

select * from listings l
where matches(l, q, filters);
```

## How to tell a function wasn't inlined

`EXPLAIN ANALYZE` showed this:

```text
Seq Scan on listings l
  Filter: matches(l.*, ''::text, '{...}'::jsonb)
Execution Time: 4926.214 ms
```

The function name in the `Filter` line is the giveaway. When Postgres inlines a simple SQL function, it pastes the body into the query, and the planner sees the real conditions and can use indexes. Here it only sees a function call, so it runs it on every row.

## Why

Postgres never inlines a SQL function that has a `SET` clause. The `search_path` line had been added as general hardening, since Supabase's linter recommends it. With a few thousand rows nobody noticed. Once the table grew, the query went past the timeout.

## The fix

Remove the `SET` line and put the schema name on everything inside the function (`public.listings`, `pg_catalog.websearch_to_tsquery`) instead:

```sql
create or replace function matches(l listings, q text, filters jsonb)
returns boolean
language sql stable
as $$ select ... $$;
```

The same query then used the index:

```text
Index Scan using listings_status_idx on listings l
Execution Time: 7.530 ms
```

Pinning `search_path` matters most for `SECURITY DEFINER` functions, which run with the owner's rights. A helper that runs with the caller's rights and is meant to be inlined is better off with the schema written into each name.

## Test for it

The query returned the right rows the whole time, so no ordinary test would catch this. A quick check that the function stays inlinable:

```sql
do $$
begin
  assert (select proconfig is null from pg_proc where proname = 'matches'),
    'matches() must not have a SET clause, or it will not be inlined';
end $$;
```

## Takeaway

If a function shows up by name in the `Filter` line of your `EXPLAIN`, it wasn't inlined. Any `SET` clause on a SQL function will do that.
