How do you identify and optimize slow database queries?
Answer
Clear, interview-ready explanation
Start by measuring real queries and their execution time. Laravel can listen for query events or monitor cumulative query time, while database logs and application monitoring help reveal slow endpoints and repeated queries. Use the database’s EXPLAIN or query plan tools to understand how the engine executes a slow statement.
Typical fixes include indexing columns used for filtering, joins, and sorting; selecting only needed columns; avoiding unbounded result sets; paginating or chunking large work; and eager-loading Eloquent relationships to eliminate N+1 queries. Optimize based on evidence, then re-measure, because an index or rewrite that helps one workload can harm another.