SlideShare a Scribd company logo
1 of 23
Tuning Slow Running
SQLs in PostgreSQL
A quick recap!
Earlier we saw:
- How you can find session and details of slow
running query
- How you can cancel a slow running query
- How you can log a slow running query
What are we going to do today
- See the explain plan and analyze the slow
running query
- Some basic tips for tuning the query
- Headsup for the next session!
Explain Plan
- Syntax: explain [analyze] <query>
- Importance-
- Gives you important information about
query performance and plan
- See steps involved in execution
- Exposes the statistics assumed by your
query for planning the execution
How to Read Explain Plan
Explain Analyze
Tips for Tuning
- These are all incremental step  I prefer implementing in same order
- Tune the query first and optimize it to remove costly clauses
- Create required indexes if they are missing
- Feed the Optimizer with correct info- Tune the optimizer parameters if
required
- e.g seq_page_cost, random_page_cost, effective_cache_size etc
- Provision more resources for hungry (costly) queries- Set some
session/transaction/user level parameters for certain costly queries
- e.g. work_mem
- Consider other changes
- e.g application architecture, application logic, hardware upgrade
Tips for Tuning the Query
Tips #1- Avoid select *
- Select only what you need
- Everyone wants to use “select *” but no one needs it
Example
Tip #2- Filter the rows
- Neither you need all the rows in one go nor
your application can handle them all
- Avoid filtering in application
- Fetch only what you need- use WHERE clause
- Limit huge recordsets- use LIMIT clause
- Iterate using OFFSET clause
Example
Tip #3- Avoid Sorting
- Avoid Sorting if you don’t actually need it
- ORDER BY Clause uses sorting memory
(work_mem)
- If not enough memory then it spills over to disk
Example
Tip #4- UPDATE from a Source Table
- In lot of cases one has to update data in one table based
on data from another table or with data from another
table
- Example
update update_target t1
set columne_to_update=t2.source_for_update ,
t1.column_2_for_update=t2.column_2_source
from update_source t2 where t1.column_id=t2.column_id;
update update_target t1
set columne_to_update =(select source_for_update from update_source t2
where t1.column_id=t2.column_id),
column_2_for_update=(select column_2_source from update_source t2
where t1.column_id=t2.column_id)
where exists (select 1 from update_source t3 where
t3.column_id=t1.column_id);
Example
Example – UPDATE FROM
update update_target t1
set columne_to_update=t2.source_for_update ,
t1.column_2_for_update=t2.column_2_source
from update_source t2 where
t1.column_id=t2.column_id;
Tip #5- Use High School Mathematics
- Shift the Calculation from RHS to LHS
- Instead of using expressions on Columns use the inverse
expression with literals
- Examples
- select * from emp where salary+200=1200;
select * from emp where salary=1200-200;
- select * from emp where date_trunc(‘d’,hiredatetime)=‘2014-01-03’::date
select * from emp where hiredatetime>=‘2014-01-03 00:00:00’::timezone and
hiredatetime<‘2014-01-03 00:00:00’::timezone +’1 day’::interval
When Basic Tuning
Does not Help
Tip #1- Look for Usual Suspects
Try to Look for Costly Clauses in Explain Plan
Tip #2- Indexing can Help
Create Indexes and test them
Some facts to remember while Indexing
- PostgreSQL can do “index-only-scans”
- PostgreSQL can do intersection between result of two indexes
- You can use filter indexes
- Pattern searches may use indexes
- e.g. select empid from emp where empname like ‘SA%’
- Pattern searches may not use indexes
- e.g. select empid from emp where empname like ‘%ER’
- PostgreSQL has expression based indexes
- Indexes can not replace a flawed schema design and poorly
written query
Heads-up for the next Hangout!
- We will be discussing some basic configuration
tuning techniques

More Related Content

What's hot

Oracle 12c New Features_RMAN_slides
Oracle 12c New Features_RMAN_slidesOracle 12c New Features_RMAN_slides
Oracle 12c New Features_RMAN_slides
Saiful
 
[Altibase] 10 replication part3 (system design)
[Altibase] 10 replication part3 (system design)[Altibase] 10 replication part3 (system design)
[Altibase] 10 replication part3 (system design)
altistory
 
Whitepaper: Exadata Consolidation Success Story
Whitepaper: Exadata Consolidation Success StoryWhitepaper: Exadata Consolidation Success Story
Whitepaper: Exadata Consolidation Success Story
Kristofferson A
 

What's hot (20)

The Magic of Tuning in PostgreSQL
The Magic of Tuning in PostgreSQLThe Magic of Tuning in PostgreSQL
The Magic of Tuning in PostgreSQL
 
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
 
SQL Server vs Postgres
SQL Server vs PostgresSQL Server vs Postgres
SQL Server vs Postgres
 
PostGreSQL Performance Tuning
PostGreSQL Performance TuningPostGreSQL Performance Tuning
PostGreSQL Performance Tuning
 
Linux internals for Database administrators at Linux Piter 2016
Linux internals for Database administrators at Linux Piter 2016Linux internals for Database administrators at Linux Piter 2016
Linux internals for Database administrators at Linux Piter 2016
 
PostgreSQL replication
PostgreSQL replicationPostgreSQL replication
PostgreSQL replication
 
Percona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ MumbaiPercona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ Mumbai
 
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesPostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
 
Oracle 12c New Features_RMAN_slides
Oracle 12c New Features_RMAN_slidesOracle 12c New Features_RMAN_slides
Oracle 12c New Features_RMAN_slides
 
[Altibase] 13 backup and recovery
[Altibase] 13 backup and recovery[Altibase] 13 backup and recovery
[Altibase] 13 backup and recovery
 
[Altibase] 12 replication part5 (optimization and monitoring)
[Altibase] 12 replication part5 (optimization and monitoring)[Altibase] 12 replication part5 (optimization and monitoring)
[Altibase] 12 replication part5 (optimization and monitoring)
 
DB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
DB2 10 & 11 for z/OS System Performance Monitoring and OptimisationDB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
DB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
 
Introduction to PgBench
Introduction to PgBenchIntroduction to PgBench
Introduction to PgBench
 
11 cool features in Defrag.nsf+ 11
11 cool features in Defrag.nsf+ 1111 cool features in Defrag.nsf+ 11
11 cool features in Defrag.nsf+ 11
 
PostgreSQL Scaling And Failover
PostgreSQL Scaling And FailoverPostgreSQL Scaling And Failover
PostgreSQL Scaling And Failover
 
Online MySQL Backups with Percona XtraBackup
Online MySQL Backups with Percona XtraBackupOnline MySQL Backups with Percona XtraBackup
Online MySQL Backups with Percona XtraBackup
 
Performance tuning in sql server
Performance tuning in sql serverPerformance tuning in sql server
Performance tuning in sql server
 
[Altibase] 10 replication part3 (system design)
[Altibase] 10 replication part3 (system design)[Altibase] 10 replication part3 (system design)
[Altibase] 10 replication part3 (system design)
 
Whitepaper: Exadata Consolidation Success Story
Whitepaper: Exadata Consolidation Success StoryWhitepaper: Exadata Consolidation Success Story
Whitepaper: Exadata Consolidation Success Story
 
Dmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL ServerDmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL Server
 

Viewers also liked

Building Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDBBuilding Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDB
Ashnikbiz
 

Viewers also liked (11)

FOSSASIA 2016 - 7 Tips to design web centric high-performance applications
FOSSASIA 2016 - 7 Tips to design web centric high-performance applicationsFOSSASIA 2016 - 7 Tips to design web centric high-performance applications
FOSSASIA 2016 - 7 Tips to design web centric high-performance applications
 
NGINX Plus PLATFORM For Flawless Application Delivery
NGINX Plus PLATFORM For Flawless Application DeliveryNGINX Plus PLATFORM For Flawless Application Delivery
NGINX Plus PLATFORM For Flawless Application Delivery
 
Transform your DBMS to drive engagement innovation with Big Data
Transform your DBMS to drive engagement innovation with Big DataTransform your DBMS to drive engagement innovation with Big Data
Transform your DBMS to drive engagement innovation with Big Data
 
FOSSASIA 2015 - 10 Features your developers are missing when stuck with Propr...
FOSSASIA 2015 - 10 Features your developers are missing when stuck with Propr...FOSSASIA 2015 - 10 Features your developers are missing when stuck with Propr...
FOSSASIA 2015 - 10 Features your developers are missing when stuck with Propr...
 
Countdown to PostgreSQL v9.5 - Foriegn Tables can be part of Inheritance Tree
Countdown to PostgreSQL v9.5 - Foriegn Tables can be part of Inheritance Tree Countdown to PostgreSQL v9.5 - Foriegn Tables can be part of Inheritance Tree
Countdown to PostgreSQL v9.5 - Foriegn Tables can be part of Inheritance Tree
 
Building Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDBBuilding Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDB
 
2016 may-countdown-to-postgres-v96-parallel-query
2016 may-countdown-to-postgres-v96-parallel-query2016 may-countdown-to-postgres-v96-parallel-query
2016 may-countdown-to-postgres-v96-parallel-query
 
Building Data Integration and Transformations using Pentaho
Building Data Integration and Transformations using PentahoBuilding Data Integration and Transformations using Pentaho
Building Data Integration and Transformations using Pentaho
 
Architecture for building scalable and highly available Postgres Cluster
Architecture for building scalable and highly available Postgres ClusterArchitecture for building scalable and highly available Postgres Cluster
Architecture for building scalable and highly available Postgres Cluster
 
PgDay Asia 2016 - Security Best Practices for your Postgres Deployment
PgDay Asia 2016 - Security Best Practices for your Postgres DeploymentPgDay Asia 2016 - Security Best Practices for your Postgres Deployment
PgDay Asia 2016 - Security Best Practices for your Postgres Deployment
 
Big Data Business Transformation - Big Picture and Blueprints
Big Data Business Transformation - Big Picture and BlueprintsBig Data Business Transformation - Big Picture and Blueprints
Big Data Business Transformation - Big Picture and Blueprints
 

Similar to Tuning Slow Running SQLs in PostgreSQL

Advance Sql Server Store procedure Presentation
Advance Sql Server Store procedure PresentationAdvance Sql Server Store procedure Presentation
Advance Sql Server Store procedure Presentation
Amin Uddin
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
avniS
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
Tommy Falgout
 

Similar to Tuning Slow Running SQLs in PostgreSQL (20)

Advance Sql Server Store procedure Presentation
Advance Sql Server Store procedure PresentationAdvance Sql Server Store procedure Presentation
Advance Sql Server Store procedure Presentation
 
Teradata Tutorial for Beginners
Teradata Tutorial for BeginnersTeradata Tutorial for Beginners
Teradata Tutorial for Beginners
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cPresentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12c
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
Teradata sql-tuning-top-10
Teradata sql-tuning-top-10Teradata sql-tuning-top-10
Teradata sql-tuning-top-10
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
 
Processes in Query Optimization in (ABMS) Advanced Database Management Systems
Processes in Query Optimization in (ABMS) Advanced Database Management Systems Processes in Query Optimization in (ABMS) Advanced Database Management Systems
Processes in Query Optimization in (ABMS) Advanced Database Management Systems
 
SQL Server Performance Tuning with DMVs
SQL Server Performance Tuning with DMVsSQL Server Performance Tuning with DMVs
SQL Server Performance Tuning with DMVs
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
How to Cost-Optimize Cloud Data Pipelines_.pptx
How to Cost-Optimize Cloud Data Pipelines_.pptxHow to Cost-Optimize Cloud Data Pipelines_.pptx
How to Cost-Optimize Cloud Data Pipelines_.pptx
 
Oracle Sql Tuning
Oracle Sql TuningOracle Sql Tuning
Oracle Sql Tuning
 
U nit i data structure-converted
U nit   i data structure-convertedU nit   i data structure-converted
U nit i data structure-converted
 
PostgreSQL Table Partitioning / Sharding
PostgreSQL Table Partitioning / ShardingPostgreSQL Table Partitioning / Sharding
PostgreSQL Table Partitioning / Sharding
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Chapter16
Chapter16Chapter16
Chapter16
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
 
Data base testing
Data base testingData base testing
Data base testing
 

More from Ashnikbiz

More from Ashnikbiz (20)

CloudOps_tool.pptx
CloudOps_tool.pptxCloudOps_tool.pptx
CloudOps_tool.pptx
 
Webinar_CloudOps final.pptx
Webinar_CloudOps final.pptxWebinar_CloudOps final.pptx
Webinar_CloudOps final.pptx
 
Autoscaling in Kubernetes (K8s)
Autoscaling in Kubernetes (K8s)Autoscaling in Kubernetes (K8s)
Autoscaling in Kubernetes (K8s)
 
Why and how to use Kubernetes for scaling of your multi-tier (n-tier) appli...
Why and how to use Kubernetes  for scaling of your  multi-tier (n-tier) appli...Why and how to use Kubernetes  for scaling of your  multi-tier (n-tier) appli...
Why and how to use Kubernetes for scaling of your multi-tier (n-tier) appli...
 
Zero trust in a multi tenant environment
Zero trust in a multi tenant environment  Zero trust in a multi tenant environment
Zero trust in a multi tenant environment
 
Deploy and automate ‘Secrets Management’ for a multi-cloud environment
Deploy and automate ‘Secrets Management’ for a multi-cloud environmentDeploy and automate ‘Secrets Management’ for a multi-cloud environment
Deploy and automate ‘Secrets Management’ for a multi-cloud environment
 
Deploy, move and manage Postgres across cloud platforms
Deploy, move and manage Postgres across cloud platformsDeploy, move and manage Postgres across cloud platforms
Deploy, move and manage Postgres across cloud platforms
 
Deploy, move and manage Postgres across cloud platforms
Deploy, move and manage Postgres across cloud platformsDeploy, move and manage Postgres across cloud platforms
Deploy, move and manage Postgres across cloud platforms
 
The Best Approach For Multi-cloud Infrastructure Provisioning-2
The Best Approach For Multi-cloud Infrastructure Provisioning-2The Best Approach For Multi-cloud Infrastructure Provisioning-2
The Best Approach For Multi-cloud Infrastructure Provisioning-2
 
The Best Approach For Multi-cloud Infrastructure Provisioning
The Best Approach For Multi-cloud Infrastructure ProvisioningThe Best Approach For Multi-cloud Infrastructure Provisioning
The Best Approach For Multi-cloud Infrastructure Provisioning
 
Which PostgreSQL is right for your multi cloud strategy? P2
Which PostgreSQL is right for your multi cloud strategy? P2Which PostgreSQL is right for your multi cloud strategy? P2
Which PostgreSQL is right for your multi cloud strategy? P2
 
Which PostgreSQL is right for your multi cloud strategy? P1
Which PostgreSQL is right for your multi cloud strategy? P1Which PostgreSQL is right for your multi cloud strategy? P1
Which PostgreSQL is right for your multi cloud strategy? P1
 
Reduce the complexities of managing Kubernetes clusters anywhere 2
Reduce the complexities of managing Kubernetes clusters anywhere 2Reduce the complexities of managing Kubernetes clusters anywhere 2
Reduce the complexities of managing Kubernetes clusters anywhere 2
 
Reduce the complexities of managing Kubernetes clusters anywhere
Reduce the complexities of managing Kubernetes clusters anywhereReduce the complexities of managing Kubernetes clusters anywhere
Reduce the complexities of managing Kubernetes clusters anywhere
 
Enhance your multi-cloud application performance using Redis Enterprise P2
Enhance your multi-cloud application performance using Redis Enterprise P2Enhance your multi-cloud application performance using Redis Enterprise P2
Enhance your multi-cloud application performance using Redis Enterprise P2
 
Enhance your multi-cloud application performance using Redis Enterprise P1
Enhance your multi-cloud application performance using Redis Enterprise P1Enhance your multi-cloud application performance using Redis Enterprise P1
Enhance your multi-cloud application performance using Redis Enterprise P1
 
Gain multi-cloud versatility with software load balancing designed for cloud-...
Gain multi-cloud versatility with software load balancing designed for cloud-...Gain multi-cloud versatility with software load balancing designed for cloud-...
Gain multi-cloud versatility with software load balancing designed for cloud-...
 
Gain multi-cloud versatility with software load balancing designed for cloud-...
Gain multi-cloud versatility with software load balancing designed for cloud-...Gain multi-cloud versatility with software load balancing designed for cloud-...
Gain multi-cloud versatility with software load balancing designed for cloud-...
 
Enterprise-class security with PostgreSQL - 1
Enterprise-class security with PostgreSQL - 1Enterprise-class security with PostgreSQL - 1
Enterprise-class security with PostgreSQL - 1
 
Enterprise-class security with PostgreSQL - 2
Enterprise-class security with PostgreSQL - 2Enterprise-class security with PostgreSQL - 2
Enterprise-class security with PostgreSQL - 2
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Tuning Slow Running SQLs in PostgreSQL

  • 1. Tuning Slow Running SQLs in PostgreSQL
  • 2. A quick recap! Earlier we saw: - How you can find session and details of slow running query - How you can cancel a slow running query - How you can log a slow running query
  • 3. What are we going to do today - See the explain plan and analyze the slow running query - Some basic tips for tuning the query - Headsup for the next session!
  • 4. Explain Plan - Syntax: explain [analyze] <query> - Importance- - Gives you important information about query performance and plan - See steps involved in execution - Exposes the statistics assumed by your query for planning the execution
  • 5. How to Read Explain Plan
  • 7. Tips for Tuning - These are all incremental step  I prefer implementing in same order - Tune the query first and optimize it to remove costly clauses - Create required indexes if they are missing - Feed the Optimizer with correct info- Tune the optimizer parameters if required - e.g seq_page_cost, random_page_cost, effective_cache_size etc - Provision more resources for hungry (costly) queries- Set some session/transaction/user level parameters for certain costly queries - e.g. work_mem - Consider other changes - e.g application architecture, application logic, hardware upgrade
  • 8. Tips for Tuning the Query
  • 9. Tips #1- Avoid select * - Select only what you need - Everyone wants to use “select *” but no one needs it
  • 11. Tip #2- Filter the rows - Neither you need all the rows in one go nor your application can handle them all - Avoid filtering in application - Fetch only what you need- use WHERE clause - Limit huge recordsets- use LIMIT clause - Iterate using OFFSET clause
  • 13. Tip #3- Avoid Sorting - Avoid Sorting if you don’t actually need it - ORDER BY Clause uses sorting memory (work_mem) - If not enough memory then it spills over to disk
  • 15. Tip #4- UPDATE from a Source Table - In lot of cases one has to update data in one table based on data from another table or with data from another table - Example update update_target t1 set columne_to_update=t2.source_for_update , t1.column_2_for_update=t2.column_2_source from update_source t2 where t1.column_id=t2.column_id; update update_target t1 set columne_to_update =(select source_for_update from update_source t2 where t1.column_id=t2.column_id), column_2_for_update=(select column_2_source from update_source t2 where t1.column_id=t2.column_id) where exists (select 1 from update_source t3 where t3.column_id=t1.column_id);
  • 17. Example – UPDATE FROM update update_target t1 set columne_to_update=t2.source_for_update , t1.column_2_for_update=t2.column_2_source from update_source t2 where t1.column_id=t2.column_id;
  • 18. Tip #5- Use High School Mathematics - Shift the Calculation from RHS to LHS - Instead of using expressions on Columns use the inverse expression with literals - Examples - select * from emp where salary+200=1200; select * from emp where salary=1200-200; - select * from emp where date_trunc(‘d’,hiredatetime)=‘2014-01-03’::date select * from emp where hiredatetime>=‘2014-01-03 00:00:00’::timezone and hiredatetime<‘2014-01-03 00:00:00’::timezone +’1 day’::interval
  • 20. Tip #1- Look for Usual Suspects Try to Look for Costly Clauses in Explain Plan
  • 21. Tip #2- Indexing can Help Create Indexes and test them
  • 22. Some facts to remember while Indexing - PostgreSQL can do “index-only-scans” - PostgreSQL can do intersection between result of two indexes - You can use filter indexes - Pattern searches may use indexes - e.g. select empid from emp where empname like ‘SA%’ - Pattern searches may not use indexes - e.g. select empid from emp where empname like ‘%ER’ - PostgreSQL has expression based indexes - Indexes can not replace a flawed schema design and poorly written query
  • 23. Heads-up for the next Hangout! - We will be discussing some basic configuration tuning techniques