2

I have a query which looks like this

SELECT 
  col1,
  col2 
FROM
  table1 t1 
  INNER JOIN table2 t2 
    ON t1.col = t2.col 
WHERE expensive_func () < 10 

This runs fairly quickly @ 0.110 seconds. But if I want to also show the result of expensive_func() so change the query to

SELECT 
  col1,
  col2,
  expensive_func() as col3
FROM
  table1 t1 
  INNER JOIN table2 t2 
    ON t1.col = t2.col 
WHERE expensive_func () < 10 

This works but the query time is now ~0.550

using explain on both query's returns exactly the same (confirmed by diff)

is there any way to re use expensive func ?

I assume its slower because it has to store the result of expensive func ? as its more than twice as slow (what I would expect to be a maximum)

EDIT:

Just in case version 5.5.37-0ubuntu0.12.04.1-log is what I'm using.

Edit2:

Removing expensive_func() from the WHERE doesnt seem to make a difference in the second query in terms of time, it returns more rows but in the same amount of time.

Edit3:

For some reason using the mysql CREATE FUNCTION slows it down, taking the code out of the function and putting it in the query makes it much faster.

2
  • What the expensive_func() do for? Try to create an simple UDF like return a constant then test again. Oct 16, 2014 at 8:53
  • Its a distance calculation
    – exussum
    Oct 16, 2014 at 8:54

1 Answer 1

0

expensive_func was a stored function. Replacing the stored function with the contents of the stored function makes the query run in ~0.080 seconds. a huge improvement.

I'm not sure why the stored function made everything much slower but it seems the only downside is slightly less maintainable MySQL code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.