SQL Tuning Proven Methodologies

Similar documents
Oracle Database 11g: SQL Tuning Workshop

1Z0-117 Oracle Database 11g Release 2: SQL Tuning. Oracle

Top 25+ DB2 SQL Tuning Tips for Developers. Presented by Tony Andrews, Themis Inc.

Oracle EXAM - 1Z Oracle Database 11g Release 2: SQL Tuning. Buy Full Product.

Advanced Oracle SQL Tuning

Oracle Database 11g: SQL Tuning Workshop Release 2

DB2 Developers Guide to Optimum SQL Performance

An Oracle White Paper May The Oracle Optimizer Explain the Explain Plan

The Sins of SQL Programming that send the DB to Upgrade Purgatory Abel Macias. 1 Copyright 2011, Oracle and/or its affiliates. All rights reserved.

Fallacies of the Cost Based Optimizer

Best Practices for DB2 on z/os Performance

Partitioning under the hood in MySQL 5.5

D B M G Data Base and Data Mining Group of Politecnico di Torino

SQL Query Evaluation. Winter Lecture 23

D B M G Data Base and Data Mining Group of Politecnico di Torino

Oracle 10g PL/SQL Training

Using TimesTen between your Application and Oracle. between your Application and Oracle. DOAG Conference 2011

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL Performance Hero and OMG Method vs the Anti-patterns. Jeff Jacobs Jeffrey Jacobs & Associates jmjacobs@jeffreyjacobs.com

Oracle Database: SQL and PL/SQL Fundamentals

University of Aarhus. Databases IBM Corporation

Oracle Database: SQL and PL/SQL Fundamentals

Execution Plans: The Secret to Query Tuning Success. MagicPASS January 2015

Execution plans and tools

DBMS / Business Intelligence, SQL Server

Oracle Database 11 g Performance Tuning. Recipes. Sam R. Alapati Darl Kuhn Bill Padfield. Apress*

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

A basic create statement for a simple student table would look like the following.

Top 25+ DB2 SQL. Developers

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Iggy Fernandez, Database Specialists DEFINING EFFICIENCY TUNING BY EXAMPLE CREATING AND POPULATING THE TABLES

SQL Query Performance Tuning: Tips and Best Practices

Experiment 5.1 How to measure performance of database applications?

COMPUTER MEASUREMENT GROUP INDIA. Large Centralized Tax Processing Solution Benchmark and Performance Analysis

Who am I? Copyright 2014, Oracle and/or its affiliates. All rights reserved. 3

Oracle Database: SQL and PL/SQL Fundamentals NEW

Tune That SQL for Supercharged DB2 Performance! Craig S. Mullins, Corporate Technologist, NEON Enterprise Software, Inc.

Big Data, Fast Processing Speeds Kevin McGowan SAS Solutions on Demand, Cary NC

Oracle Database 12c: Introduction to SQL Ed 1.1

SQL Performance and Tuning. DB2 Relational Database

news from Tom Bacon about Monday's lecture

Inside the PostgreSQL Query Optimizer

Subqueries Chapter 6

Performance rule violations usually result in increased CPU or I/O, time to fix the mistake, and ultimately, a cost to the business unit.

Oracle SQL. Course Summary. Duration. Objectives

Chapter 13: Query Processing. Basic Steps in Query Processing

Oracle DBA Course Contents

Optimizing the Performance of the Oracle BI Applications using Oracle Datawarehousing Features and Oracle DAC

SQL Server Query Tuning

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

Displaying Data from Multiple Tables. Chapter 4

CIS 631 Database Management Systems Sample Final Exam

Oracle Database 12c Enables Quad Graphics to Quickly Migrate from Sybase to Oracle Exadata

SQL Performance for a Big Data 22 Billion row data warehouse

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Physical Design. Phases of database design. Physical design: Inputs.

Objectives. Oracle SQL and SQL*PLus. Database Objects. What is a Sequence?

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Useful Business Analytics SQL operators and more Ajaykumar Gupte IBM

SQL Server Query Tuning

Displaying Data from Multiple Tables

SQL SELECT Query: Intermediate

Maximizing Materialized Views

Aggregating Data Using Group Functions

An Oracle White Paper May Guide for Developing High-Performance Database Applications

Programming with SQL

MOC 20461C: Querying Microsoft SQL Server. Course Overview

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia

Oracle Database 11g: Performance Tuning DBA Release 2

University of Massachusetts Amherst Department of Computer Science Prof. Yanlei Diao

Efficient Data Access and Data Integration Using Information Objects Mica J. Block

SQL the natural language for analysis ORACLE WHITE PAPER JUNE 2015

Introduction to the Oracle DBMS

VARRAY AND NESTED TABLE

MS SQL Performance (Tuning) Best Practices:

Improving SQL efficiency using CASE

Instant SQL Programming

1. This lesson introduces the Performance Tuning course objectives and agenda

Keep It Simple - Common, Overlooked Performance Tuning Tips. Paul Jackson Hotsos

FHE DEFINITIVE GUIDE. ^phihri^^lv JEFFREY GARBUS. Joe Celko. Alvin Chang. PLAMEN ratchev JONES & BARTLETT LEARN IN G. y ti rvrrtuttnrr i t i r

Intro to Embedded SQL Programming for ILE RPG Developers

Netezza SQL Class Outline

Oracle PL/SQL Best Practices

Query tuning by eliminating throwaway

Performance Tuning for the Teradata Database

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Oracle Database In-Memory The Next Big Thing

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

Mini User's Guide for SQL*Plus T. J. Teorey

Object-Relational Query Processing

3.GETTING STARTED WITH ORACLE8i

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

PERFORMANCE TIPS FOR BATCH JOBS

Toad for Oracle 8.6 SQL Tuning

Oracle InMemory Database

SAP Business Objects Business Intelligence platform Document Version: 4.1 Support Package Data Federation Administration Tool Guide

Introduction to Microsoft Jet SQL

Database Performance and Tuning

Transcription:

SQL Tuning Proven Methodologies V.Hariharaputhran

V.Hariharaputhran o Twelve years in Oracle Development / DBA / Big Data / Cloud Technologies o All India Oracle Users Group (AIOUG) Evangelist o Passion to learn and share o Blog: o Twitter: @puthranv

Our 60 minutes Agenda Objective Lifecycle of a SQL Cursors Why and What Get the right Execution Plan Case Studies Push predicate vs. No-Push Join Elimination Correlated sub-query Why my Index is not Used Take Away

Until Yesterday it was running Fine What happened now? DBA Developer

Typical Day Options we see 1. Why not Cache Table 2. There is Memory Problem / No partition hence you are bound to run slow 3. I learnt new features and desperate to implement them 4. Rewrite the SQL / Add Index / 5. SQL running slow Found the init parameter causing it, Let me change it. 6. I see no Histograms / must be a stats problem 7. I came across a tool, you just have to provide the table name it would generate the SQL for us.

Out of the BOX Recreate the Table Avoid writing the SQL / Change the Design Archive Strategy

SQL Lifecycle Parse Bind Execute Fetch

Some more Parse PARSE So what is before the syntax check Adding VPD Predicates to SQL

VPD Watch out for the Predicate Info

Why add VPD first

More about Parsing Syntax Check - Keywords Semantic Check - Objects Accessible View Merging/Subquery Unnesting Views to Base tables / Inline Views Query Transformation Transitivity Optimization Soft Parse Hard Parse Query Execution Plan / Load into Library Cache

Cursor SELECT * FROM EMP ENV STATS SQL TEXT BIND VARIABLES PARENT CURSOR CHILD CURSOR

Cursors

What is this Child Number = 0?

Identify the reason for Child Cursor

declare v_ename emp.ename%type; begin For x in 1..10000 loop select /* NORMAL */ ename into v_ename from Binding in PLSQL emp where empno = x ; end loop; end; / declare v_ename emp.ename%type; v_sql varchar2(200); begin For x in 1..10000 loop execute immediate 'select /* bind */ ename from emp where empno = :v_empno' into v_ename using x ; end loop; end; / In PL/SQL its free, Oracle does the binding for us

Explain Plan

Is X not a Number?

Estimate Vs Actual

Autotrace

Autotrace 20000/3=6666.6

Explain Plan Not the Real Plan, Just an estimate Treat all Bind Variable as Varchar2 Datatype Does not use Bind Variable Peeking

DBMS_XPLAN DBMS_XPLAN.display - Estimated DBMS_XPLAN.display_cursor Real from Memory DBMS_XPLAN.display_awr - Historic

CASE STUDY -1

Estimated Plan from DBMS_XPLAN SQL> select * from tblchk tbl1 where exists 2 (select 1 from tblchk tbl2 where tbl1.id=tbl2.id and tbl2.id_val='aioug'); no rows selected SQL> select * from table(dbms_xplan.display_cursor()); -------------------------------------------------------------------------------- Id Operation Name Rows Bytes Cost (%CPU) Time -------------------------------------------------------------------------------- ----------------------------- 0 SELECT STATEMENT 1 (100) * 1 FILTER * 2 HASH JOIN RIGHT SEMI 190K 2226K 207 (2) 00:00:01 * 3 TABLE ACCESS FULL TBLCHK 36663 214K 103 (1) 00:00:01 4 TABLE ACCESS FULL TBLCHK 220K 1289K 103 (1) 00:00:01 -------------------------------------------------------------------------------- Predicate Information (identified by operation id): --------------------------------------------------- 1 - filter(null IS NOT NULL) 2 - access("tbl1"."id"="tbl2"."id") 3 - filter("tbl2"."id_val"='aioug')

God 10046+TKprof call count cpu elapsed disk query current rows ------- ------- -------- ---------- ---------- ---------- ---------- ---------- Parse 1 0.01 0.01 0 0 0 0 Execute 1 0.00 0.00 0 0 0 0 Fetch 1 0.02 0.12 483 487 0 0 ------- ------ ------- -------- ---------- ---------- ---------- ---------- total 3 0.03 0.14 483 487 0 0 Misses in library cache during parse: 1 Optimizer mode: ALL_ROWS Parsing user id: 143 Number of plan statistics captured: 1 Rows (1st) Rows (avg) Rows (max) Row Source Operation ---------- ---------- ---------- --------------------------------------------------- 0 0 0 HASH JOIN RIGHT SEMI (cr=487 pr=483 pw=0 time=128029 us cost=207 size=2280096 card=190008) 0 0 0 TABLE ACCESS FULL TBLCHK (cr=487 pr=483 pw=0 time=127573 us cost=103 size=219978 card=36663) 0 0 0 TABLE ACCESS FULL TBLCHK (cr=0 pr=0 pw=0 time=0 us cost=103 size=1320000 card=220000) Elapsed times include waiting on following events: Event waited on Times Max. Wait Total Waited ---------------------------------------- Waited ---------- ------------ SQL*Net message to client 1 0.00 0.00 Disk file operations I/O 1 0.00 0.00 db file sequential read 3 0.01 0.03 db file scattered read 22 0.02 0.08 SQL*Net message from client 1 25.96 25.96

Add the Check Constraint SQL> select distinct id_val from tblchk; ID_VAL ----------- A B C alter table tblchk add CONSTRAINT check_idval CHECK (id_val in ('A','B','C'));

After Constraint 10046+TKprof call count cpu elapsed disk query current rows ------- ------ -------- ---------- -------- ---------- ---------- ---------- Parse 1 0.00 0.00 0 0 0 0 Execute 1 0.00 0.00 0 0 0 0 Fetch 1 0.00 0.00 0 0 0 0 ------- ------ -------- ---------- --------- -------- --------- ---------- total 3 0.00 0.00 0 0 0 0 Misses in library cache during parse: 1 Optimizer mode: ALL_ROWS Parsing user id: 143 Number of plan statistics captured: 1 Rows (1st) Rows (avg) Rows (max) Row Source Operation ---------- ---------- ---------- --------------------------------------------------- 0 0 0 FILTER (cr=0 pr=0 pw=0 time=7 us) 0 0 0 HASH JOIN RIGHT SEMI (cr=0 pr=0 pw=0 time=0 us cost=276 size=3094080 card=257840) 0 0 0 TABLE ACCESS FULL TBLCHK (cr=0 pr=0 pw=0 time=0 us cost=138 size=279972 card=46662) 0 0 0 TABLE ACCESS FULL TBLCHK (cr=0 pr=0 pw=0 time=0 us cost=137 size=1680000 card=280000) Elapsed times include waiting on following events: Event waited on Times Max. Wait Total Waited ---------------------------------------- Waited ---------- ------------ SQL*Net message to client 1 0.00 0.00 SQL*Net message from client 1 19.78 19.78

DBMS_XPLAN ALLSTATS LAST Rows = Num_Rows / No of Distinct records in ID_VAL More Info @ v$sql_plan_statistics_all

Explain Plan Access Method Table Scan / Index Join Method NL/Hash/Sort Merge Join Order Order in which tables are joined Join Type Anti / Semi / Outer Partition Pruning What partitions are used Parallel Execution Predicate / Column Projections Memory Stats 0/1/M

Full table Scan Majority Rows + Columns Scans up to HWM Multi block Reads Candidate for Parallel Execution

FTS with Filter

Index Fast Full Scan Not Going to Table

Index Unique Scan Not Going to Table

Index to Table

Transform SQL to semantically equivalent SQL - WHY Processed more efficiently Better Plan. I wrote this way because it easy for me, I can develop the application Faster

Query Transformation View Merging

CREATE VIEW V_EMP_SAL AS SELECT * FROM EMP WHERE SAL>100; View Merging SELECT EMP_ID FROM V_EMP_SAL WHERE DEPTNO = 10; SELECT * FROM EMP WHERE SAL>100 AND DEPTNO = 10; ROWNUM PSEUDOCOLUMN SET OPERATORS UNION UNION ALL INTERSECT MINUS CONNECT BY CLAUSE

Transitivity

SELECT T1.COL1, T2.COL2 FROM TBL1 T1, TBL2 T2 WHERE T1.COL1 = T2.COL1 AND T1.COL1 = 100; Transitivity SELECT T1.COL1, T2.COL2 FROM TBL1 T1, TBL2 T2 WHERE T1.COL1 = T2.COL1 AND T1.COL1 = 100 AND T2.COL1 = 100;

Subquery Unnesting

SELECT E.EMPNO, E.DEPTNO FROM EMP E WHERE E.DEPTNO IN (SELECT D.DEPTNO FROM DEPT D WHERE D.LOC = 'CHICAGO') Subquery Unnesting SELECT E.EMPNO EMPNO,E.DEPTNO DEPTNO FROM HARI.EMP E WHERE E.DEPTNO=ANY (SELECT D.DEPTNO DEPTNO FROM HARI.DEPT D WHERE D.LOC='CHICAGO') SELECT E.EMPNO EMPNO,E.DEPTNO DEPTNO FROM HARI.DEPT D,HARI.EMP E WHERE E.DEPTNO=D.DEPTNO AND D.LOC='CHICAGO'

Complex View Merging

SELECT D.DNAME, D.DEPTNO,VW.DEPT_AVG_SAL FROM DEPT D, VW_AVG_SAL VW WHERE D.DEPTNO = VW.DEPTNO AND D.LOC = 'CHICAGO'; SELECT D.DNAME,D.DEPTNO, AVG(EMP.SAL) DEPT_AVG_SAL FROM HARI.DEPT D,HARI.EMP EMP WHERE D.DEPTNO=EMP.DEPTNO AND D.LOC='CHICAGO' GROUP BY D.ROWID,D.DEPTNO,D.DNAME Complex View Merging SELECT D.DNAME DNAME,D.DEPTNO DEPTNO, VW.DEPT_AVG_SAL DEPT_AVG_SAL FROM HARI.DEPT D, ( SELECT EMP.DEPTNO DEPTNO, AVG(EMP.SAL) DEPT_AVG_SAL FROM HARI.EMP EMP GROUP BY EMP.DEPTNO ) VW WHERE D.DEPTNO=VW.DEPTNO AND D.LOC='CHICAGO'

Push Predicates

CREATE OR REPLACE VIEW V_EMP_UNION AS SELECT ENAME, EMPNO FROM EMP E1 WHERE DEPTNO <20 UNION SELECT ENAME, EMPNO FROM EMP E2 WHERE DEPTNO >30; SELECT * FROM VW_EMP_UNION WHERE EMPNO > 7788 SELECT * FROM ( SELECT ENAME, EMPNO FROM EMP E1 WHERE DEPTNO <20 AND EMPNO > 7788 UNION SELECT ENAME, EMPNO FROM EMP E2 WHERE DEPTNO >30 AND EMPNO > 7788 ) ; ; * Push Predicates

Do You Know (DYK) How many row source can be joined together at a time? TWO In a Full Table Scan up to what point oracle scans all the blocks in a table? HWM Hash or Sort-Merge which is more efficient in general? HASH

Join Methods

SORT MERGE JOIN

SORT MERGE JOIN

Join Type Nested Loop Retrieves row from one source and find its corresponding one from another source Hash Join Build Hash Table in memory for smaller row source Go through the other source and uses Hash function on Join Columns

select empno from emp where empno like '11'; Do You Know (DYK) How will my predicate info look like? select * from dept where loc like '%CHENNAI'; This operator can be used instead OR clause. How will my predicate info look like? UNION,Even after having DISTINCT clause in the query, SORT UNIQUE is not done by the Optimizer. If the Data doesn't have duplicates

Case Study - Correlated Subquery

In Action Correlated Subquery SELECT * FROM TAB1 WHERE EXISTS (SELECT 1 FROM TAB2 WHERE TAB2.COL1 = TAB1.COL1)

Not Using my Index

Number <-> Varchar

Fix the Datatype

Approach of Datatype Change now - Impacts the Existing Code Don t Forget the Learning TO_Number Function

Correlated Subquery is the problem, do you know how it works? You should not use Correlated subquery, rewrite it with NOT IN OK?

IS NOT EXISTS = NOT IN?

Lets us dig more Data & Facts

NOT EXISTS ANTI JOIN

NOT IN ANTI JOIN

NOT EXISTS NOT IN ORDERS ******** SINGLE TABLE ACCESS PATH Single Table Cardinality Estimation for ORDERS[O] Table: ORDERS Alias: O Access Path: TableScan Cost: 1074.74 Access Path: index (FullScan) Index: PK_ORDER Cost: 2096.64 Best:: AccessPath: TableScan Cost: 1074.74 ORDERS ******** Single Table Cardinality Estimation for ORDERS[O] Table: ORDERS Alias: O Access Path: TableScan Cost: 1075.36 Access Path: index (FFS) Cost: 777.95 index filter:"o"."book_id" IS NOT NULL Best:: AccessPath: IndexFFS Index: IDX_ORDERS1 Cost: 777.95

Does Index Store NULL Values

Back to Basics Fast Full Index Scan multiple blocks from disk in a single I/O Cost = No of blocks to be scanned + MBRC value Reads the index blocks in no particular order Accesses the data in the index itself, without accessing the table

Fast Full Index Scan Accesses the data in the index itself, without accessing the table

Can I do it even better Yes, Why not at the Design Stage Enforce referential Integrity Mark Columns as NOT NULL Index the Foreign Key Column

I have a CTD After Datatype Correction

CTD cont

Recap View Merging/Subquery Unnesting Views to Base tables / Inline Views Query Transformation Transitivity Optimization Query Execution Plan

Until Yesterday it was running Fine What happened now? DBA Developer Start Comparing Old Plan and New Plan Analyze the Data and understand what has changed The above 2 would help you to dig further

References www.asktom.oracle.com ( NOT IN with NULL Values) Gaja Krishna Vaidyanatha CTD,TKPROF Options - Exadata Performance Mgmt AIOUG Chennai Chapter - 2015

Thanks