select for update gives error on indexed column here is my code:

mysql_query("start transaction");
$q="select max(id) from test for update";
$r=mysql_query($q);
$row=mysql_fetch_array($r);
for ($k=0;$k&lt;100000;$k++)
{
$q="insert into test values ($row[0]+$k)";
$r=mysql_query($q);
}
mysql_query("commit");


if i run code with 2 browser if id column is not indexed code run correctly-  second session wait until first session commit -.

but if id column is indexed i get this error "mysql_fetch_array() expects parameter 1 to be resource, boolean given " on second browser - waiting session -.

when i use mysql_error() before mysql_fetch_array() i get this error "Deadlock found when trying to get lock; try restarting transaction". why?
SELECT FOR UPDATE tends to do row level locking in a deep way we tend to take for granted: Locking the corresponding index entries as well.

SELECT queries can perform locks on the gen_clust_index, aka the Clustered Index.

Here are three DBA Stack Exchanges questions I agressively looked over with @RedBlueThing, the person who asked these questions. @RedBlueThing found work arounds for his questions.


Reasons for occasionally slow queries?
Trouble deciphering a deadlock in an innodb status log
Will these two queries result in a deadlock if executed in sequence?


Just to keep your question in perspective, when you look over these answers (don't look too deeply, even I get dizzy looking at my own convoluted answers) it should be quickly apparent that SELECT queries can lock data at the index level.

You also have special cases of SELECT where you can lock specific rows on demand.

Look at this issue from another angle, "Are InnoDB deadlock exceptions possibly going to be thrown by SELECT?" The answer to that can be Yes under a certain condition: If just a single SQL statement is rolled back as a result of an error, some of the locks set by the statement may be preserved. This happens because InnoDB stores row locks in a format such that it cannot know afterward which lock was set by which statement.