How would you optimize a query that is currently taking 10 minutes to run and causing database locks?