Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql function call

If I call a function several time then will it execute every time or just execute once and the value will be used then after several time? Example:

 select my_function('filed'),my_function('filed')/field2, 
        (my_function('filed')*field1)/field3,
...... from my_table    where group by filed1;

My question is my_function('filed') will be executed once and then the result will be used in my_function('filed')/field2 and (my_function('filed')*field1)/field3 or every time my_function('filed') will be called and executed in system level ?

like image 605
Samiul Avatar asked Jan 16 '13 10:01

Samiul


2 Answers

Why not use a variable that catch the value of your function. For example:

declare var_function (datatype(size)); // just to declare proper data type for your function

set var_function = my_function('filed');

select var_function, var_function/field2, 
        (var_function*field1)/field3,

....from my_table    where group by filed1;

in that case, you'll be going to reuse the function result and no need to repeat the process of the function.

like image 189
wedev27 Avatar answered Oct 05 '22 13:10

wedev27


It is possible to have some optimization if you declare your function as DETERMINISTIC. But it really should be deterministic:

A routine is considered “deterministic” if it always produces the same result for the same input parameters, and “not deterministic” otherwise. If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly.

Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used. Prior to MySQL 5.0.44, the DETERMINISTIC characteristic is accepted, but not used by the optimizer.

like image 39
triclosan Avatar answered Oct 05 '22 11:10

triclosan