Posts

Showing posts with the label explain

SQL Query and performance tuning - DB stats and identifying slow queries

Image
  📊 Understanding Table Statistics in PostgreSQL (With Simple Examples) Efficient queries depend on knowing your data . PostgreSQL uses table statistics to build better query plans, and you can use them too, to diagnose slow queries , analyze distributions , and optimize performance . Let’s explore how to gather and use these statistics using tools like: ANALYZE pg_stat_statements auto_explain pg_stats 📦 Why Do Table Statistics Matter? PostgreSQL keeps metadata about: 🔢 Number of rows in each table 💾 Storage usage 🔄 Value frequency (e.g., most common values) 📉 Data distribution (e.g., histograms, skew) ⚖️ Cardinality (how many distinct values a column has) This info helps the query planner decide how to execute your queries efficiently. ⚙️ 1. Collecting Stats with ANALYZE Run ANALYZE to gather statistics on tables: ANALYZE your_table; You can also combine it with VACUUM to clean and analyze at the same time: VACUUM ANALYZE your...

SQL Query and performance tuning - Explain and Analyse commands

Image
  🛠️ Understanding SQL Query Performance with EXPLAIN and ANALYZE When it comes to SQL optimization, the first and most powerful step is understanding how your queries are actually executed . While SQL is declarative—you tell the database what you want—what happens under the hood is procedural and driven by a query execution plan . This blog post will walk you through how to use PostgreSQL’s EXPLAIN and ANALYZE tools to explore, diagnose, and improve query performance, including how WHERE clauses and indexes influence plans . 🔍 Meet EXPLAIN : Peek Into the Execution Plan Let’s start simple: EXPLAIN SELECT * FROM staff; Output: Seq Scan on staff ( cost = 0.00 . .24 .00 rows = 1000 width= 75 ) Seq Scan : A full table scan—every row is read. Cost : Estimated computation units. Not real time, but useful for comparing query complexity. Width : Amount of data (in bytes) returned per row. 🟢 For small tables , a Seq Scan is typically fast enough. 🔴 For la...