Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql query takes too long when sleep() is used in where clause

Tags:

mysql

I have read about sleep(n) function in MySql, which is supposed to sleep for n seconds and return 0 if uninterrupted or 1 if interrupted.

This works well if I use sleep() in select clause. For example, following query returns result after 10 seconds.

SELECT id, sleep(10) FROM versions WHERE id = 123

However, the query takes too long if I use sleep(10) in the where clause.

SELECT id FROM versions WHERE id = 123 OR sleep(10)=1

Any idea about why is it behaving like this?

like image 467
Sanket Meghani Avatar asked Dec 18 '14 06:12

Sanket Meghani


2 Answers

In the first query it takes just 10 second sleep time while in the second one every id is being checked if it is 123 or not and if not it sleeps for 10 seconds.

In where clause using sleep is like checking it against each row in the database except the one where it matches the value 123 in your case.

like image 119
Danyal Sandeelo Avatar answered Oct 03 '22 00:10

Danyal Sandeelo


It will sleep at every row for 10 seconds when your first condition is false.

like image 37
Piyush Aghera Avatar answered Oct 02 '22 23:10

Piyush Aghera