Junior — Middle
How to determine that your SQL query is optimized and adheres to the principles of cleanliness and efficiency?
sobes.tech AI
Answer from AI
The optimality and purity of an SQL query can be determined by several criteria:
- Use of indexes. The query should efficiently utilize indexes to speed up search.
- Minimization of the amount of data returned. Select only necessary columns, avoid SELECT *.
- Absence of redundant joins and subqueries. The query should be as simple and understandable as possible.
- Check the execution plan (EXPLAIN). Analyzing the plan shows how the DBMS executes the query and helps identify bottlenecks.
- Absence of condition and operation duplication. The code should be clean and easy to read.
Example of checking the execution plan in MySQL:
EXPLAIN SELECT id, name FROM users WHERE status = 'active';
If the plan shows index usage on the status field and no full table scan, the query is considered optimal.