How do you optimize a slow-running SQL query or search routine when dealing with millions of database records?