Skip to content
Advertisement

Firebird query taking too long when using IN clause with Stored Procedure

For a report I had to write a recursive Stored Procedure GET_RECIPE_STEPS_ID(recipe_id). It returns ids of steps which are of type recipe. I.E.

When I run it on it’s own It’s quick (like 0.031sec execution time). But if it is to be used with IN clause in a query it takes ages. Like the following query took almost 12 minutes.

Which is equivalent to the following query, and almost as quick as the stored procedure itself (0.038sec)

Stored Procedure

Advertisement

Answer

The problem is two-fold:

  1. IN does not have very good performance to begin with and
  2. In this situation the stored procedure gets executed for each row and not once like you would expect; I guess the Firebird optimizer doesn’t infer that this stored procedure invocation is not correlated with the query.

It will probably perform better if you transform your query to use an INNER JOIN instead of IN:

I assume that your real query might be more complex, because otherwise just select ID from GET_RECIPE_STEPS_ID(3189) would suffice.

The above query will behave slightly different than IN, for example if an ID occurs multiple times in the stored procedure output, it will also produce multiple rows now. You may need to adjust accordingly.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement