Что вы анализируете в EXPLAIN ANALYZE и какие проблемы находили на практике, помимо добавления индексов?
Asked at
AI answer
In EXPLAIN ANALYZE (in PostgreSQL), I compare the planner’s estimates with the actual row counts and execution times for each node: large discrepancies point to cardinality estimation errors. I examine the join types and order, loops, filtered rows, buffers and reads, parallel nodes, as well as sorts and hash operations that may have spilled to disk. I keep in mind that EXPLAIN ANALYZE actually runs the query and adds overhead of its own.
Besides missing indexes, common issues include stale statistics, a poor query shape or unnecessary joins, filtering after reading a large volume of data, functions or type casts that prevent index use, lack of partition pruning, sorts spilling to disk, and selecting too many columns. I also check for N+1 queries at the application level and the impact of competing workloads. Then I change one cause at a time and compare the plan and execution time on representative data.
Also asked at GigaChat / Сбер
- app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() def heavy_text_parser(file_id: int, db: Session): # Parsing a file that takes 5 minutes parse_and_save(file_id, db) @app.post("/upload") async def upload_file( background_tasks: BackgroundTasks, db: Session = Depends(get_db) ): file_id = save_file_to_db(db) db.commit() background_tasks.add_task(heavy_text_parser, file_id, db) return {"status": "parsing started"}
- def extract_emails_from_huge_file(file_path: str) -> list[str]: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Заменяем переносы строк, чтобы текст был "сплошным" content = content.replace('\r\n', ' ').replace('\n', ' ') lines = content.split(' ') emails = [word for word in lines if '@' in word] return emails
Similar questions
- How do you find and optimize a slow SQL query? What do you look at first in EXPLAIN ANALYZE?
- Have you used EXPLAIN?
- What join algorithms are used in PostgreSQL? What is the difference between Nested Loop, Hash Join, and Merge Join, and when is each preferable?
- What are PostgreSQL indexes used for, what are their pros and cons, and what is a B-tree?
- If the problem turns out to be on the database side and a SELECT query is taking a long time, what would you do? Which columns are indexes usually created on?