Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deterministic function in mysql

I got confused with a seemingly simple concept. Mysql defines deterministic function as a function that

always produces the same result for the same input parameters

So in my understanding, functions like

CREATE FUNCTION foo (val INT) READS SQL DATA BEGIN    DECLARE retval INT;    SET retval = (SELECT COUNT(*) FROM table_1 WHERE field_1 = val);    RETURN retval; END; 

are not deterministic (there is no guarantee that delete/update/insert does not happen between 2 calls to the function). At the same time, I saw many functions which do pretty much the same, i.e. return value based on result of queries, and declared as DETERMINISTIC. It looks like I'm missing something very basic.

Could anyone clarify this issue?

Thanks.

Update Thanks for those who answered(+1); so far it looks like there is a widespread misuse of DETERMINISTIC keyword. It is still hard to believe for me that so many people do it, so I'll wait a bit for other answers.

like image 535
a1ex07 Avatar asked Oct 30 '11 17:10

a1ex07


People also ask

What is deterministic function?

A deterministic function always returns the same results if given the same input values. A nondeterministic function may return different results every time it is called, even when the same input values are provided.

Why deterministic is used in function?

Deterministic functions always return the same result any time they're called with a specific set of input values and given the same state of the database.

What is non deterministic function in SQL?

An SQL statement is non-deterministic in a replication set if it does not return the same result when executed on all replication nodes in the set. If an SQL statement contains a non-deterministic expression, by-value replication of the expression is performed.


1 Answers

From the MySQL 5.0 Reference:

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.

So there you have it, you can tag a stored routine as DETERMINISTIC even if it is not, but it might lead to unexpected results or performance problems.

like image 112
Xint0 Avatar answered Sep 20 '22 10:09

Xint0