Rewrited sql to prevend deadlocks