ABAP Performance Tuning-BC490 - 2001-Q3 - A4

251
BC490 ABAP Performance Tuning mySAP Technology Date Training Center Instructors Education Website Participant Handbook Course Version: 2001 Q3 Course Duration: 3 Day(s) Material Number: 50066279 An SAP course - use it to learn, reference it for work

Transcript of ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Page 1: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490ABAP Performance Tuning

mySAP Technology

Date

Training Center

Instructors

Education Website

Participant HandbookCourse Version: 2001 Q3Course Duration: 3 Day(s)Material Number: 50066279

An SAP course - use it to learn, reference it for work

Page 2: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Copyright

Copyright © 2004 SAP AG. All rights reserved.

No part of this publication may be reproduced or transmitted in any form or for any purposewithout the express permission of SAP AG. The information contained herein may be changedwithout prior notice.

Some software products marketed by SAP AG and its distributors contain proprietary softwarecomponents of other software vendors.

Trademarks

� Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® areregistered trademarks of Microsoft Corporation.

� IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®,S/390®, AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation.

� ORACLE® is a registered trademark of ORACLE Corporation.� INFORMIX®-OnLine for SAP and INFORMIX® Dynamic ServerTM are registered

trademarks of Informix Software Incorporated.� UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group.� Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®,

VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarksof Citrix Systems, Inc.

� HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, WorldWide Web Consortium, Massachusetts Institute of Technology.

� JAVA® is a registered trademark of Sun Microsystems, Inc.� JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for

technology invented and implemented by Netscape.� SAP, SAP Logo, R/2, RIVA, R/3, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP

EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo and mySAP.comare trademarks or registered trademarks of SAP AG in Germany and in several other countriesall over the world. All other products mentioned are trademarks or registered trademarks oftheir respective companies.

Disclaimer

THESE MATERIALS ARE PROVIDED BY SAP ON AN "AS IS" BASIS, AND SAP EXPRESSLYDISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR APPLIED, INCLUDINGWITHOUT LIMITATION WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE, WITH RESPECT TO THESE MATERIALS AND THE SERVICE,INFORMATION, TEXT, GRAPHICS, LINKS, OR ANY OTHER MATERIALS AND PRODUCTSCONTAINED HEREIN. IN NO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT,INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES OF ANYKIND WHATSOEVER, INCLUDING WITHOUT LIMITATION LOST REVENUES OR LOSTPROFITS, WHICH MAY RESULT FROM THE USE OF THESE MATERIALS OR INCLUDEDSOFTWARE COMPONENTS.

Page 3: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

About This HandbookThis handbook is intended to complement the instructor-led presentation of thiscourse, and serve as a source of reference. It is not suitable for self-study.

Typographic ConventionsAmerican English is the standard used in this handbook. The followingtypographic conventions are also used.

Type Style Description

Example text Words or characters that appear on the screen. Theseinclude field names, screen titles, pushbuttons as wellas menu names, paths, and options.

Also used for cross-references to other documentationboth internal (in this documentation) and external (inother locations, such as SAPNet).

Example text Emphasized words or phrases in body text, titles ofgraphics, and tables

EXAMPLE TEXT Names of elements in the system. These includereport names, program names, transaction codes, tablenames, and individual key words of a programminglanguage, when surrounded by body text, for exampleSELECT and INCLUDE.

Example text Screen output. This includes file and directory namesand their paths, messages, names of variables andparameters, and passages of the source text of aprogram.

Example text Exact user entry. These are words and characters thatyou enter in the system exactly as they appear in thedocumentation.

<Example text> Variable user entry. Pointed brackets indicate that youreplace these words and characters with appropriateentries.

Icons in Body TextThe following icons are used in this handbook.

2001/Q3 © 2004 SAP AG. All rights reserved. iii

Page 4: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

About This Handbook BC490

Icon Meaning

For more information, tips, or background

Note or further explanation of previous point

Exception or caution

Procedures

Indicates that the item is displayed in the instructor�spresentation.

iv © 2004 SAP AG. All rights reserved. 2001/Q3

Page 5: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

ContentsCourse Overview ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Course Goals .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .viiCourse Objectives ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .vii

Unit 1: Course Overview ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Measuring ABAP Performance... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2

Unit 2: Analyzing Individual Objects ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . .11Performing Individual Object Analysis... . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Introduction to Transaction Steps... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15SQL Performance Trace .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21ABAP Runtime Analysis .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33ABAP Debugger.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Unit 3: Database Accesses ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Introduction to Database Accesses... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Unsuitable Access Paths .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Suitable Access Paths .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107

Unit 4: Internal Tables..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Introduction to Internal Tables .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170Working with Internal Tables... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181

Unit 5: R/3 System Analysis.... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207Types of R/3 System Analysis.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208

Appendix 1: Access Costs and Inline Runtime Processing 229

Index ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

2001/Q3 © 2004 SAP AG. All rights reserved. v

Page 6: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Contents BC490

vi © 2004 SAP AG. All rights reserved. 2001/Q3

Page 7: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Course OverviewThis course provides an understanding of how to diagnose and analyze frequenterrors in ABAP programming using SAP�s tools. The course also explains how toimprove ABAP programs and transactions proactively in non-production SAP R/3Enterprise Systems and reactively in production SAP R/3 Enterprise Systems.

Target AudienceThis course is intended for the following audiences:

� Experienced ABAP Programmers� Fundamentals of the SAP R/3 Enterprise database� ABAP courses:

� BC400-ABAP Workbench: Concepts of Process and Tools� BC430 ABAP Dictionary

� Basic courses

� BC315

Course PrerequisitesRequired Knowledge

� ABAP programming with basic knowledge of the R/3 Basis

Course GoalsThis course will prepare you to:

� Diagnose frequent errors in ABAP programming that cause performanceproblems

� Improve ABAP programs and transactions proactively in non-productionSAP R/3 Enterprise Systems and reactively in production R/3 Systems

Course ObjectivesAfter completing this course, you will be able to:

� Use SAP�s tools for monitoring ABAP performance� Systematically analyze ABAP performance problems� Solve ABAP performance problems that cause:� High database load (frequent accesses to the database)

2001/Q3 © 2004 SAP AG. All rights reserved. vii

Page 8: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Course Overview BC490

� High CPU load (frequent accesses to internal tables)

SAP Software Component InformationThe information in this course pertains to the following SAP Software Componentsand releases:

viii © 2004 SAP AG. All rights reserved. 2001/Q3

Page 9: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 1Course Overview

Unit OverviewThis unit provides an overview to this course. The unit discusses the ABAPperformance analysis by giving an overview of the SAP R/3 Enterpriseclient/server architecture and the DBMS architecture. The unit then covers theconcept of roadmaps used throughout in the course.

Unit ObjectivesAfter completing this unit, you will be able to:

� Explain the client/server architecture in the SAP R/3 Enterprise System� Describe the DBMS architecture

Unit ContentsLesson: Measuring ABAP Performance ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2

2001/Q3 © 2004 SAP AG. All rights reserved. 1

Page 10: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 1: Course Overview BC490

Lesson: Measuring ABAP Performance

Lesson OverviewThis lesson helps you understand how to measure the performance of ABAPprograms. To begin with, you will learn about the client/server architecture in theSAP R/3 Enterprise System. Then, you will gain an understanding of the DBMSarchitecture in the SAP R/3 Enterprise System.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain the client/server architecture in the SAP R/3 Enterprise System� Describe the DBMS architecture

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 EnterpriseSystem to improve the efficiency of its activities. However, the companyencounters performance problems due to errors in ABAP programming. As adeveloper, you have been entrusted with the task of measuring ABAP performanceto remove bottlenecks in system performance. To do this, you need to understandthe client/server architecture in the SAP R/3 Enterprise System.

ABAP Performance Analysis

Figure 1: Overview of R/3 Client/Server Architecture

2 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 11: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Measuring ABAP Performance

The SAP R/3 Enterprise System has a three-tier client/server architecture with apresentation layer, an application layer, and a database layer. The presentationlayer and the application layer are scalable. This means that if there is a hardwarebottleneck, you can extend the system by adding more front ends and applicationservers. The database - as the central data repository - is not scalable in terms ofsimply adding more databases.

ABAP performance analysis has two main areas of focus. One goal is to reducethe run time of programs on the application server, thereby reducing the CPUload. Another goal is to reduce the database load. Reducing the database load isparticularly important since the database is a central resource.

If the required data is located in the R/3 buffers on the application server,accessing this data requires approximately 0.01 milliseconds per data record.If the data records are read from the database buffer, around 0.1 millisecond isrequired. When the data is read from the disk, this requires approximately 1milliseconds per data record.

An R/3 work process allocates around 5 megabytes (MB) of memory. The R/3table buffers allocate approximately 120 MB (40 MB for single record buffers, 80MB for generic table buffers). The data buffers of the database use around 500MB of memory. The database on the disks can reach a size of several terabytes.

Data transfer between the front end and application server occurs in blocks of2 kilobytes (KB). The transfer between application server and database serveroccurs in blocks of typically 32 KB.

Figure 2: Overview: DBMS Architecture

2001/Q3 © 2004 SAP AG. All rights reserved. 3

Page 12: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 1: Course Overview BC490

The database work processes are a service offered by the database managementteam (DBMS). This service is used by the R/3 work processes. With Oracle,exactly one database work process is assigned to each R/3 work process. Thereare different database services for different purposes (for example, startingcommunications, changing database tables, locking mechanisms, and archiving).

In addition, the database allocates an area of the shared memory, which containsthe data buffer, the DB SQL cache, the redo log information, and so on. Thedatabase files are on the hard disk and are usually administered by a file system.

You can measure the performance of a database server by monitoring the physicalI/O (read and write access to database files), memory consumption, CPUconsumption, and network communication (which is negligible on the centralinstance). To do this, you can use various tools in the SAP R/3 Enterprise System.The performance of a well configured SAP R/3 Enterprise System is largelydetermined by the physical I/O.

Legend for Roadmaps

Figure 3: Legend for Roadmaps

The material in this training course will be summarized in roadmaps. Theseroadmaps use the following symbols:

� Monitor icon: This indicates the initial situation in which you will need toproceed as described in the roadmap. Typically, you will have just completedan analysis task and want to apply an optimization measure.

� Question mark: A yes/no question you must answer. If the answer is yes,apply the procedure indicated in the subsidiary node. If the answer is no,proceed as described in the next sibling node.

� Exclamation mark: Indicates an interim result. Apply the optimizationprocedure in the next sibling node.

� Tool icon: A concrete action is required (end of the optimization path).� Arrow: Refers to another roadmap (end of the optimization path).

4 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 13: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Measuring ABAP Performance

Figure 4: Example of a Roadmap: Runtime Analysis

2001/Q3 © 2004 SAP AG. All rights reserved. 5

Page 14: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 1: Course Overview BC490

Lesson Summary

You should now be able to:� Explain the client/server architecture in the SAP R/3 Enterprise System� Describe the DBMS architecture

6 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 15: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Unit Summary

Unit SummaryYou should now be able to:� Explain the client/server architecture in the SAP R/3 Enterprise System� Describe the DBMS architecture

2001/Q3 © 2004 SAP AG. All rights reserved. 7

Page 16: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit Summary BC490

8 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 17: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

Test Your Knowledge

1. Describe the client/server architecture of the SAP R/3 Enterprise System.

2. List three ways to measure the performance of a database server.

2001/Q3 © 2004 SAP AG. All rights reserved. 9

Page 18: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

Answers

1. Describe the client/server architecture of the SAP R/3 Enterprise System.

Answer: The SAP R/3 Enterprise has a 3-layer client/server architecture,with a presentation layer, an application layer, and a database layer. Thepresentation layer and the application layer are scalable, while the database-as the central data repository- is not scalable in terms of simply addingmore databases.

2. List three ways to measure the performance of a database server.

Answer: The performance of a database server can be measured bymonitoring the following:

� Physical I/O Memory consumption� CPU consumption� Network communication

10 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 19: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2Analyzing Individual Objects

Unit OverviewThis unit discusses analyzing different objects by covering concepts such asperforming individual object analysis, transaction steps, SQL performance trace,ABAP runtime analysis, and ABAP debugger.

Unit ObjectivesAfter completing this unit, you will be able to:

� Define individual objects� Specify the prerequisites for analyzing individual objects� Define transaction steps� Describe the features of the SAP R/3 Workload Monitor� Identify the response time for transaction steps� Describe SQL performance trace� Use the trace list� Describe the features of an ABAP runtime analysis� Limit and measure data in ABAP runtime analysis� Analyze and evaluate the results of an ABAP runtime analysis� Describe the functions of the ABAP debugger� Check memory usage

Unit ContentsLesson: Performing Individual Object Analysis ... . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Lesson: Introduction to Transaction Steps ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Lesson: SQL Performance Trace... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Lesson: ABAP Runtime Analysis ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Lesson: ABAP Debugger .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Exercise 1: Analyze programs using SQL performance trace, ABAPrun time analysis, and the ABAP debugger ... . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

2001/Q3 © 2004 SAP AG. All rights reserved. 11

Page 20: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Lesson: Performing Individual Object Analysis

Lesson OverviewThis lesson provides an overview of individual objects. To begin with, the lessondefines what individual objects are. Next, the lesson describes the variousprerequisites for analyzing individual objects.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Define individual objects� Specify the prerequisites for analyzing individual objects

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 EnterpriseSystem to improve the efficiency of its activities. As a developer, you have beenasked by the senior management to analyze the various individual objects of thecompany�s business processes. To do this, you need to gain an understanding ofindividual objects and the prerequisites to analyze these individual objects.

Prerequisites for Analyzing Individual Objects

� What are individual objects?

� Reports, transactions, or a series of these� Where is the analysis of individual objects performed?

� Quality assurance system or production system� Who performs the individual objects analysis?

� Developer or performance analyst� What are the prerequisites for individual objects analysis?

� The individual object is known� Absence of basic problems (R/3 Basis, database, or hardware)� Representative data sample and user actions (QAS or PRD)� Availability of the person responsible for the process

An object requiring analysis can be a report, a transaction, or a series of reports ortransactions, which form a business process or part of a business process.

The single-object analysis can be performed proactively in the quality assurancesystem for non-production objects or reactively in the production system forproduction objects.

12 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 21: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Performing Individual Object Analysis

The analysis of individual objects may be performed by the developer of the objector by the performance analyst. The person assuming the role of performanceanalyst must be familiar with ABAP and R/3 Basis.

The analysis of individual objects is performed proactively in quality assurancetesting before the object is used in production and reactively typically after anSAP R/3 Enterprise system analysis.

A prerequisite for performing the analysis of individual objects is that there areno fundamental problems with R/3 Basis. To ensure this, use the SAP services,GoingLive and EarlyWatch.

To analyze individual objects, representative business data must be available inthe quality assurance system. In the production system, individual objects shouldbe analyzed at times of representative user activity.

Contact the person responsible for the business process or the programmer if youhave business-oriented or technical questions.

2001/Q3 © 2004 SAP AG. All rights reserved. 13

Page 22: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Lesson Summary

You should now be able to:� Define individual objects� Specify the prerequisites for analyzing individual objects

14 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 23: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Transaction Steps

Lesson: Introduction to Transaction Steps

Lesson OverviewThis lesson provides an overview of transaction steps. To begin with, you willlearn what transaction steps are. Next, you will learn the various features of theSAP R/3 Workload Monitor used to analyze transaction steps. You will also learnabout the various transaction steps response times. Finally, you will learn aboutthe roadmap used to analyze transaction steps.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Define transaction steps� Describe the features of the SAP R/3 Workload Monitor� Identify the response time for transaction steps

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 EnterpriseSystem to improve the efficiency of its activities. As a developer, you needto gather information on the various user requests made and the backgroundprocessing done by the company�s employees during a previous system upgrade.To do this, you need to know about the transaction steps for all user requests madeand the background processing done during that upgrade process.

2001/Q3 © 2004 SAP AG. All rights reserved. 15

Page 24: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Analyzing Transaction Steps

Figure 5: Analyzing Transaction Steps: Overview

During dialog processing, a transaction step corresponds to a change of screens.During an update or spool process, each request counts as a transactions step.Background processing can consist of one or more transaction steps such as thefollowing:

1. Sending the user request to the application server.2. Placing the user request in the dispatcher queue if all SAP R/3 Enterprise

System work processes are occupied.3. Assigning the user request to an SAP R/3 Enterprise System work process.4. Rolling the user context in to the SAP R/3 Enterprise System work process.5. Attempting to satisfy the SQL statement from the SAP R/3 Enterprise

System buffers.6. Sending the SQL statement to the database server.7. Attempting to satisfy the SQL statement from the database buffer.8. Importing from the database the data blocks missing in the database buffer.9. Displacing data blocks from the database buffer.10. Sending the results of SQL statements to the application server.11. Changing the buffered table content following database table changes.12. Sending the results of the user request to the presentation server.13. Rolling the user context out of the SAP R/3 Enterprise System work process.

16 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 25: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Transaction Steps

Figure 6: Analyzing Transaction Steps: R/3 Workload Monitor

To display the statistics for each transaction step, use the transaction code STAT orfrom the SAP R/3 Enterprise System initial screen choose Tools→ Administration→ Monitor→ Performance→ Workload→ Statistics Record.

To toggle between various detailed views, choose from DB, Time, Task/Mem, andBytes. For an overview of all detail views, choose All details.

The detail view DB shows information on the executed transaction steps for asingle transaction step. The average database time for a sequential read (SELECT...ENDSELECT, SELECT ...INTO TABLE) should be around 10 milliseconds perdata record. For a direct read (SELECT SINGLE ...) it should be around 5 ms perrecord. Accesses that change data (UPDATE, INSERT, MODIFY, and DELETE)should require around 20 ms per record.

To help you decide which tool to use for further analysis (SQL Performance Trace,ABAP runtime analysis), look at the response time, dispatcher wait time, CPUtime, and database time (indicated as DB req. time).

2001/Q3 © 2004 SAP AG. All rights reserved. 17

Page 26: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Figure 7: Analyzing Transaction Steps: Response Time

Response time: Time from the receipt of a user request to the sending of aresponse (measured on the application server; does not include network timebetween the presentation server and the application server).

Dispatcher wait time: Time spent by the user request in the dispatcher queue.

Roll-in: Time required to roll the user context in to the SAP R/3 EnterpriseSystem work process.

Load time: The time required to load and generate program objects (coding,screens, and so on).

Processing time: = response time - (dispatcher wait time + roll-in + roll-out +load time + database time + enqueue time + roll-wait time).

Enqueue time: Time from sending an enqueue request to the SAP R/3 EnterpriseSystem enqueue server to the receipt of the results .

Database time: Time from sending an SQL statement to the receipt of the results(includes network time between the application server and the database server).

Roll-wait time: Time in which the user context is rolled out of the work processpending response to an RFC callstep

Roll-out: Time required to roll the user context into the roll buffer.

CPU time: Time spent by the CPU in processing the transaction (measured by theoperating system; not an additive component of the response time).

18 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 27: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Transaction Steps

Figure 8: Analyzing Transaction Steps: Roadmap

To analyze individual objects such as programs and transactions, first examinethe statistics records for each transaction step. Remember to perform the analysisunder production-like conditions (with representative data and, in the productionsystem, with representative user activity).

If in the single statistics records you find that much CPU time is used, look foroptimization potential in application server processing (for example, processinginternal tables) using the ABAP runtime analysis.

If in the single statistics records you find that there is a problem during databaseserver processing, perform an SQL Performance Trace.

2001/Q3 © 2004 SAP AG. All rights reserved. 19

Page 28: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Lesson Summary

You should now be able to:� Define transaction steps� Describe the features of the SAP R/3 Workload Monitor� Identify the response time for transaction steps

20 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 29: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: SQL Performance Trace

Lesson: SQL Performance Trace

Lesson OverviewThis lesson provides an overview of the SQL performance trace. To begin with,the lesson explains the uses and benefits of the SQL performance trace. Next, thelesson discusses the trace list in the SQL performance trace.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Describe SQL performance trace� Use the trace list

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 EnterpriseSystem to improve the efficiency of its activities. As a developer, you need toobtain information on the behavior of the SAP R/3 Enterprise System in order toanalyze performance problems with database access. To do this, you need toactivate the SQL Performance Trace.

Overview of SQL Performance Trace

� SQL Trace

� A record of SQL statements that access the database system� Buffer trace

� A record of data requests for buffered tables� Enqueue trace

� A record of enqueue requests to the enqueue server� RFC trace

� A record of Remote Function Calls received and sent

To obtain an overview of the behavior of the SAP R/3 Enterprise System, youcan record various processes during the execution of an individual object. Toanalyze performance problems with database accesses, activate the SQL trace andthe buffer trace from transaction ST05.

The SQL trace records SQL statements. There may be considerable differencesbetween the SQL statement formed on the ABAP level and the SQL statementthat is received by the database.

2001/Q3 © 2004 SAP AG. All rights reserved. 21

Page 30: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

A buffer trace lets you trace SQL statements that access buffered tables. SQLstatements that access buffered tables can cause buffer reloads, which are indicatedin a buffer trace. An SQL statement accessing a buffered table can result in acompletely different SQL statement if it cannot be satisfied by the SAP R/3Enterprise System table buffer.

Additional tools include the enqueue trace, which records enqueue requests orreleases, indicating the enqueue key and the object involved; as well as the RFCtrace, which records the RFC calls received or sent.

Figure 9: SQL Performance Trace: Initial Screen

To access the SQL Performance Trace, use transaction ST05 or from the SAP R/3Enterprise System initial screen, choose System→ Utilities→ SQL Trace.

Before activating an SQL Performance Trace for a report or a transaction, youshould execute the report once to prevent the buffer load process for the R/3 tablebuffer, the R/3 program buffer, and so on, from being included in the subsequenttrace.

The trace can be activated in the production system without any risk of creatingerrors or inconsistencies.

The trace can be activated by any user and for any object. When activatingthe trace, ensure that you are not using multiple user sessions or running otherprocesses such as background jobs or update processes under the same user IDon this application server. These activities would make the SQL PerformanceTrace difficult to interpret.

22 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 31: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: SQL Performance Trace

For each application server, there is only one active trace file. Therefore, on agiven application server, only one user can activate a trace. The default size of thetrace file is 800 KB. SAP recommends increasing the size of the trace file to 16MB by setting the parameter rstr/max_diskspace to 16 384 000.

Figure 10: SQL Performance Trace: SQL Trace Overview

The SAP R/3 Enterprise database interface receives an SQL statement from theABAP program and converts it to an SQL statement that can be processed bythe database.

For each database operation, the SQL trace measures the time taken from thesending of the request to the database server to the receipt of the results for therequest on the application server via the SAP R/3 Enterprise database interface(including the time spent in the network between the application server and thedatabase server).

The data written to the trace file includes the database response time, a timestamp, the number of transferred data records, the database return code, the text ofthe SQL statement, and additional administrative information for each databaseoperation.

2001/Q3 © 2004 SAP AG. All rights reserved. 23

Page 32: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Trace List and Database Operations

Figure 11: SQL Performance Trace: Trace List

The trace list is the same regardless of the database system. Data operations thatrequire more than 100 milliseconds are marked red. Each section of the list has aheader identifying the user, transaction, SAP R/3 Enterprise System work processnumber, and SAP R/3 Enterprise System client ID. The expanded trace list hasthe following columns:

� hh:mm:ss:ms : Time stamp indicating the begin of sending the databaserequest (hour:minute:second:millisecond)

� Duration: Duration of the database operation in microseconds (variesaccording to system load)

� Program: Name of the program calling the SQL statement� Object: Name of the table or view, as taken from the SQL statement� Oper : Database operation to be executed� Curs : Name of the database cursor� ArrSz: Size of packets containing the data records sent from the database

server to the application server� Rec: Number of data records sent by the database operation� RC: Return code of the database system� Statement: The text of the SQL statement

24 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 33: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: SQL Performance Trace

Figure 12: SQL Performance Trace: Database Operations

During the processing of an SQL statement performing a read access, thefollowing operations occur:

� PREPARE: This operation parses the SQL statement and converts it to astatement that can be processed by the database. In particular, the accessstrategy is determined. Placeholders are used for variables in the SQLstatement.

� OPEN/REOPEN: This operation replaces the placeholders in the SQLstatement with concrete values, and opens the database cursor.

� FETCH: This operation transfers the database records from the databaseserver to the application server. The number of records transferred perFETCH is given by dividing the length of the data record to be read in bytesby the value of dbs/io_buf_size, which, by default, is set to 33 792 bytes.

An SQL statement performing a write access is processed in the same way, exceptthat EXEC/REEXEC is used instead of OPEN/REOPEN and FETCH.

Database cursors per SAP R/3 Enterprise System work process are buffered inthe SAP cursor cache. This enables the PREPARE operation to be omitted forrepeated executions of similar SQL statements. Displacement occurs in the SAPcursor cache.

2001/Q3 © 2004 SAP AG. All rights reserved. 25

Page 34: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Figure 13: SQL Performance Trace: Explain SQL

To access Explain SQL from the trace list, choose Trace → ExplainSQLAlternatively, use the Explain SQL button. Explain SQL is performed forthe SQL statement on which your cursor is currently positioned in the trace list.Explain SQL is only possible for the database operations PREPARE, OPEN,and REOPEN.

In the top part of the Explain SQL display, you see the SQL statement with itsvariables. The lower part of the display shows the access strategy of the SQLstatement.

Double-click the table frame (see 1 in the figure) to display a dialog box containingstatistical information on the table and information on all indexes of the table.Double-click an index (see 2) to display statistical information on it.

Use the Analyze button (see 3) to refresh the statistical information on a tableand its indexes. To enable the cost-based optimizer to function effectively, thestatistical information it uses must be updated after each change to a table or itsindexes. Use the Index Statistics button (see 4) to display an overview of thestatistical information across all indexes.

Use the Explain with hint button (see 5) to display the execution path of an SQLstatement in conjunction with hints. Hints are used to force the database to choosea particular execution path.

26 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 35: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: SQL Performance Trace

Figure 14: SQL Performance Trace: ABAP Display

To access the ABAP code that triggered the issue of the SQL statement, from thetrace list screen, use the ABAP Display button or choose Trace→ ABAP Displayfrom the menu. The ABAP coding is displayed for the SQL statement on whichyour cursor is currently positioned in the trace list. Explain SQL is only possiblefor the database operations PREPARE, OPEN, and REOPEN.

The SQL statement in the ABAP code, which is normally formulated in OPENSQL, may differ considerably from the SQL statement processed by the database.The following list indicates how the SAP R/3 Enterprise database interfaceconverts certain SQL terms:

� A WHERE clause is used for each SQL statement that accesses aclient-dependent table (except for SELECT ... CLIENT SPECIFIED)

� SELECT ... FOR ALL ENTRIES => Several SELECT statements withcorresponding OR clauses

� MODIFY => INSERT or UPDATE� Accessing pooled and cluster tables� EXPORT/IMPORT TO/FROM DATABASE => INSERT/SELECT on

INDX-like tables� OPEN CURSOR/FETCH NEXT => No equivalent in the SQL trace or/

equivalent SELECT

2001/Q3 © 2004 SAP AG. All rights reserved. 27

Page 36: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Figure 15: SQL Performance Trace: Summary

In the trace list, choose Goto→ Summary to display a summarized form of thelist. The list shows the SQL operations, the number of affected data records, andthe processing time required.

The summarized list is particularly useful for identifying loop constructs. The listcan be compressed even further to show the most frequently accessed tables byusing the Summarize button.

Figure 16: SQL Performance Trace: Statement Summary

28 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 37: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: SQL Performance Trace

In the trace list, choose Goto→ Statement Summary to find out how manystructure-identical SQL statements there are, and which tables or views theyaccess (a structure-identical strategy is an identical access strategy with differentvariables). The displayed list is sorted by the time taken with time indicated inmicroseconds.

The list also indicates the percentage of value-identical accesses (identicalSELECTs) and the total number of returned data records. You should avoid allvalue-identical accesses.

Figure 17: SQL Performance Trace: Identical selects

From the trace list, choose Goto→ Identical Selects to see an overview of thevalue-identical SQL statements in a trace (a value identical statement has thesame access strategy and the same variables).

Identical SELECTS deliver an identical quantity of data records. Therefore, itmakes sense to buffer the results in, for example, an internal table of the callingABAP program.

2001/Q3 © 2004 SAP AG. All rights reserved. 29

Page 38: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

From the number of executions of SQL statements that are similar in value, youcan determine the optimization potential. For example, if there are 4 value-similarexecutions on table VVBAK, buffering the resulting data in an internal tablemakes 3 executions unnecessary. This represents an optimization potential for thisSQL statement of between 60% and 75%.

� Trace list

� Per database operation = 200, 000 microseconds� Per SQL statement = 10 Fetches� Nested SQL statements of the same structure = 200, 000 microseconds

in total� Summary or Condensed Summary

� Loop constructs� Benchmark for the most-accessed tables and database views

� Statement summary

� Percentage of avoidable statements� Identical selects

� Always avoid (buffer in program, buffer beyond roll area limits)

The goal of using an SQL Performance Trace is to find SQL statements with ahigh optimization potential. Use three user sessions. One user session is for thetrace list, one for the compressed summary, and one for identical selects.

From the trace list, you can access Explain SQL or the ABAP code. An expensiveSQL statement is indicated when a database operation takes longer than 200, 000microseconds or requires more than 10 FETCHs.

In addition, a series of SQL statements that are similar in structure usuallyindicate nesting that can be optimized considerably. If the structure-identical SQLstatements in a loop or nesting require in total more than 200, 000 microseconds,they can be regarded as expensive.

The display of identical SELECTs tells you which of the statements are similar invalue and are, therefore being executed unnecessarily. You should always avoidunnecessary execution of SQL statements.

30 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 39: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: SQL Performance Trace

Figure 18: Problem classification: Roadmap

Figure 19: SQL Performance Trace: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 31

Page 40: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Lesson Summary

You should now be able to:� Describe SQL performance trace� Use the trace list

32 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 41: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Runtime Analysis

Lesson: ABAP Runtime Analysis

Lesson OverviewThis lesson provides an overview of ABAP runtime analysis. To begin with, youlearn about the three phases of an ABAP runtime analysis. Next, you will learnhow to limit and measure the data in an ABAP runtime analysis. Finally, you willlearn how to analyze and evaluate the results of an ABAP runtime analysis.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Describe the features of an ABAP runtime analysis� Limit and measure data in ABAP runtime analysis� Analyze and evaluate the results of an ABAP runtime analysis

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 EnterpriseSystem to improve the efficiency of its activities. As a developer, you needinformation about all individual objects of your company�s business processes thatare CPU-intensive. To do this, you need to use an ABAP runtime analysis.

Overview of ABAP Runtime Analysis

Figure 20: ABAP Runtime Analysis: Overview

2001/Q3 © 2004 SAP AG. All rights reserved. 33

Page 42: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

The ABAP runtime analysis enables you to analyze the elapsed run time forindividual objects such as transactions, programs, or function modules, orsub-objects such as modularization units or commands. An ABAP runtimeanalysis is especially useful for individual objects that are CPU-intensive (seeWorkload Analysis).

An ABAP runtime analysis has three phases:

� Limiting the data to be measured: In this phase, you decide which objectis to be analyzed. You also decide the type of aggregation that is used (fullaggregation, aggregation per calling position, or no aggregation) and whetherto use filter options (for modularization units or commands).

� Measuring the data: You can measure or record the run time data either inthe same user session in which the ABAP runtime analysis is running, or in aseparate user session. You can also start the ABAP runtime analysis for anSAP R/3 Enterprise work process and record the run time data for an objectthat is being processed by that work process.

� Analyzing the data: When using full aggregation, you analyze the data inthe hit list, which provides a log record for each called modularization unitor instruction. For runtime analyses using no aggregation or aggregationper calling position, there are further hit lists, such as table hit lists or acall hierarchy.

Figure 21: ABAP Runtime Analysis: Initial Screen

To access the initial screen of the ABAP runtime analysis, in any SAP R/3Enterprise System screen choose System→ Utilities→ Runtime analysis→Execute.

34 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 43: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Runtime Analysis

The runtime-analysis results are either saved to an operating system file on thecurrent application server for up to 8 days, or transferred to the front end. Theresults file can be loaded into the ABAP runtime analysis from the front endat any time.

The SAP R/3 Enterprise System parameter abap/atrasizequota specifies howmuch memory should be reserved in the file system to store the results data. TheSAP R/3 Enterprise System parameter abap/atrapath specifies where the resultsdata are stored in the file system. In the Short description field, enter a shorttext to identify your analysis.

In the screen area, In the current user session, select and specify the object to beanalyzed. To execute the object, choose Execute. Alternatively, you can use In aseparate user session to access an R/3 work process (see Obtaining Run Data).

In the section about measurement you can limit the data to be recorded. To dothis, you define or modify variants. When modifying variants, you work with theProgram parts, Instructions, and Duration and type tabs.

Limiting and Measuring Data in ABAP RuntimeAnalysis

Figure 22: ABAP Runtime Analysis: Limit Data (2)

The Program part tab lets you limit the recording of data to specific programparts. For this you must specify the program and its type (program, global class, orsubprogram), and the procedure to be measured. By selecting Within and below,you extend the recording of data to include program parts and instructions withinthe program parts you specified.

In addition, you can limit the recorded data by choosing Specific units. Thisenables you to record the data between either static points, such as the ABAPinstructions SET RUNTIME ANALYZER ON and SET RUNTIME ANALYZER

2001/Q3 © 2004 SAP AG. All rights reserved. 35

Page 44: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

OFF, or between dynamic points, such as the menu options Runtime analysis→Switch on (Transaction code RON) or Runtime analysis→ Switch off (Transactioncode ROFF).

Figure 23: ABAP Runtime Analysis: Limit Data (1)

In the Instructions tab, you can limit the recording of data to specific statementsor types of statements.

Figure 24: ABAP Runtime Analysis: Limit Data (3)

36 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 45: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Runtime Analysis

Under Duration and Type, you can specify the maximum size of the results fileand the maximum recording duration. Select the aggregation level. Selecting Fullaggregation, causes one record to be created for each program part or instruction.Selecting Aggregation per calling position, causes one record to be created in theresults file for each calling position. Selecting No aggregation, causes a record tobe written in the results file for each call.

The ABAP runtime analysis is normally used with a top-down procedure. First,record the run data for an individual object with full aggregation and identifycritical program parts and instructions. Next, limit the recorded data to the criticalprogram parts and instructions, and set the aggregation level to per calling positionor no aggregation to receive more detailed information.

Figure 25: ABAP Runtime Analysis: Measuring the data

Under In the current user session in the ABAP runtime analysis initial screen,specify the object to be analyzed (a transaction, program, or function module). Toexecute the object, choose Execute. This causes the object to be run in the sameuser session as the ABAP runtime analysis. After the object has run, the ABAPruntime analysis results screen appears, and you can begin evaluating the results.

If you choose Switch on/off under In a separate user session, a screen appearslisting all SAP R/3 Enterprise System work processes running on the currentapplication server. To switch on runtime analysis for the object currently runningin any SAP R/3 Enterprise System work process, choosing Edit→ Runtimeanalysis→ Switch on. To stop the runtime analysis, from the ABAP runtimeanalysis initial screen, choose Switch on/off. Alternatively, from the menu,choose Edit→ Runtime analysis→ Switch off. Using this Switch on/off functionis a useful way of obtaining a snapshot analysis. You can directly monitorlong-running programs in order to identify critical program parts of instructions.

2001/Q3 © 2004 SAP AG. All rights reserved. 37

Page 46: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

The limits to recorded data that you set in the initial screen apply equally to aruntime analysis run in the current user session and to a runtime analysis run ina separate user session using the Switch on/off function. You can also use fullaggregation with the snapshot analysis in parallel mode.

Analyzing and Evaluating Results of ABAP RuntimeAnalysis

Figure 26: ABAP Runtime Analysis: Analyzing the Results (1)

From the ABAP runtime analysis initial screen, you can select the performanceresults file you want to access. Then choose Execute to display those results.

The Runtime Analysis Evaluation: Overview screen initially provides a bar chartcomparing the distribution of the runtime between the ABAP processing, thedatabase, and the SAP R/3 Enterprise System. Beneath the bar chart is informationon the conversions and the total number of loaded programs.

38 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 47: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Runtime Analysis

From this overview screen, you can access various other detailed data views. Toaccess these views, choose from the icons in the toolbar or from the menu, chooseGoto→ Hit list, or Goto→ Object-centered hit list .

� Hit list

� Lists all called program parts or commands� Group hit list

� Lists all commands according to category� Table hit list

� Lists all accesses to database tables� Hit list of internal tables

� Lists all internal tables� Call hierarchy

� Lists the analyzed objects in chronological order

Hit list: A list of all called program parts or instructions, sorted according to grosstime. It contains one row for each program part or instruction. This row showsthe name of the program part of instruction, the gross time, the net time, and thenumber of times this program part or instruction was called.

Group hit list: A list of individual calls of instructions grouped according toinstruction categories (such as forms, function modules, methods), indicatingthe gross run time and the number of times the instruction was called. The listcontains one row for each call of an instruction.

Table hit list: A list showing accesses to database tables indicating the accessname, the number of accesses, the table type, the buffering mode, and otherinformation sorted according to access time.

Hit list of internal tables: A list of all internal table accesses that indicates theinternal name, the number of accesses, the gross and net time taken (as an absolutevalue and as a percentage), the memory required, and other information. Thelist is sorted according to gross time.

Call hierarchy: A list showing the chronological sequence of analyzed objects,and indicating the gross and net time taken and the call level.

In each detailed view, you can use various functions, including sort options,toggling between absolute and percentage time, accessing still more detailedviews, and displaying ABAP source code.

2001/Q3 © 2004 SAP AG. All rights reserved. 39

Page 48: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Figure 27: ABAP Runtime Analysis: Evaluating the Results (3)

Gross time is the total time required to execute the relevant functions.

Net time is the gross time minus the time taken by any modularization units andseparate statements (which can be limited in the ABAP runtime initial screenusing variants). The net time is the time that is not otherwise accounted for.

If the gross time is the same as the net time, these times are not indicated separately.

You can display times either as a percentage or as absolute times in microseconds.

Figure 28: Example of a Roadmap: Runtime Analysis

40 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 49: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Runtime Analysis

Lesson Summary

You should now be able to:� Describe the features of an ABAP runtime analysis� Limit and measure data in ABAP runtime analysis� Analyze and evaluate the results of an ABAP runtime analysis

2001/Q3 © 2004 SAP AG. All rights reserved. 41

Page 50: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Lesson: ABAP Debugger

Lesson OverviewThis lesson provides an overview of the ABAP debugger. You will learn about thefunctions of the ABAP debugger. You will also learn how to check the memoryusage of an internal table.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Describe the functions of the ABAP debugger� Check memory usage

Business ExampleABC Limited is a petrochemical company. It has installed SAP R/3 EnterpriseSystems to improve the efficiency of its activities. You have seen that someinstructions are slowing down the performance of the systems. As a developer,you want to check the memory allocated to and used by all internal tables. To dothis, you need to use the ABAP debugger.

Memory Usage

Figure 29: ABAP Debugger: Memory Usage (1)

42 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 51: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Debugger

The ABAP debugger enables you to run through an object step by step and isnormally used to check functionality. Specific functions of the debugger are alsorelevant to performance.

From a performance perspective, large internal tables are often problematicbecause instructions that affect them (such as LOOP AT.... ENDLOOP, READTABLE..., or SORT ) often require much CPU time and effectively increase objectruntime and slow down the system in general. Thus it is useful to check thememory use of internal tables during the running of a program.

To find out how much memory is allocated for and used by an internal table,from the ABAP runtime analysis initial screen choose Settings→ Table memory,position the cursor on the table and choose Table.

Figure 30: ABAP Debugger: Memory Use (2)

To display a list of the properties of all internal tables used in the current programrun, choose Goto→ System→ System areas, and enter ITAB in the Area field.The resulting list displays information such as the column width or the currentnumber of rows, which in turn enables you to calculate the memory use.

Since error situations or implicit database commits may occur when using thedebugger, and can cause inconsistencies, make sure that you are working in thetest or development system.

2001/Q3 © 2004 SAP AG. All rights reserved. 43

Page 52: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

44 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 53: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Debugger

Exercise 1: Analyze programs usingSQL performance trace, ABAP run timeanalysis, and the ABAP debugger

Exercise ObjectivesAfter completing this exercise, you will be able to:� Analyze the performance critical parts of programs using SQL performance

trace, run time analysis, and the ABAP debugger

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 EnterpriseSystem to improve the efficiency of its activities. However, the company isencountering problems due to some errors in ABAP programming. As a developer,you need to optimize system performance. To do this, you need to analyze theperformance-critical parts of programs using the SQL performance trace, runtime analysis, and the ABAP debugger.

Task 1:1. Copy the program SAPBC490T_PROJECT_CASE_STUDY to the

program ZBC490_##_PROJECT_CASE_STUDY. ## is the group number.

Familiarize yourself with the structure of the program. The main databaseaccesses occur in the subroutine GET_ELIGIBLE_SALES_ITEMS.

Look for runtime-intensive parts of the program. After you have gatheredthe information in this exercise, you can find the causes of poor performanceand solve the problems in later exercises.

Task 2:To find performance-critical database accesses, use the SQL trace (transactionST05).

1. Perform a trace for the tables VVBAK, VVBAP, VVBEP,MMARC, andKKNA1 (use the filter function in ST05). Limit the number of recordsreturned to 5000.

2. Identify the identical SELECTs. To do this, use the menu path Goto→Identical Selects. Make a note of the table names (use the "log" providedbelow).

3. Summarize the output list to find SELECTs within LOOPs. To do this,use the menu path Goto→ Summary. Make a note of what you find out.Summarize the output list to find the most frequently accessed tables.

Continued on next page

2001/Q3 © 2004 SAP AG. All rights reserved. 45

Page 54: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

4. Analyze the SQL statements.

Task 3:To find performance-critical parts of the program, use the runtime analysis(transaction SE30). Define a variant for performance data restrictions thatmeasures internal tables, subroutines, and OPEN SQL statements.

1. Display the Hit List. Sort the list according to gross times. This gives you anoverview of particularly runtime-intensive subroutines and internal tables.Write down the names of the subroutines and internal tables, the runtimerequired, and the number of executions.

2. Now sort the hit list according to the number of executions. This givesyou an overview of frequently executed entities. It may be the case thatindividual statements are not performance-intensive, but are executed withunnecessary frequency. Write down the statements, their runtimes, and thenumber of executions.

Task 4:1. Use the ABAP debugger to determine the size of the internal tables you

wrote down in the runtime analysis. Can you establish a connection betweenthe largest internal table and some of the frequently executed statements(see runtime analysis log)?

Task 5:1. Write down the whole runtime of the program so that you have a value for

comparison later on.

Hint: In the runtime analysis, internal tables have the prefix IT_. Tofind the name of an internal table for a particular row, position thecursor on that row in the hit list, and go from there to the source code.

To determine the size of the internal tables, place a breakpoint infront of the subroutine GET_SOURCE_LIST.

SQL Trace Log

Identical SELECTs occurred for the tables:

__________________________________

__________________________________

There were SELECT-loops over the tables:

__________________________________

Continued on next page

46 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 55: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Debugger

__________________________________

SQL statements:

__________________________________

__________________________________

Comments/improvements

___________________________________

___________________________________

Runtime analysis log

Performance-critical subroutines (critical to DB or CPU?)

___________________________________

___________________________________

___________________________________

___________________________________

Comments/improvements

___________________________________

___________________________________

Debugger log

Size and memory consumption of internal tables

_____________________________________

_____________________________________

Comments/improvements

_____________________________________

_____________________________________

Overall runtime (in microseconds):

______________________________________

2001/Q3 © 2004 SAP AG. All rights reserved. 47

Page 56: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Solution 1: Analyze programs usingSQL performance trace, ABAP run timeanalysis, and the ABAP debuggerTask 1:1. Copy the program SAPBC490T_PROJECT_CASE_STUDY to the

program ZBC490_##_PROJECT_CASE_STUDY. ## is the group number.

Familiarize yourself with the structure of the program. The main databaseaccesses occur in the subroutine GET_ELIGIBLE_SALES_ITEMS.

Look for runtime-intensive parts of the program. After you have gatheredthe information in this exercise, you can find the causes of poor performanceand solve the problems in later exercises.

a) In the SQL trace, your results should be as follows:

Identical SELECTs:

You will find a large number of identical SELECTs for tables KKNA1and MMARC.

Summary of the output list (Goto→ Summary):

You will see that table VVBAK is the outer table in a loop construction(driver table). The data records of tables KKNA1, VVBEP, VVBAP,and MMARC are read within the loop over VVBAK.

Condensed summary of the results list (Goto→ Summary →Condense):

In total, the database accesses to tables KKNA1, MMARC, VVBEP,and VVBAP are the most expensive within the SQL trace beingexamined.

Continued on next page

48 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 57: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Debugger

Task 2:To find performance-critical database accesses, use the SQL trace (transactionST05).

1. Perform a trace for the tables VVBAK, VVBAP, VVBEP,MMARC, andKKNA1 (use the filter function in ST05). Limit the number of recordsreturned to 5000.

a) In the runtime analysis, your results should be as follows:

Sorting the hit list according to gross times

The subroutine GET_ELIGIBLE_SALES_ITEMS is processed onceand has a long runtime. It is therefore very important to optimize thissubroutine.

LOOP and SORT statements are executed five times in total over thetable itab with long gross and net runtimes.

2. Identify the identical SELECTs. To do this, use the menu path Goto→Identical Selects. Make a note of the table names (use the "log" providedbelow).

a) Sorting the hit list according to the number of executions:

The subroutines PROCESS_SCHEDULE_LINES andPROCESS_GET_NAME1 are processed frequently. The total runtimeof these calls is long. You should therefore optimize these subroutines.

You will see that the number of accesses to tableMMARC is greaterthan the number of entries in the internal table itab.

3. Summarize the output list to find SELECTs within LOOPs. To do this,use the menu path Goto→ Summary. Make a note of what you find out.Summarize the output list to find the most frequently accessed tables.

a)

4. Analyze the SQL statements.

a)

Continued on next page

2001/Q3 © 2004 SAP AG. All rights reserved. 49

Page 58: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Task 3:To find performance-critical parts of the program, use the runtime analysis(transaction SE30). Define a variant for performance data restrictions thatmeasures internal tables, subroutines, and OPEN SQL statements.

1. Display the Hit List. Sort the list according to gross times. This gives you anoverview of particularly runtime-intensive subroutines and internal tables.Write down the names of the subroutines and internal tables, the runtimerequired, and the number of executions.

a) In the debugger, your results should be as follows:

You will see that the internal table itab is the largest table.

2. Now sort the hit list according to the number of executions. This givesyou an overview of frequently executed entities. It may be the case thatindividual statements are not performance-intensive, but are executed withunnecessary frequency. Write down the statements, their runtimes, and thenumber of executions.

a) You will see that SELECT statements for table MMARC (which youcan find in the runtime analysis) are executed more frequently thanthere are rows in the table.

Task 4:1. Use the ABAP debugger to determine the size of the internal tables you

wrote down in the runtime analysis. Can you establish a connection betweenthe largest internal table and some of the frequently executed statements(see runtime analysis log)?

a)

Task 5:1. Write down the whole runtime of the program so that you have a value for

comparison later on.

Hint: In the runtime analysis, internal tables have the prefix IT_. Tofind the name of an internal table for a particular row, position thecursor on that row in the hit list, and go from there to the source code.

To determine the size of the internal tables, place a breakpoint infront of the subroutine GET_SOURCE_LIST.

SQL Trace Log

Identical SELECTs occurred for the tables:

Continued on next page

50 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 59: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: ABAP Debugger

__________________________________

__________________________________

There were SELECT-loops over the tables:

__________________________________

__________________________________

SQL statements:

__________________________________

__________________________________

Comments/improvements

___________________________________

___________________________________

Runtime analysis log

Performance-critical subroutines (critical to DB or CPU?)

___________________________________

___________________________________

___________________________________

___________________________________

Comments/improvements

___________________________________

___________________________________

Debugger log

Size and memory consumption of internal tables

_____________________________________

_____________________________________

Comments/improvements

_____________________________________

_____________________________________

Overall runtime (in microseconds):

______________________________________

a)

2001/Q3 © 2004 SAP AG. All rights reserved. 51

Page 60: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 2: Analyzing Individual Objects BC490

Lesson Summary

You should now be able to:� Describe the functions of the ABAP debugger� Check memory usage

52 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 61: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Unit Summary

Unit SummaryYou should now be able to:� Define individual objects� Specify the prerequisites for analyzing individual objects� Define transaction steps� Describe the features of the SAP R/3 Workload Monitor� Identify the response time for transaction steps� Describe SQL performance trace� Use the trace list� Describe the features of an ABAP runtime analysis� Limit and measure data in ABAP runtime analysis� Analyze and evaluate the results of an ABAP runtime analysis� Describe the functions of the ABAP debugger� Check memory usage

2001/Q3 © 2004 SAP AG. All rights reserved. 53

Page 62: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit Summary BC490

54 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 63: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

Test Your Knowledge

1. Which of the following is true for single-object analysis?Choose the correct answer(s).□ A Single-object analysis can be performed proactively in the quality

assurance system for non-production objects.□ B Single-object analysis can be performed proactively in the

production system for non-production objects.□ C Single-object analysis can be performed reactively in the

production system for production objects.□ D Single-object analysis requires that representative data must be

available in the quality assurance system.

2. A prerequisite for performing the analysis of individual objects is thatrepresentative business data must be available in the quality assurancesystem.Determine whether this statement is true or false.□ True□ False

3. Which of the following are valid transaction steps for backgroundprocessing?Choose the correct answer(s).□ A Sending the user request to the database server.□ B Assigning the user request to an SAP R/3 Enterprise System

work process.□ C Sending the SQL statement to the database server.□ D Rolling the user context out of the SAP R/3 Enterprise System

work process.

4. You can use the transaction code to display the statistics foreach transaction step.Fill in the blanks to complete the sentence.

2001/Q3 © 2004 SAP AG. All rights reserved. 55

Page 64: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

5. Which of the following definitions are correct?Choose the correct answer(s).□ A Response time is the time from the receipt of a user request to the

sending of a response.□ B Load time is the time required to load and generate program

objects.□ C Roll wait time is the time required to roll the user context into

the roll buffer.□ D CPU time is the time spent by the CPU in processing the

transaction step.

6. What are the different types of data written to the trace file?

7. Database cursors per SAP R/3 Enterprise System work process are bufferedin the SAP .Fill in the blanks to complete the sentence.

8. Which of the following are the phases of an ABAP runtime analysis?Choose the correct answer(s).□ A Limiting the data to be measured□ B Comparing the data□ C Measuring the data□ D Analyzing the data

9. Which of the following is NOT correct?Choose the correct answer(s).□ A The tab "Program part" lets you limit the recording of data to

specific program part.□ B The tab "Specific units" lets you record the data between either

static points or between dynamic points.□ C The tab "Instructions" lets you limit the recording of data to

specific dynamic points.□ D The option "Duration and Type" can be used to specify the

maximum size of the results file and the maximum recordingduration.

56 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 65: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

10. Which of the following are correct?Choose the correct answer(s).□ A Hit list is a list of all called program parts or instructions, sorted

according to gross time.□ B Call hierarchy is a list showing the chronological sequence of

analyzed objects, and indicating the gross and net time takenand the call level.

□ C Table hit list is a list of all internal table accesses that indicate theinternal name, the number of accesses, the gross and net timetaken, the memory required, and other information.

□ D Group hit list is a list of individual calls of instructions groupedaccording to instruction categories, indicating the gross run timeand the number of times the instruction was called.

11. What are the functions of the ABAP debugger?

12. How can you check the amount of memory allocated for and used by aninternal table?

2001/Q3 © 2004 SAP AG. All rights reserved. 57

Page 66: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

Answers

1. Which of the following is true for single-object analysis?

Answer: A, B, D

The single-object analysis can be performed proactively in the qualityassurance system for non-production objects, or reactively in the productionsystem for production objects.

2. A prerequisite for performing the analysis of individual objects is thatrepresentative business data must be available in the quality assurancesystem.

Answer: True

A prerequisite for performing the analysis of individual objects is thatrepresentative business data must be available in the quality assurancesystem.

3. Which of the following are valid transaction steps for backgroundprocessing?

Answer: B, C, D

The valid transaction steps for background processing are as follows:

� Sending the user request to the application server.� Assigning the user request to an SAP R/3 Enterprise System work

process.� Sending the SQL statement to the database server.� Rolling the user context out of the SAP R/3 Enterprise System work

process.

4. You can use the transaction code STAD to display the statistics for eachtransaction step.

Answer: STAD

5. Which of the following definitions are correct?

Answer: A, B, D

Roll wait time is the time in which the user context is rolled out of the workprocess pending response to an RFC call.

58 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 67: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

6. What are the different types of data written to the trace file?

Answer: The data written to the trace file includes the database responsetime, a time stamp, the number of transferred data records, the databasereturn code, the text of the SQL statement, and additional administrativeinformation for each database operation.

7. Database cursors per SAP R/3 Enterprise System work process are bufferedin the SAP cursor cache.

Answer: cursor cache

8. Which of the following are the phases of an ABAP runtime analysis?

Answer: A, C, D

The three phases of an ABAP runtime analysis are as follows:

� Limiting the data to be measured� Measuring the data� Analyzing the data

9. Which of the following is NOT correct?

Answer: C

The tab "Instructions" can be used to limit the recording of data to specificstatements or types of statements.

10. Which of the following are correct?

Answer: A, B, D

Table hit list is a list showing accesses to database tables indicating theaccess name, the number of accesses, the table type, the buffering mode, andother information sorted according to access time.

11. What are the functions of the ABAP debugger?

Answer: The ABAP debugger enables you to run through an object step bystep and is normally used to check functionality. Specific functions of thedebugger are also relevant to performance.

2001/Q3 © 2004 SAP AG. All rights reserved. 59

Page 68: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

12. How can you check the amount of memory allocated for and used by aninternal table?

Answer: To find out how much memory is allocated for and used by aninternal table, from the ABAP runtime analysis initial screen choose Settings→ Table memory, position the cursor on the table and choose Table.

60 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 69: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3Database Accesses

Unit OverviewThis unit provides an overview to database accesses. The unit first introducesdatabase accesses and then covers unsuitable and suitable access paths in detail.

Unit ObjectivesAfter completing this unit, you will be able to:

� Explain database accesses� Identify suitable and unsuitable access paths� Identify database indexes� Identify database joins� Explore possible problems within the system database� Use database hints� Explain general methods of reducing the number of data records to be

transferred� Describe ways of accessing individual and several tables� Describe Pooled and Cluster tables� Explain SAP table buffering

Unit ContentsLesson: Introduction to Database Accesses ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Lesson: Unsuitable Access Paths .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Exercise 2: Optimizing Customer database .. . . . . . . . . . . . . . . . . . . . . . . . . . .103Lesson: Suitable Access Paths .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107

Exercise 3: Suitable Access Path for a Table.. . . . . . . . . . . . . . . . . . . . . . . . . .153Exercise 4: Suitable Access Paths for Several Tables .. . . . . . . . . . . . . . .159

2001/Q3 © 2004 SAP AG. All rights reserved. 61

Page 70: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Lesson: Introduction to Database Accesses

Lesson OverviewIn this lesson, you will learn about database accesses. You will also learn aboutthe cost-based database optimizer and DB SQL Cache. In addition, you will beable to identify how to optimize SQL statements by using suitable and unsuitableaccess paths.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain database accesses� Identify suitable and unsuitable access paths

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters database problems due to suitable and unsuitable access paths. As adeveloper, you need to optimize database access.

Overview of Database Accesses

Figure 31: Overview: Cost-Based Database Optimizer

For each SQL statement, the database optimizer determines the strategy foraccessing data records. Access can be with database indexes (index access), orwithout database indexes (full table scan).

62 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 71: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Database Accesses

The cost-based database optimizer determines the access strategy on the basis of:

� Conditions in the WHERE clause of the SQL statement� Database indexes of the table(s) affected� Selectivity of the table fields contained in the database indexes� Size of the affected table(s)

The table and index statistics supply information about the selectivity of tablefields, the selectivity of combinations of table fields, and table size.

Before a database access is performed, the database optimizer cannot calculatethe exact cost of a database access. The optimizer uses the information describedabove to estimate the cost of the database access.

The optimization calculation is the amount by which the data blocks to be read(logical read accesses) can be reduced. Data blocks show the level of detail inwhich data is written to the hard disk or read from the hard disk.

Figure 32: Overview: DB SQL Cache

To avoid repeating the time-consuming and costly procedure of parsing an SQLstatement and determining an access strategy, SQL statements are buffered withthe chosen access strategy in the DB SQL cache (shared memory area) of thedatabase server.

For a received SQL statement, the DBMS first checks whether the statementalready exists in the DB SQL cache. If it does exist, the statement can be usedimmediately. If it does not exist, the SQL statement must be parsed and the accessstrategy must be determined again.

2001/Q3 © 2004 SAP AG. All rights reserved. 63

Page 72: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Next, the DBMS attempts to read the data blocks required by the SQL statementfrom the data buffer (logical read access). If this is possible, physical read accessesare not necessary. If this is not possible, the missing data blocks are read from thedatabase files on the hard disk (physical read accesses).

Suitable and Unsuitable Access Paths

Figure 33: Overview: Suitable / Unsuitable Access Path

With an appropriate access path:

� The SQL statement reads many data blocks in the database. The statement isexpensive because it transfers many data records from the database to theapplication server. Database performance is satisfactory. The criterion usedis that less than 5 data blocks should be read per data record.

� Expensive SQL statements with a suitable access path are listed at the topof the database SQL cache since they execute frequently. A problem withthe application logic is usually indicated. This problem can be fixed throughchanges to the ABAP code or to the business process.

Unsuitable Access Path:

� The SQL statement reads many data blocks in the database but does nottransfer many data records from the database to the application server.Database performance is not optimal. The criterion used is that more than 5data blocks should be read per data record.

� Expensive SQL statements with no appropriate access paths can be optimizedeither by creating or improving the design of an index, or modifying theABAP code to improve a poorly designed WHERE clause.

64 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 73: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Database Accesses

Figure 34: Overview: Unsuitable Access Path

If the single object analysis establishes that an expensive SQL statement has anunsuitable access path, you can narrow (and thus optimize) the search.

The search range is the number of data records that need to be checked in a tablein order to satisfy an SQL statement. When the SQL statement is processed on thedatabase, the search range is dynamically determined by the WHERE clause, thedatabase index used, and the access strategy selected.

You can narrow the search by:

� Solving technical problems� Changing the ABAP Coding� Changing the Index Design� Using Database Hints

2001/Q3 © 2004 SAP AG. All rights reserved. 65

Page 74: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 35: Overview: Suitable Access Path (1)

If the single object analysis establishes that the SQL statement analyzed has asuitable access path, you can optimize it by:

� Reducing the rows to be transferred� Reducing the columns to be transferred� Reducing data transfer� Avoiding unnecessary SQL statements

You can reduce the number of rows to be transferred by optimizing the WHEREclause or by using aggregate functions.

You can reduce the number of columns to be transferred by formulating a suitablefield list or, in the case of database changes, by using UPDATE .. SET.

66 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 75: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Database Accesses

Figure 36: Overview: Suitable Access Path (2)

You can reduce data transfers between the database server and the applicationserver by formulating your SQL statements in such a way that data transfers takeplace in as large blocks as possible (a full fetch is 32 KB). You can do this byavoiding nested SELECT statements, for example.

Unnecessary SQL statements are either similar or identical SQL statements.Similar SQL statements can often be grouped together. Identical SQL statementscan be avoided by buffering data in the program. By using SAP table buffering,you can prevent SQL statements from having to be read at database level.

2001/Q3 © 2004 SAP AG. All rights reserved. 67

Page 76: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Lesson Summary

You should now be able to:� Explain database accesses� Identify suitable and unsuitable access paths

68 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 77: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Lesson: Unsuitable Access Paths

Lesson OverviewIn this lesson, you will be introduced to database indexes and database joins Youwill also learn to identify the possible problems within the system database.Additionally, you will learn how to optimize the database.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Identify database indexes� Identify database joins� Explore possible problems within the system database� Use database hints

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters database problems due to suitable and unsuitable access paths. As adeveloper, you need to optimize database access.

Introduction to Database Indexes

Figure 37: Introduction to DB Indexes: Overview (1)

When you create a database table in the ABAP Dictionary, you must specify thecombination of fields that enable an entry within the table to be clearly identified.Position these fields at the top of the table field list, and define them as key fields.

2001/Q3 © 2004 SAP AG. All rights reserved. 69

Page 78: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

After activating the table, an index is created (for Oracle, Informix, and DB2)that consists of all key fields. This index is called a primary index. The primaryindex is unique by definition.

As well as the primary index, you can define one or more secondary indexes fora table in the ABAP Dictionary, and create them on the database. Secondaryindexes can be unique or non-unique.

The example shows two unique indexes (Index A and Index B) pointing to tableX. Index records and table records are organized in data blocks.

If you dispatch an SQL statement from an ABAP program to the database, theprogram searches for the data records requested either in the database table itself(full table scan) or by using an index (index unique scan or index range scan). Ifyou find all the requested fields in the index using an index scan, you do notneed to access the table records.

A data block shows the level of detail in which data is written to the hard disk orread from the hard disk. Data blocks may contain multiple data records, but asingle data record may be spread across several data blocks.

Figure 38: Introduction to DB Indexes: Overview (2)

Data blocks can be index blocks or table blocks. The database organizes the indexblocks in the form of a multi-level B* tree. There is a single index block at rootlevel, which contains pointers to the index blocks at branch level. The branchblocks contain either some of the index fields and pointers to index blocks atleaf level, or all index fields and a pointer to the table records organized in tableblocks. The index blocks at leaf level contain all index fields and pointers tothe table records from the table blocks.

70 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 79: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

The pointer that identifies one or more table records has a specific name. Forexample, the pointer is called ROWID for Oracle databases. The ROWID consistsof the number of the database file, the number of the table block, and the rownumber within the table block.

The index records are stored in the index tree and sorted according to index fields.This enables accelerated access using the index. The table records in the tableblocks are not sorted.

An index should not consist of too many fields. Having a few very selectivefields increases the chance of reusability, and reduces the chance of the databaseoptimizer selecting an unsuitable access path.

Figure 39: Introduction to DB Indexes: Index Unique Scan

If, for all fields in a unique index (primary index or unique secondary index),WHERE conditions are specified with an equal sign (=) in the WHERE clause, thedatabase optimizer selects the access strategy index unique scan.

For the index unique scan access strategy, the database usually needs to read amaximum of four data blocks (three index blocks and one table block) to accessthe table record.

In the SELECT statement, the VVBAK table is accessed. The MANDT andVBELN fields form the primary key, and are specified with an equal sing (=) inthe WHERE clause. The database optimizer selects the index unique scan accessstrategy, and only needs to read four data blocks to find the requested table record.

2001/Q3 © 2004 SAP AG. All rights reserved. 71

Page 80: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 40: Introduction to DB indexes: Index Range Scan (1)

In the example not all fields in the primary index of the VVBAP table (keyfields MANDT, VBELN, and POSNR) are specified with an equal sign (=) inthe WHERE clause. The database optimizer checks a range of index recordsand deduces the table records from these index records. This access strategy iscalled an index range scan.

To execute the SQL statement, the DBMS first reads a root block (1) and a branchblock (2). The branch block contains pointers to two leaf blocks (3 and 4). Inorder to find the index records that fulfill the criteria in the WHERE clause of theSQL statement, the DBMS searches through these leaf blocks sequentially. Theindex records found point to the table records within the table blocks (5 and 6).

If index records from different index blocks point to the same table block, thistable block must be read more than once. In the example above, an index recordfrom index block 3 and an index record from index block 4 point to table recordsin table block 5. This table block must therefore be read twice. In total, seven datablocks (four index blocks and three table blocks) are read.

The index search string is determined by the concatenation of the WHEREconditions for the fields contained in the index. To ensure that as few index blocksas possible are checked, the index search string should be specified starting fromthe left, without placeholders or percentage signs (%). Because the index is storedand sorted according to the index fields, a connected range of index records canbe checked, and fewer index blocks need to be read.

72 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 81: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 41: Introduction to DB Indexes: Index Range Scan (2)

In the example, an index range scan is performed on the VVBAP table using theprimary index. Since no WHERE condition is specified for the VBELN field inthe SQL statement, the corresponding places for VBELN are filled with �_� inthe index search string.

The range that can be used to select the index blocks (that is, the fully specifiedrange starting from the left), therefore only consists of the MANDT field. Sincemany index records fulfill the condition MANDT = �001�, a large number ofindex blocks are read, and their index records checked. All the index records arethen filtered out that fulfill the condition POSNR = �0001�. The relevant indexrecords point to the table records.

If a further WHERE condition had been specified in the SQL statement for a fieldthat was not in the index, this WHERE condition would only have been evaluatedafter the table records had been read from the table blocks.

2001/Q3 © 2004 SAP AG. All rights reserved. 73

Page 82: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 42: Introduction to DB Indexes: Index Range Scan (3)

Due to outdated update statistics, database optimizer errors, missing indexes,or inappropriate ABAP coding, the database optimizer may select a completelyunsuitable index, and then perform an unselective index range scan.

In the example, WHERE conditions are only specified for MANDT and MATNR.In spite of this, the database optimizer chooses to perform an index range scanover the primary index (MANDT, VBELN, and POSNR). Since there is onlyone unselective WHERE condition (MANDT = �001�) to select the index blocks(due to the WHERE clause), a large number of index blocks are read. Thereis no further WHERE condition to filter the index records. The table recordscorresponding to all suitable index records are therefore read.

More data blocks are read if an unselective index range scan is performed, thanif the table is read sequentially. This is because a table block is read more thanonce if index records in different index blocks point to the same table record.The maximum number of data blocks to be read per SQL statement execution isthus calculated from the product of the number of table blocks and the numberof index blocks.

All index blocks and table blocks read during an index range scan are stored in thedata buffer at the top of an LRU (least recently used) list. This can lead to manyother data blocks being forced out of the data buffer. Consequently, more physicalread accesses become necessary when other SQL statements are executed.

74 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 83: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 43: Introduction to DB Indexes: Concatenation

In the concatenation access strategy, one index is reused. Therefore, various indexsearch strings also exist. An index unique scan or an index range scan can beperformed for the various index search strings. Duplicate entries in the results setare filtered out when the search results are concatenated.

In the SQL statement, a WHERE condition with an IN operation is specifiedover VBELN field. The MANDT and VBELN fields are shown on the left of theprimary index. Various index search strings are created, and an index range scanis performed over the primary index for each index search string. Finally, theresult is concatenated.

2001/Q3 © 2004 SAP AG. All rights reserved. 75

Page 84: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 44: Full Table Scan

If the database optimizer selects the full table scan access strategy, the table is readsequentially. Index blocks do not need to be read.

For a full table scan, the read table blocks are added to the end of an LRUlist. Therefore, no data blocks are forced out of the data buffer. As a result,comparatively little memory space is required within the data buffer to processa full table scan.

The full table scan access strategy is very effective if a large part of a table (forexample, 5% of all table records) needs to be read. In the example a full table scanis more efficient than access using the primary index.

� Index unique scan

� Unique index is fully specified using AND after the equals sign� Index range scan

� Index is not fully specified or not unique� Full table scan

� No index is used� All table blocks are read

� Concatenation

� Indexes are used more than once� Use with OR or IN operation

76 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 85: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Index unique scan: The index selected is unique (primary index or uniquesecondary index) and fully specified. One or no table record is returned. Thistype of access is very effective, because a maximum of four data blocks needs tobe read.

Index range scan: The index selected is unique or non-unique. For a non-uniqueindex, this means that not all index fields are specified in the WHERE clause.A range of the index is read and checked. An index range scan may not be aseffective as a full table scan. The table records returned can range from none to all.

Full table scan: The whole table is read sequentially. Each table block is readonce. Since no index is used, no index blocks are read. The table records returnedcan range from none to all.

Concatenation: An index is used more than once. Various areas of the index areread and checked. To ensure that the application receives each table record onlyonce, the search results are concatenated to eliminate duplicate entries. The tablerecords returned can range from none to all.

Introduction to Database Joins

Figure 45: Introduction to DB Joins: Overview

In the SAP R/3 Enterprise System, users often need to access information stored intables. The database-logical operator used to do this is called the Join operator.

In ABAP, there are various ways to implement the Join operator (nested SELECTs,SELECT FOR ALL ENTRIES, DB views, ABAP JOINS, subqueries, or anexplicit cursor).

2001/Q3 © 2004 SAP AG. All rights reserved. 77

Page 86: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

If you want the database system to determine the resulting set of the Join operator,you can use DB views, ABAP JOINs, or subqueries. DB views are defined in theABAP dictionary and activated to create them in the database. DB views createdby other developers can also be used (reusability). ABAP JOINs are definedin an ABAP program.

The following important access strategies are available to the database optimizerfor processing ABAP JOINs, subqueries, or SQL statements against databaseviews:

Nested loop

Sort merge join

Figure 46: Introduction to DB Joins: Nested loop

When a Join is processed using the nested loop strategy, two steps are performed:

The order of access is determined.

Data is selected from the tables.

The database optimizer first determines the order in which the tables in the Joinare to be accessed. To do this, it uses the WHERE clause to estimate the numberof data records or blocks to be returned for every table in the Join. For the outertable, the database optimizer selects the table with the lowest number of returnedtable records or data blocks because it assumes that in total the fewest data blocksneed to be read in this table. Therefore, the goal once more is to minimize thenumber of data blocks to be read in indexes and tables. If there are more than twotables in the Join, the inner table is selected in the same way.

In the second step, the table records from the outer table are first selected. Forthese table records, the table records from the next inner table are read accordingto the Join condition, and so on.

78 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 87: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

For the SQL statement above, the optimizer selects the VVBAK table as the outertable, because a selective WHERE condition exists for the VVBAK-OBJNR field.For each table record that fulfills the WHERE condition, table records fromVVBUK are selected according to the Join condition.

Figure 47: Introduction to DB Joins: Sort Merge Join

When a Join is processed using the sort merge join access strategy, the followingsteps are performed:

� The table records that correspond to the WHERE clause are selected.� The tables in the Join are sorted according to the Join condition.� The table records are merged.

For the SQL statement, the selective WHERE condition for the CUOBJ field,VVBAP table, and the selective WHERE condition for the OBJNR field, VVBAKtable are evaluated. The resulting sets are sorted according to VBELN. The resultsare then merged.

2001/Q3 © 2004 SAP AG. All rights reserved. 79

Page 88: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

If selective WHERE conditions exist for the relevant tables, a sort merge joinis very effective. If the Join conditions are not selective for any of the relevanttables, the sort merge join access strategy is more effective than a nested loop.If there are more than two tables in the join, you can combine the nested loopand sort merge join access strategies.

� Nested loop

� Determine the key table� Access the inner table via JOIN conditions

� Sort merge join

� Evaluate the WHERE clause on all relevant tables� Sort according to JOIN conditions� Merge the resulting set

Nested loop: This strategy is relevant for database views and ABAP JOINs. First,the WHERE clause is used as a basis for selecting the (outer) table to be used foraccess. Next, starting from the outer table, the table records for the inner tables areselected according to the Join condition.

Sort merge Join: First, the WHERE clause is evaluated for all tables in the Join,and a resulting set is produced for each table. Each resulting set is sorted accordingto the Join conditions and then merged, also according to the Join conditions.

Technical Problems

� The SAP Basis system and database system are not correctly configured

� See the GoingLive or EarlyWatch report� Communication problems� rsdb/max_blocking_factor

� Fragmented database index

� Index blocks filled < 50%

Optimizing SQL statements only makes sense if the SAP R/3 Enterprise Systemand database system are correctly configured. This is the responsibility of theSAP System administrator and the database administrator respectively. Technicalproblems may have an effect on the whole system (for example, wrongly setparameters, communication problems, or old table and index statistics), or mayonly affect SQL statements on certain tables (for example, missing or fragmentedindexes).

To avoid technical problems: Follow the SAP installation instructions and refer toSAP Notes. Implement the recommendations given by the SAP standard servicesGoingLive and EarlyWatch Communication problems may occur between theapplication server and database server (for example, the TCP No Delay problem

80 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 89: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

with Oracle databases, see Note 72638). Parameters on the database interface maybe wrongly set, and thus cause problems (for example, incorrect values for thersdb/max_blocking_factor, see the topics on SELECT FOR ALL ENTRIES).

On some databases (for example, Oracle and Informix), fragmented indexes mayoccur. The term fragmented indexes means that index blocks are less than 50%full. Fragmented indexes can occur, for example, if a large number of tablerecords are deleted and then a large number of table records are inserted. If youdiscover that an index is suitable for an SQL statement, but that executing the SQLstatement causes heavy database system load, your database administrator shouldcheck whether a fragmented index (database-specific) is causing the problem.

Figure 48: Problems with SAP Basis System and Database (2)

The SAP Workload monitor gives you an overview of the general state of yourSAP System. To view the initial screen of the SAP Workload monitor, fromthe SAP standard menu choose Tools→ CCMS→ Control/Monitoring→Performance menu→ Workload→ Analysis, or use Transaction ST03.

From the resulting screen, choose Performance database. In the dialog box thatappears, first select the server to be checked, then the time period (for example,previous weeks), and the examination period (for example, previous week).

If the average database response time for every transaction step is greater than 600ms, the cause is very probably a fundamental SAP or database problem. If thisis the case, the results of the SQL performance trace are not reliable. Your SAPSystem administrator or database administrator should first solve the problem,and then you can repeat the analysis.

2001/Q3 © 2004 SAP AG. All rights reserved. 81

Page 90: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 49: Missing Indexes

Database reorganization or deliberately deleting database objects can causeinconsistencies between the indexes in the ABAP Dictionary and the indexeson the database.

You can find these inconsistencies by using the database monitor. To view theinitial screen of the database monitor, from the SAP standard menu choose Tools→ Administration→ Monitor→ Performance→ Database→ Activity→ DetailAnalysis Menu→ State on disk, or use Transaction DB02. For an overview ofindexes that are missing in the database or not found in the ABAP Dictionary,choose Missing indexes.

If you find indexes that are missing on the database, inform your databaseadministrator. Database indexes can be activated from the database monitor screenor from the ABAP Dictionary, and thus created on the database. Database indexesthat exist on the database but not in the ABAP Dictionary can be created in theABAP Dictionary. Indexes are transferred to the database when they are activated.The index that already exists on the database is then overwritten. After you havechanged the index design for a table, you must create new index statistics - atleast for the changed indexes.

Only make changes to database indexes at times of low system activity becausethe database locks the database table while the indexes are being created.

82 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 91: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 50: Outdated Table and Index Statistics

To ensure that the cost-based database optimizer functions properly, you mustregularly update the table and index statistics. The database optimizer uses thesestatistics as a basis for selecting the access strategy used to execute a particularSQL statement.

The database administrator must regularly update the table and index statistics.To find out when the last update was performed, choose Tools→ CCMS→ DBadministration→ DBA Planning Calendar→ from the SAP standard menu, oruse Transaction DB13. You must ensure that the last update was not performedmore than a week ago, and that it was performed successfully (refer to the log).

When changing the index design, use the following procedure: First, the ABAPprogrammer designs the database indexes to support SQL statements. In aproduction system or test system, only the database administrator should beresponsible for creating database indexes. Then, the database administrator mustverify whether the programmer�s index design is correct.

When database indexes are created, the table and index statistics must be updatedfor the relevant tables. If the index design is correct, you can transport the databaseindex to the production system at a time of low system activity, and then updatethe table and index statistics in the production system.

2001/Q3 © 2004 SAP AG. All rights reserved. 83

Page 92: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Changing the ABAP Coding

Figure 51: Missing WHERE Conditions (1)

The way in which the database optimizer selects and uses database indexesdepends partly on the WHERE conditions specified in the SQL statement. Theorder of the WHERE conditions in the SQL statement is not important (note thatthis is not the case with the order of the fields in the database index).

The index search string is based on the fields that are specified without gaps andwith an equal sign (=) in the WHERE condition. The index blocks to be checkedare selected using the index search string.

In the first example, a WHERE condition is not specified for BUKRS field (secondfield in primary index). The index search string over the primary index, whichselects index blocks to be checked, is therefore not selective at all.

In the second example, all fields in the index are specified without gaps and withWHERE conditions with an equal sign (=). Therefore, only a few index blocksneed to be checked.

84 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 93: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 52: Missing WHERE Conditions (2)

Incorrect use of the addition CLIENT SPECIFIED can lead to ineffective use ofa database index.

In the top example, the addition CLIENT SPECIFIED blocks the effect of theWHERE condition at the database interface, and thus no WHERE condition forthe field MANDT is stated in the SQL statement. Therefore, all index blocks inthe primary index are checked unnecessarily.

In the second example, the WHERE conditions for the MANDT field areincorporated in the SQL statement. Therefore, the use of an index is effective

2001/Q3 © 2004 SAP AG. All rights reserved. 85

Page 94: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 53: Critical Operators (NOT and <> ) (1)

If fields in the WHERE clause are specified with operators NOT or <>, theseWHERE conditions cannot be used for a search over a database index. You shouldtherefore formulate SQL statements positively wherever possible.

If a positive formulation cannot be used, for example because the IN list wouldbe too long, you should nevertheless specify the WHERE condition with NOT toreduce the amount of data to be transferred.

In both of the examples, an index range scan is performed over the indexconsisting of the MANDT, KUNNR, and AUART fields.

For the search over the index in the first example, only the MANDT and KUNNRfields can be used (the index search string is: �0010000000050__�). In ExplainSQL, you therefore see an index range scan.

However, in the second example, the MANDT, KUNNR, and AUART fields canbe used for the search over the index (index search string: �0010000000050BV�,�0010000000050WV�, and so on). You see a concatenation of index range scansin Explain SQL.

86 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 95: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 54: Critical Operators (BETWEEN, LIKE, > and <) (2)

On ORACLE databases, a WHERE condition with BETWEEN is evaluatedtogether with the costs for reading 5 % of all index blocks and table blocks,regardless of the size of the BETWEEN interval. If the BETWEEN interval issufficiently small, then you can replace WHERE BETWEEN by WHERE IN (), oralternatively by WHERE IN

In the top example, the WHERE condition with BETWEEN cannot be evaluatedon the index. In the second example, however, the WHERE condition with IN isevaluated on the index and the results are concatenated (see Explain SQL).

On ORACLE databases, a WHERE condition with LIKE, >, or < is calculated ascosting 10% of the cost of reading all table blocks and index blocks. Therefore,use LIKE sparingly and only where necessary. Replace SQL statements of thetype SELECT � WHERE LIKE �999� (field is fully specified) by SELECT �WHERE = �999�. You can omit WHERE conditions of the type LIKE �%�.

A field specified with LIKE can narrow the selection of database indexes and beused for a search over a database index only if it does not begin with the wildcardcharacter _ or %. In ABAP, the wildcard + is used for any character, and * isused for any character string. For database accesses, however, the characters_ and % are used.

2001/Q3 © 2004 SAP AG. All rights reserved. 87

Page 96: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 55: Critical Operators (BETWEEN, LIKE, > and <) (3)

WHERE conditions with critical operators that are linked to the WHERE clausewith OR can be particularly problematic. Since BETWEEN is calculated ascosting 5% and LIKE is calculated as costing 10%, the cost-based databaseoptimizer opts for a full table scan after a certain number of correspondingWHERE conditions, instead of using an index.

In the top example, a large number of WHERE conditions with LIKE are linkedby OR operations. The database optimizer calculates the cost of each of theseWHERE conditions as being 10% of the cost of a full table scan. Because the sumof the costs over the WHERE conditions is large, the database optimizer opts fora full table scan.

In the second example, the SQL statement is split into several statements, and anindex range scan is performed for each. The APPENDING TABLE groups theresults together. If you use this procedure, you must also make sure that youeliminate any duplicate entries in the internal table.

88 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 97: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 56: Sort at Database Level or in ABAP?

If you want the results of an SQL statement to be returned in a sorted order, use anORDER BY clause on the database, or use the ABAP statement SORT <internaltable> in the program.

Since the database is a central resource and is therefore not scalable, sort inABAP wherever possible. If the same database index can be used for sortingand selecting data records (according to the WHERE clause), you can also havethe database perform the sort.

In the top example, the primary index is used for selecting data. Sorting accordingto the primary index (ORDER BY PRIMARY KEY) can therefore be performedon the database. If the data is selected using the primary index, the ORDER BYPRIMARY KEY is counterproductive.

In the second and third example, data is also selected using the primary index.However, data is sorted according to a field that is not in the primary index. Forthis reason, data should not be sorted on the database (second example), but inABAP instead (third example).

2001/Q3 © 2004 SAP AG. All rights reserved. 89

Page 98: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 57: Changing the ABAP Coding: Roadmap

Changing the Index Design

� SQL statements from SAP programs:

� Look for SAP Notes� SQL statements from customer-developed programs:

� Avoid indexes on transaction data� Change existing indexes� If necessary, delete existing indexes

� No secondary indexes should exist on SAP Basis tables

� Tables with D010, D020, DD*, or NAST

If you establish that an SAP program triggers an expensive SQL statement, firstsearch for SAP Notes in SAPNet (in a full text search, specify the name of thetable or view, as well as the word performance). If you cannot find an applicableSAP Note, create a problem message in SAPNet.

In your own programs, if you find expensive SQL statements on SAP standardtables with master data or transaction data, avoid creating secondary indexes.Master and transaction data tables usually grow linearly with their indexes.Therefore, a search using a secondary index becomes less effective as time goeson. You should look for alternative methods of access, for example, using indextables or matchcode tables.

Before you create a secondary index to optimize an SQL statement, check whetheryou can adapt a secondary index that already exists, so that it can be used by theSQL statement. Before you change an index, you must perform a selectivity andinterference analysis.

90 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 99: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

In some cases, deleting a secondary index makes sense. For example, if asecondary index is not used, or if a secondary index is a subset of another index,updating it causes unnecessary work for the database. Before you delete an index,you must perform an interference analysis.

Avoid secondary indexes over SAP Basis tables (such as NAST, D010, D020,or tables beginning with DD).

� General rules

� Use disjunct indexes.� Create as few indexes as possible per table (as few as possible but as

many as necessary).� Selection of index fields

� As few fields as possible in index� Fields that are as selective as possible� Selective fields as near to the beginning as possible

� Do not change SAP standard indexes

� Unless recommended by SAP

An index only makes sense if SQL statements that use the index return less than5% of the table records. The index fields must therefore significantly reducethe resulting sets. Otherwise, the database optimizer would perform a full tablescan anyway.

Indexes must not be contained in other indexes (that is, they must be disjunct),because the cost-based database optimizer can also select the index with the upperquantity. In addition, do not create indexes that can be selected accidentally.

To minimize additional work for the database, create as few indexes as possiblefor each table (approximately 5 indexes per table).

As a general rule, an index should consist of a maximum of 4 fields. If too manyfields are specified in an index, additional work is created every time a databaseoperation is performed, and the memory space required grows accordingly.Consequently, the index becomes less effective and the probability of it beingselected decreases.

The selective fields in an index should be as near to the beginning of the index aspossible (see index range scan access strategy ). Selective fields are, for example,document number, material number, and customer number. Unselective fields are,for example, client, company code, header account, and plant.

Do not change SAP standard indexes unless SAP explicitly recommends thatyou do so.

2001/Q3 © 2004 SAP AG. All rights reserved. 91

Page 100: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 58: Selectivity Analysis: Semantic Typing

Before you perform a technical selectivity analysis, be sure you know what thevarious index fields in question mean. You should type index fields accordingto their meaning.

Identifiers: These are particularly selective table fields because they are usuallycharacterized by consecutive numbers (document number, object number, and soon). The numbers are taken from a number range object.

Organizational units: These are fields such as sales organization, company code,or distribution channel. They are often very unselective, and should only be usedin secondary indexes in exceptional circumstances.

Status fields: These can be very selective if, in an SQL statement, values areselected where only a few corresponding data records exist in the table (forexample, open orders, if most of them are complete). Conversely, they can also bevery unselective.

Classifiers: These are fields where typing is performed (for example, sales order,planned order, and production order). In general, classifiers are not selectivebecause few different versions exist.

They are usually distributed relatively evenly.

Date and time: These are often selective, and can be used in a secondary index.

Text fields: These are generally selective, but they are also very long. Theyshould not be used in a secondary index because it would become too wide.

92 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 101: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 59: Selectivity Analysis: Distinct Values

When you know what the index fields mean (that is, their semantics), check howmany distinct values there are for each index field. Distinct values are the numberof different values per field in a particular database table.

The relationship between the total number of data records in a table and thedistinct values per field indicates the selectivity of the index field.

When the table and index statistics update, the distinct values re-calculate. Forindex fields, the number of distinct values can be determined using EXPLAINSQL (DB SQL cache or SQL trace).

For an overview of the distinct values for all fields in a database table, from theSAP standard menu choose Tools→ Administration→ Monitor→ Performance→ Database→ Activity→ Detail analysis menu→ State on disk, or useTransaction DB02. Then choose Detailed analysis. In the dialog box that appears,enter the table name under Object name, and confirm. In the next screen, chooseTable columns.

2001/Q3 © 2004 SAP AG. All rights reserved. 93

Page 102: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 60: Selectivity Analysis: Histograms (1)

The number of data records that are returned for each combination of index fieldsshows how selective an index is if only a few data records are returned for a largenumber of index field combinations, an index is selective.

For an overview of how selective an index is over all index field combinations,a histogram can be calculated. Calculating a histogram is very expensive,because the number of data records returned must be checked for all index fieldcombinations over the whole table.

The histogram on the left shows a selective index for all index field combinations.This index can be created without any problems.

The middle histogram shows that few data records are returned for most indexfield combinations. However, there are also some combinations for which a largenumber of data records are returned. This index can lead to ineffective accesses.

The histogram on the right shows an unselective index. A large number of datarecords are returned for almost all index field combinations. This index shouldnot be created.

94 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 103: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 61: Selectivity Analysis: Histograms (2)

To perform a selectivity analysis, use Transaction DB05. In the initial screen ofDB05, enter a table name, select an analysis for primary key or for specified fields,specify the index fields if applicable, and submit the analysis in background ordialog mode.

In the example, there are 4,506 different values for the USPOB field, 7,172values for the combination of USPOB and GJAHR, 9,195 different values for thecombination of USPOB, GJAHR, and WRTTP, and 16,607 values for all indexfield combinations.

If quotients are calculated from the total number of table records (635,336) and thenumber of distinct values for the index fields (16,607), the results show that anaverage of 30 data records are returned when the index is used.

If the number of distinct values does not increase from one index field to the nextindex field, this index field is not selective. It should be omitted.

In the other columns in the table, you can see how many index field combinationsfall into other categories. For example, between 1 and 10 data records are returnedfor 16,587 index field combinations. For a selective index, this number is similarto the number of distinct values.

2001/Q3 © 2004 SAP AG. All rights reserved. 95

Page 104: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 62: Selectivity Analysis: Histograms (3)

In the example, you can also see that between 10,001 and 100,000 data records arereturned for 8 index field combinations. If an SQL statement with one of thesecombinations is dispatched, the result is an unselective index range scan.

You can decide whether to create the checked secondary index or not, only ifyou follow the logic behind the table.

Remember that a selectivity analysis is an expensive operation that should only beperformed at times of low system activity.

96 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 105: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 63: Selectivity Analysis: Roadmap

� Clarify table usage

� Use the where-used list from ABAP Dictionary� Perform an object-related DB SQL cache analysis before changing the index

design

� DB SQL cache >= restrict to tables and views� Retain all SQL statements with access strategy, where the tables or

views are affected� Changing the Index Design� Reset the DB SQL cache� Perform object-related DB SQL cache analysis after changing index design

� DB SQL cache >= restrict to tables and views� Retain all SQL statements with access strategy, where the tables or

views are affected

Changing the index design of a table in the SAP System can affect SQL statementsother than the one you want to optimize. You must therefore ensure that other SQLstatements are not negatively influenced by a new, changed, or deleted index.

To do this, you must first establish which database views are referenced on thetable. You can find this information in the where-used list in the ABAP Dictionary.

Next, perform an object-related shared SQL area analysis. This means that yourestrict the analysis to the relevant tables or database views, rather than findinginefficient SQL statements in the whole system.

2001/Q3 © 2004 SAP AG. All rights reserved. 97

Page 106: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

After that, change the index design (also activate the indexes, and update thetable and index statistics). Immediately after you have changed the index design,reset the DB SQL cache (use Reset).

Repeat the object-related DB SQL cache analysis approximately two days afterchanging the index design. Because you reset the DB SQL cache, only informationdisplays for SQL statements executed after the index design was changed.

Figure 64: Interference Analysis (2)

To establish in which database views the tables to be analyzed are used, go to theinitial screen of the ABAP Dictionary. To do this, from the SAP standard menuchoose Tools→ ABAP Workbench→ Dictionary, or use Transaction SE12. Enterthe table name in the appropriate field, and choose Where-used list.

In the dialog box, select the Views check box and confirm your selection. A listappears, showing all the database views that use the table. You must perform theobject-related DB SQL cache analysis for the database views and for the table.

98 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 107: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Figure 65: Interference Analysis (3)

To perform an object-related DB SQL cache analysis, first go to the initial screenof the database monitor. To do this, from the SAP standard menu choose Tools→ Administration→ Monitor→ Performance→ Database→ Activity, or useTransaction ST04.

Choose Detail analysis menu→ SQL request. A dialog box appears where youcan limit the SQL statements that display. Delete the entries in the Buffer Gets andDisk Reads fields. In the Table field, replace the * with the name of the table tobe analyzed.

Download to a local file the list of SQL statements contained in the DB SQL cachefor the table. Save the Explain SQL display for each SQL statement. Perform theanalysis in the same way for all database views that use the table.

A few days after you changed the index design, perform the same analysis again,and for each SQL statement compare the values for logical and physical accessesper execution. This second analysis enables you to ensure that none of the SQLstatements analyzed is negatively influenced by the change in index design. Thechange should affect only the SQL statement to be optimized.

2001/Q3 © 2004 SAP AG. All rights reserved. 99

Page 108: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 66: Interference Analysis: Roadmap

Using Database Hints

Figure 67: Database Hints (1)

If you want to force the database optimizer to choose a particular executionpath, use database hints. In SAP Basis releases before 4.5A, database hints canonly be used in the respective database-specific SQL dialects (native SQL in theparentheses EXEC SQL. � ENDEXEC.).

100 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 109: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

As of SAP Basis Release 4.5A, you can use database hints directly from OPENSQL. To do this, add the addition %_HINTS DBMS �DBHINT� to the end of theSQL statement . Under DBMS, enter the applicable database system (for example,ORACLE, INFORMIX). UnderDBHINT, enter the relevant database-specific hint.

If the hint cannot be interpreted by the database system, it is treated as a comment,and does not affect the execution of database statements.

� Disadvantages� Database hints are database-specific

� Database hints force the database optimizer to make a decision, regardless of:

� The SQL statement� The table and index statistics

Supported database systems:

� Oracle (see SAP Note 130480)� MS SQL Server (see SAP Note 133381)� DB2/6000 - UDB (see SAP Note 150037)� Informix (see SAP Note 152913)� DB2/390 (see SAP Note 162034)

A database hint should be incorporated into an SQL statement only as a last option(regardless of whether it is formulated in native SQL or OPEN SQL). Databasehints are database-specific. If you replace the DBMS, you must change all theSQL statements that have database hints (and document your changes).

Database hints ignore the database optimizer�s strategy of dynamically makingselections according to table and index growth and the selectivity of fields.Therefore, an index that is good today could be bad tomorrow.

To find out in which database systems you can formulate database hints fromOPEN SQL, refer to SAP Note 140825. The following SAP Notes containinformation about database hints for each database system:

� 130480 Database hints in Open SQL for Oracle� 133381 Database hints in Open SQL for MS SQL Server� 150037 Database hints in Open SQL for DB6 (DB2 UDB)� 152913 Database Hints in Open SQL for Informix� 162034 DB2/390 Database hints in Open SQL

2001/Q3 © 2004 SAP AG. All rights reserved. 101

Page 110: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 68: Unsuitable Access Path: Roadmap

102 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 111: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

Exercise 2: Optimizing Customer database

Exercise ObjectivesAfter completing this exercise, you will be able to:� Create a list of customer no., cust. name, postal code, and city and use the

correct access path

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters database problems due to suitable and unsuitable access paths. As adeveloper, you have been entrusted with the task of optimizing the ABAP programfor creating a customer database.

Task:1.

In the ABAP Dictionary (Transaction SE11), copy the database tableBC490KKNA1 to the table ZBC490_##_KKNA1. Activate the table. Tofill the table, start the program SAPBC490I_INITIALIZE_KKNA1.

Create a list of customer numbers and the corresponding customer name,postal code, and city. To do this, read table ZBC490_##_KKNA1.

The user should be able to use a selection screen to specify(SELECT-OPTIONS for PSTLZ).

The output list requires the following fields:

Customer number: KUNNRCustomer name: NAME1Postal Code: PSTLZCity: ORTO1

Perform an SQL Trace (ST05) for your program and check the databaseaccess. In particular, check whether the table statistics are outdated, and, ifso, refresh them from the Explain SQL function.

Find out which index is used by the database. If there is no suitable databaseindex for table ZBC490_##_KKNA1, create a new index in the ABAPDictionary. Ensure that it is a selective index. Verify whether using theindex causes a gain in performance.

2001/Q3 © 2004 SAP AG. All rights reserved. 103

Page 112: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Solution 2: Optimizing Customer databaseTask:1.

In the ABAP Dictionary (Transaction SE11), copy the database tableBC490KKNA1 to the table ZBC490_##_KKNA1. Activate the table. Tofill the table, start the program SAPBC490I_INITIALIZE_KKNA1.

Create a list of customer numbers and the corresponding customer name,postal code, and city. To do this, read table ZBC490_##_KKNA1.

The user should be able to use a selection screen to specify(SELECT-OPTIONS for PSTLZ).

The output list requires the following fields:

Customer number: KUNNRCustomer name: NAME1Postal Code: PSTLZCity: ORTO1

Perform an SQL Trace (ST05) for your program and check the databaseaccess. In particular, check whether the table statistics are outdated, and, ifso, refresh them from the Explain SQL function.

Find out which index is used by the database. If there is no suitable databaseindex for table ZBC490_##_KKNA1, create a new index in the ABAPDictionary. Ensure that it is a selective index. Verify whether using theindex causes a gain in performance.

a)

If, after filling the table ZBC490_##_KKNA1,you start the program ZBC4 90_##_KKNA1 while running anSQL Trace, you will see that the cost-based optimizer isnot used (no costs are calculated) since no statistics yetexist for this table. You can create these statistics fromthe Explain SQL function. After tracing the program again,you find that an unsuitable access path is used. The accesspath can be improved by creating a secondary index usingthe fields MANDT and PSTLZ.

*&------------------------------------------------------

Continued on next page

104 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 113: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Unsuitable Access Paths

*& Report SAPBC490S_UNSUITABLE_PATH*&*&------------------------------------------------------*&*&*&------------------------------------------------------

REPORT sapbc490s_unsuitable_path NO STANDARD PAGE HEADINGLINE-SIZE 83.

* Data DeclarationTYPES: BEGIN OF t_kkna1,

kunnr TYPE kkna1-kunnr,name1 TYPE kkna1-name1,pstlz TYPE kkna1-pstlz,ort01 TYPE kkna1-ort01,

END OF t_kkna1.

DATA: wa TYPE t_kkna1,itab TYPE STANDARD TABLE OF t_kkna1.

SELECT-OPTIONS: so_pstlz FOR wa-pstlz.

* Data selectionSELECT kunnr name1 pstlz ort01

FROM kkna1INTO TABLE itabWHERE pstlz IN so_pstlz.

* Data OutputFORMAT COLOR COL_NORMAL.LOOP AT itab INTO wa.ULINE.WRITE: sy-vline, wa-kunnr, 83 sy-vline,sy-vline, wa-name1, 83 sy-vline,

sy-vline, wa-pstlz, 83 sy-vline,sy-vline, wa-ort01, 83 sy-vline.

ULINE.ENDLOOP.

2001/Q3 © 2004 SAP AG. All rights reserved. 105

Page 114: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Lesson Summary

You should now be able to:� Identify database indexes� Identify database joins� Explore possible problems within the system database� Use database hints

106 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 115: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Lesson: Suitable Access Paths

Lesson OverviewThis lesson describes the ways of optimizing SQL statements with a suitableaccess path. It explains the general methods of reducing the number of datarecords to be transferred and accessing individual and several tables. The lessonalso gives an insight into Pooled and Cluster tables, as well as SAP table buffering.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain general methods of reducing the number of data records to betransferred

� Describe ways of accessing individual and several tables� Describe Pooled and Cluster tables� Explain SAP table buffering

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters ABAP performance problems that cause high database load. As adeveloper, you need to resolve this problem by accessing the database usingsuitable access paths.

2001/Q3 © 2004 SAP AG. All rights reserved. 107

Page 116: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

General Methods

Figure 69: Reducing the Records to be Transferred (1)

To reduce the number of data records to be transferred, for each SQL statementyou must specify a WHERE clause that is as selective as possible. A SELECTstatement without a WHERE condition is an indication of a design error in theprogram. You must ensure that the number of selected records remains constantwith time, especially when selecting transaction tables (for example, BKPF,BSEG, COBK, COEP, LIPK, MKPF, VBAK, and VBAP).

In the top example, an SQL statement is specified without a WHERE condition onthe rapidly growing RESB table (the size of RESB can reach several 100 MB).Such statements have a dramatic effect on the overall performance of an SAPSystem. As a general rule, always formulate SQL statements on master data andtransaction data with a selective WHERE condition.

In the second example, a WHERE condition is specified for the MATNR field.This field is selective and therefore suitable for limiting the amount of dataselected. Because material numbers are continually reserved, the number ofrecords selected increases with time and the performance of the SQL statementworsens. Therefore the WHERE clause becomes unstable.

In the third example, an additional WHERE condition is specified for the KZEARfield. The KZEAR field contains the final state of the reservation. Therefore, dueto the additional WHERE condition, only the records from RESB are selectedthat are relevant for the particular material. This means that the WHERE clauseremains stable over time.

108 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 117: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 70: Reducing the Records to be Transferred (2)

To reduce the amount of data to be transferred, do not formulate conditions forselecting data using a CHECK statement within a SELECT... ENDSELECT.Instead, formulate conditions as part of a WHERE clause.

In the example, the records are not checked for validity until they are checked bythe program using a CHECK statement. The system has to read the entire contentsof the VVBAK table, transfer them over the network to the database interface,and then transfer them into ABAP. In the second example, the DBMS only readsthe required data.

Always specify all known conditions in the WHERE clause. Without one, theDBMS cannot use an index to optimize a statement.

To make the reuse of SQL statements possible, and thus to optimally utilizethe DB SQL cache, always adhere to the order of fields specified in the ABAPDictionary when formulating SELECT and WHERE clauses.

2001/Q3 © 2004 SAP AG. All rights reserved. 109

Page 118: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 71: Reducing the Columns to be Transferred

If you use SELECT *, more data than necessary is often transferred from thedatabase server to the application server. If you require the contents of only a fewcolumns, always list the table fields individually in a field list. Creating a field listmakes sense if the number of fields can be greatly reduced.

In the top example, all columns are read and transferred to the application server,although only three columns are required. Therefore, the amount of data to betransferred and the number of fetches increases.

In the second example, the addition INTO CORRESPONDING FIELDS ... copiesthe field contents to target fields with the same name. This type of copying is morework than left-aligned copying to a suitable internal table using INTO TABLE (seethird example) or listing target fields explicitly. The same applies to APPENDINGCORRESPONDING FIELDS and APPENDING TABLE.

If you need different projections on a database table at different places in aprogram, read all the required fields at once from the database, buffer them in aninternal table, and then distribute the data within the program.

110 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 119: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 72: General Methods: Roadmap

Accessing Individual Tables

Figure 73: SELECT FOR ALL ENTRIES (1)

Use SELECT FOR ALL ENTRIES in order to divide SELECT statements intoloops. This variant enables you to create a join between an internal table and adatabase table. In the example, only the records from the KKNA1 table are readthat have customer numbers in the g_itab_vvbak internal table.

2001/Q3 © 2004 SAP AG. All rights reserved. 111

Page 120: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

In connection with the SELECT ... FOR ALL ENTRIES command, the followingproblems occur:

� You cannot have an empty internal driver table. If the driver table is empty,selection is not limited. In particular, the WHERE clause conditions are notevaluated if they do not refer to the internal driver table.

� Duplicate table entries should be deleted from the internal table beforeexecuting the SELECT... FOR ALL ENTRIES. If they are not deleted,identical data is read unnecessarily from the database.

� The rsdb/max_blocking_factor parameter must be implemented according toSAP�s database-specific recommendations.

Figure 74: SELECT FOR ALL ENTRIES (2)

The SELECT ... SELECT FOR ALL ENTRIES addition ensures that SQLstatements are divided into several SELECT statements by the database interface.The individual SELECT statements are processed on the database and the resultsare buffered in the database interface. The database interface eliminates duplicatedata records from the results set and transfers the results set to the ABAP program.

Each SELECT statement processed on the database is executed as a concatenationof individual accesses (for example, index range scans or index unique scans).Concatenation is performed over the entries in the internal driver table. Sincethe SELECT ... FOR ALL ENTRIES may be very complex, it should not becombined with RANGES tables.

The implementation of the WHERE clause for individual SELECT statementsdepends on the database and is realized by the database interface.

112 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 121: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

The rsdb/max_blocking_factor profile parameter controls the maximum numberof individual WHERE conditions that can be concatenated. SAP pre-configuresthis parameter according to the database. For Oracle the setting is 15.

Figure 75: RANGES Tables

You can use RANGES tables in ABAP. You can define RANGES tables usingthe ABAP statements SELECT-OPTIONS and RANGES. These two statementsimplicitly define an internal table with the SIGN, OPTION , LOW, and HIGHfields (see SAP documentation). The end user at the selection screen dynamicallyfills a RANGES table defined with SELECT OPTION. In contrast, a RANGEStable defined with RANGES is filled by the program.

The database interface converts the rows in a RANGES table so that they can beread by the DBMS, and links them with OR. The SQL statement produced isthen transferred to the database.

The RANGES table can contain rows with complex expressions (for example, BT=> BETWEEN, CP => LIKE). The SQL statement that results from a RANGEStable can therefore be complex and difficult for the DBMS to process.

If the program determines how they are filled, you must limit the number of entries.If the RANGES table is too large, a complex database statement is generated whenthe OR or IN list is evaluated. This statement may take a long time to be evaluatedon the database. The maximum possible length of the database statement dependson the database (for example, with the ORACLE 32 bit version, the maximum is32 KB). If the maximum length is exceeded, an ABAP dump may be generated.

2001/Q3 © 2004 SAP AG. All rights reserved. 113

Page 122: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 76: Aggregate Functions

You can use aggregate functions (COUNT, SUM, MAX, MIN, and AVG) toperform calculations using the DBMS. Only use aggregate functions if theysignificantly reduce the quantity of data records to be transferred.

In the top example, an aggregation is performed in ABAP using control levelprocessing. A data record must be transferred for each document item that fulfillsthe condition in the WHERE clause. However, in the second example, only onedata record needs to be transferred for each document header.

Aggregate functions are usually used with a GROUP BY clause. SQL statementsthat contain aggregate functions bypass SAP table buffers. (Note that this can bea disadvantage if tables are buffered).

Field values are processed differently, depending on whether they are in ABAP orat database level. The database uses a different method compared to ABAP forrounding data (for example, when converting F to I). The database recognizes thevalue NULL. In contrast, ABAP recognizes initial values.

For the aggregate function AVG, use data type F (number with floating point) forthe target field. For the aggregate function SUM, make the data type of the targetfield longer than the data type of the source field, to allow for overflow.

114 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 123: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 77: HAVING Clause

With a SELECT statement, to apply a logical condition to the groups defined inthe GROUP BY clause, use HAVING. The database determines the resultingquantity, that is, the data quantity to be transferred depends on the selectivityof the HAVING clause.

Using HAVING clauses is similar to using aggregate functions. HAVING clausescreate an extra load on the database. Therefore, only use HAVING clauses ifthey significantly reduce the quantity of data records to be transferred. Beforeyou use a HAVING clause, check whether the condition can be specified in theSELECT clause instead.

In the examples above, the goal is to return the largest document number and theaverage target quantity per material number. The average target quantity should bewithin a certain range.

In the top example, the target quantity range is read within the SELECT ..ENDSELECT. Therefore, all data records that fulfill the conditions in the WHEREand GROUP BY clauses are transferred.

In the second example, the target quantity is queried using the HAVING clause.Only the data records that fulfill the conditions in the WHERE, GROUP BY,and HAVING clauses are transferred.

2001/Q3 © 2004 SAP AG. All rights reserved. 115

Page 124: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 78: ARRAY FETCH

For SELECT .. ENDSELECT, and ARRAY FETCH, the same number of datarecords must be transferred from the database server to the application server.Since data records are transferred in 32 KB blocks, the transfer load (that is, thenumber of fetches) is the same for both variants.

However, an ARRAY FETCH is preferable to a SELECT ... ENDSELECT loop,because data records are transferred per record from the database interface tothe ABAP program in a SELECT .. ENDSELECT. In contrast, in an ARRAYFETCH, the data records are transferred to the ABAP program in a block.

116 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 125: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 79: UP TO n ROWS

There are two ways to read a fixed number of data records. You can transfer thedata records to the application server, and then, in the SELECT... ENDSELECT,drop those records that were read too many times. However, using SELECT...UPTO n ROWS is preferable, because only the requested number of data records aretransferred from the database to the application.

In the top example, the system field SY-DBCNT is read within a SELECT...ENDSELECT, and cancelled after a certain number of data records has been read.The last of the 32 KB blocks is transferred in full, even though only part of theblock may be required.

In the second version, the UP TO n ROWS addition ensures that only the requireddata quantity is read from the database and transferred to the database interface.

2001/Q3 © 2004 SAP AG. All rights reserved. 117

Page 126: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 80: UPDATE ... SET

In an UPDATE, only the field contents that have actually been changed shouldbe updated to the database. With UPDATE ... SET <f> = ... , these fields arespecified. In the WHERE condition, you can limit the table rows to be changed.

In the examples above, the goal is to increase field ZMENG by a constant amountfor a range of document numbers.

In the top example, the data records are read from the database and transferredto the application server. On the application server, they are changed and thentransferred back to the database.

In the second example, there is no data transfer. Only the UPDATE request mustbe transferred, since on the right-hand side of the equals sign a database fieldand not a program-internal field is specified, and the calculation is performedby the database.

You can use the UPDATE ... SET statement for multiple fields of a database table.

118 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 127: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 81: Creating, Changing, and Deleting Mass Data

Always use mass data when inserting data into database tables. To prevent aruntime error when inserting duplicate entries using INSERT, use the additionACCEPTING DUPLICATE KEYS (existing data records are not changed, andSY-SUBRC is set).

In the examples above, the goal is to insert a certain number of entries into adatabase table. In the first example this is done record by record; in the secondexample it is done with mass data.

For operations to change (UPDATE, MODIFY) or delete (DELETE), also usemass data operations (UPDATE dbtab FROM TABLE itab, MODIFY dbtabFROM TABLE itab, DELETE FROM TABLE itab). For MODIFY .. .. FROMTABLE itab, there is no performance improvement (since transfer is record byrecord).

To delete several entries from database tables, you can also use DELETE FROMdbtab WHERE .. . A WHERE clause can only be specified in association withUPDATE dbtab, SET, and DELETE.

You should not use CALL FUNCTION ... IN UPDATE TASK within LOOPs withregard to asynchronous updates. Instead, gather the data records to be changed inan internal table and then update them. Otherwise, an extra load is created not onlyfor the application tables but also for the update tables (inserting and deleting).

2001/Q3 © 2004 SAP AG. All rights reserved. 119

Page 128: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 82: Accessing Individual Tables: Roadmap

Accessing Several Tables

Figure 83: INNER and OUTER JOIN Logic

To read data distributed over various tables, you must create a Join betweenfunctionally dependent tables. The database-logical operator used to do this iscalled the Join operator. INNER JOINs and LEFT OUTER JOINs can be derivedfrom the resulting set.

120 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 129: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

An INNER JOIN produces a result set that contains only the records of the outertable whose records in the inner table match the Join conditions (shown in theexample above left).

A LEFT OUTER JOIN produces a resulting set containing all data records fromthe outer table, regardless of whether matching records exist in the inner table. Ifthere are no matching data records in the inner table, NULL values are returnedfor the fields in the inner table (see example above right).

Tables that are linked with a Join are called basis tables. Using the results of a Join,you can perform a projection (column selection) or a selection (row selection).

Figure 84: Implementation in ABAP

You can implement INNER JOINs and LEFT OUTER JOINs in various ways.One method is to read the data records from the outer table in a SELECT loop.Within the loop, a further SELECT statement is nested, in which the informationfrom the inner table is read. Depending on how the data records read aresubsequently processed, you can implement an INNER JOIN or an OUTER JOIN.

Since nested SELECT statements have some disadvantages, you can replace themby reading the data records to an internal table, and then using a SELECT FORALL ENTRIES. This method enables you to partly remove loops from nestedSELECT statements. However, this solution is only suitable for small quantitiesof data, and can cause problems. An INNER JOIN or a LEFT OUTER JOIN canalso be implemented.

A standard method of retrieving data from an SAP System is by using logicaldatabases. Generally, this type of access uses LEFT OUTER JOIN logic.

2001/Q3 © 2004 SAP AG. All rights reserved. 121

Page 130: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

The most flexible and often the most effective way to perform Joins is at databaselevel. In OPEN SQL, you can use subqueries, database views, and ABAP JOINs.Only an INNER JOIN implements a database view. ABAP JOINs are used toperform both INNER JOINs and LEFT OUTER JOINs.

Figure 85: Nested SELECTs

In the example, nested SELECTs are used to perform an INNER JOIN. FromExplain SQL, you can see that one data record from the inner table KKNA1 isread for each data record in the outer table VVBAK. Access to VVBAK and toKKNA1 is performed using a primary index.

ABAP distinguishes between INNER JOIN and LEFT OUTER JOIN byperforming the APPEND to the target table in the inner or outer SELECT ..ENDSELECT.

The major disadvantage of nested SELECTs is that they are expensive to transfer.As shown in the example, for every data record of the outer table VVBAK, onedata record is read from the inner table KKNA1. Therefore, the database operationREOPEN must be performed separately for each SELECT on table KKNA1,

122 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 131: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

and only one data record is transferred from KKNA1 each time. This causesan unnecessarily high number of small fetches (that is, 32 KB blocks that arenot completely filled).

� Inefficient transfer

� Data records of the inner table are transferred row-by-row to thedriving table

� Lots of small fetches, instead of fewer and more compact fetches� Multiple SELECTs on individual values

� The data records of the inner table are read multiply (the WHEREclause working between the inner table and the driving table uses a keyfield and a non-key field)

� Defined access sequence

� Whether a table is an inner or outer table is defined in coding� Dynamic WHERE conditions are ignored

Nested SELECTs cause an unnecessarily high transfer load.

A further disadvantage of nested SELECTs is that identical SQL statementsexecute more than once. When WHERE clauses associate a non-key fieldof the outer table with a key field of the inner table, this generally results invalue-identical SELECTs, for example, when customer data is read for a salesdocument. As a general rule, one customer has several sales and distributiondocuments. Identical customer data is read multiple times from the inner table.

The third disadvantage of nested SELECTs is that the order of access is fixed incoding. That is, a table is defined as either an inner or an outer table. The effectsare particularly negative if you use dynamic WHERE conditions in a SELECTstatement (for example, SELECT-OPTIONS, PARAMETERS) that is suppliedwith user entries at runtime. The user entry (and therefore the WHERE condition)often determines which table the JOIN uses for access. If the Join is implementedusing database views or ABAP JOINs, the database optimizer determines theorder of access.

Nested SELECTs and SELECT FOR ALL ENTRIES can be satisfied by the tablebuffer, but Joins processed at database level always bypass table buffering. Thiscan make Joins using nested SELECTs or SELECT .. FOR ALL ENTRIES thebetter alternative.

2001/Q3 © 2004 SAP AG. All rights reserved. 123

Page 132: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 86: Database View

A database view is created in the ABAP Dictionary as a Dictionary object. Theview is generated in the database after being activated in the ABAP Dictionary.However, the database view data is stored in the tables used to define the databaseview. Therefore, defining a database view does not cause extra load (for example,due to redundant data retention). When you define a database view, you canperform a column selection (projection) and a row selection (selection), as well asa Join condition.

You cannot define an index using a database view. Instead, when an SQLstatement is processed for a database view, the indexes from the relevant tablesare usually used. An SQL statement using a database view is always processed asan INNER JOIN.

Unlike an ABAP JOIN, a database view can easily be reused. If various SQLstatements use one database view, the DB SQL cache performs efficiently.

An SQL statement on a database view always bypasses SAP table buffering.However, as of Release 4.0, contents of database views can be buffered on theapplication server.

124 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 133: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 87: ABAP INNER JOIN

In an ABAP JOIN, database tables are Joined using the ON clause. You can usealiases for the relevant tables, as shown in the example above. You can alsospecify field lists (projection) and WHERE clauses (selection) for ABAP JOINs.

Ensure that you clearly allocate the field name in the SELECT clause, in the ONclause, and in the WHERE clause to a table or to an alias for a table. If the databasedoes not support Standard SQL, the ON conditions convert to WHERE conditions.

ABAP JOINs also bypass SAP table buffering. To implement a JOIN on abuffered table, it may be best to define a buffered database view on the table.

If you use parentheses, an ABAP JOIN can link more than two tables. Do not Jointoo many tables because this increases the complexity of processing the SQLstatement on the database.

In the example above, an INNER JOIN is implemented. The resulting set (witha blue frame) contains only the data records with entries for KUNNR field inboth VVBAK and KKNA1.

2001/Q3 © 2004 SAP AG. All rights reserved. 125

Page 134: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 88: FOR ALL ENTRIES Over TWO Database Tables

SELECT ... FOR ALL ENTRIES was included in OPEN SQL syntax at a timewhen it was not possible to create joins at database level (that is, creating joinsat database level was not supported by all DBMS approved for use with SAPSystems). The join between inner and outer database table is created in ABAP.

By replacing nested SELECTs with SELECT FOR ALL ENTRIES, you onlypartially avoid nesting and its associated problems. You actually bundle the innerSELECT statements together to form packages of 15 single statements. You thusreduce the amount of data to be transferred, and avoid identical SQL statements.For nested SELECTs, the order of access is determined in the ABAP coding.

If you use SELECT...FOR ALL ENTRIES, you must ensure that the drivertable is not empty and does not contain duplicate entries, and that the parameterrsdb/max_blocking_factor is correctly set.

For SELECT...FOR ALL ENTRIES, ABAP determines whether an INNER orOUTER JOIN is used. If you want to read large quantities of data, use SELECTFOR ALL ENTRIES in exceptional cases only.

126 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 135: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 89: Subquery

A subquery is contained within a SELECT, UPDATE, or DELETE statement. Asubquery is formulated in the WHERE or HAVING clause, to check whether datafrom various database tables or views fulfills certain conditions.

A SELECT statement with a subquery has a more restricted syntax than a SELECTstatement without a subquery: SELECT...FROM dbtab [WHERE ...] [GROUPBY ...] [HAVING ...]. If the subquery returns one value, standard relationaloperators can be used, with the exception of LIKE and BETWEEN.

If a subquery is used with a relational operator rather than with EXISTS, only onecolumn can be specified in the SELECT clause of the subquery. This can be a fieldfrom the database table, or an aggregate expression.

In the example above, the goal is for the subquery to return several rows with onevalue each. If you want to compare all values returned, use IN.

Subqueries in which fields from the main query are used in the WHERE clause arecalled correlated subqueries. If several subqueries are nested, a subquery can useall fields from the subqueries above it in the hierarchy.

Always use positive formulations for subqueries if possible. Negative formulationscan cause nonperforming accesses to the database if there is no suitable index.

2001/Q3 © 2004 SAP AG. All rights reserved. 127

Page 136: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 90: ABAP OUTER JOIN

A Join with LEFT OUTER logic can only be created using an ABAP JOIN(database views always implement an INNER JOIN).

Since some DBMSs approved by SAP do not support the standard syntax for ONconditions, syntax restrictions were made to allow only those Joins that producethe same results on all database systems.

To the right of the Join operator, there must be a table or a view (not anotherJoin expression)

Only AND is possible as a logical operator in an ON condition

Every comparison in an ON condition must contain a field from the table onthe right

No fields from the table on the right are permitted in the WHERE condition ofthe LEFT OUTER JOIN

128 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 137: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

In the example above, a LEFT OUTER JOIN is implemented. Therefore, theresulting set (with a blue frame) also contains the data records from VVBAK thatdo not have entries for KUNNR field in KKNA1.

� Possible access strategies:

� Nested loop� Sort merge join

� Database optimizer determines order of access� Access to outer table should be as selective as possible (selective WHERE

conditions)� For each data record in the outer table, as few records as possible should

exist in the inner table (selective JOIN conditions)

The following statements refer to database views and ABAP JOINs.A nested loopis the access strategy generally used for Joins at database level. In some cases,you can also use a sort merge join . The database optimizer dynamically selectsthe access strategy.

Unlike nested SELECTs, SELECT FOR ALL ENTRIES, and subqueries, thedatabase optimizer dynamically determines the order of access. The criterion forthe order of access is to have as few data blocks to be read as possible. There is noway to control this from the application program (apart from using database hints).

To make access to the outer table as selective as possible, formulate an appropriateWHERE clause. Then, fewer data records need to be read from the outer table,and consequently fewer data records also need to be read from the inner table.

The fields used for creating a Join (Join condition) should also be as selective aspossible. The goal is to have as few data records as possible returned from theinner table per data record from the outer table (if possible, just one using indexunique scan).

There should be a database index at least on the inner table for the fields in theJOIN conditions.

2001/Q3 © 2004 SAP AG. All rights reserved. 129

Page 138: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 91: Using Logical Databases

The structure of a logical database determines the node hierarchy, and thus theorder in which the nodes are read. The read depth depends on the GET eventsspecified in the program. The logical database reads all nodes on the direct accesspath, until the deepest GET event.

GET events are processed several times in the program, so a GET statement is likeloop processing. Consequently, programming a SELECT statement within a GETevent can cause problems, this is equivalent to a nested SELECT.

Because the order of reads is predetermined, only program a GET event thatrefers to a node lower down in the hierarchy if the data above it is also required.The logical database reads the key fields of these nodes as well (VBAK, in theexample above). In this situation, do not use the logical database. Program theSELECT statements yourself.

If you do not require all fields in your program, and particularly if the fields inyour table are wide, always use a FIELDS addition when you formulate a GETstatement. The statement GET <node> FIELDS <f1> <f2>.. corresponds to aSELECT <f1> >f2> ... and should be evaluated similarly.

130 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 139: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 92: Accessing Several Tables: Roadmap

Introducing Pooled and Cluster Tables

Figure 93: Pooled and Cluster Tables: Introduction

In addition to transparent tables, which are defined in the same way in the ABAPDictionary and at database level, the SAP System also has pooled and clustertables.

2001/Q3 © 2004 SAP AG. All rights reserved. 131

Page 140: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Pooled and cluster tables group several tables that are logically defined in theABAP Dictionary together in a physical database table.

� Advantages� Fewer tables and table fields

� Simplified administration

� Data compression

� Less memory space� Less network load

� For cluster tables

� Fewer database accesses� Disadvantages� Limitations on database functionalities

� No native SQL� No views or ABAP JOINs� No secondary indexes� No GROUP BY, ORDER BY, ... clauses

� No table appends� For cluster tables

� Limited selection on cluster key fields� For pooled tables

� Longer keys than necessary

Pooled and cluster tables have the advantage that their data is stored in compressedform on the database. Required memory space and network load are thus reduced.

Grouping tables together in table pools or table clusters reduces the number oftables, and compression reduces the number of fields on the database. The resultis that fewer different SQL statements are executed.

Pooled and cluster tables are not created as separate tables on the database.Administration is therefore made easier. For cluster tables, functionally dependentdata is read together, thus reducing the number of database accesses.

The disadvantage of pooled and cluster tables is that database functionality islimited. You cannot create an index for non-key fields. You can create eitherprimary indexes or indexes for a subset of the key fields. In addition, you cannotuse database views, ABAP JOINS, or table appends. The data in pooled or clustertables can only be accessed using OPEN SQL. It cannot be accessed using nativeSQL.

132 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 141: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

For pooled tables, only the WHERE conditions for key fields are transferred tothe database. For cluster tables, only the WHERE conditions for the fields in thecluster key (subset of the key fields) are transferred to the database. ORDER BYor GROUP BY clauses for non-key fields are not transferred. Longer keys arerequired for pooled tables than is semantically necessary.

Figure 94: Cluster Tables

In cluster tables, functionally dependent data that is distributed over several tablesis grouped together in one database table. The intersection of the key fields in thecluster table forms the key of the table cluster (cluster key).

The data that depends on a cluster key is stored in the VARDATA field of the tablecluster. If the VARDATA field is not large enough to store all dependent data,the database interface creates an overflow record. The PAGNO field ensuresuniqueness within the table cluster.

The database interface compresses the contents of the VARDATA field. TheVARDATA field contains a description of how to compress its data. TheTIMESTAMP and PAGELG fields contain administrative information.

2001/Q3 © 2004 SAP AG. All rights reserved. 133

Page 142: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 95: Selective Access to Cluster Tables

In the example, data is read from the BSEG cluster table. The SQL statement istransferred to the database interface and converted into an SQL statement for theRFBLG table cluster. The SQL statement returns all corresponding data records(for example, for BUKRS = �0001� and BELNR = �0000000022�) from the cluster,regardless of whether the data records are logically included in BSEG or in one ofthe other tables from RFBLG.

Because some of the fields in the cluster key are specified in the WHERE clause,the corresponding WHERE conditions transfer to the database. The databaseinterface also incorporates the WHERE clause for the MANDT field and theORDER BY clause for the fields in the cluster key.

When accessing cluster tables, because only the primary index can be used, ensurethat WHERE clauses are specified starting at the left and continuing without anygaps to a selective field.

In the example above, if the WHERE condition for the field BUKRS was omitted,the index search string would have the form �001____0000000022�. In this case,when the SQL statement was processed, many index blocks would be read (seeunit Unsuitable Access Path = Unselective Index Range Scan).

134 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 143: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 96: Unselective Access on Cluster Tables

In the top example, the BSEG cluster table is accessed with a WHERE conditionfor the KUNNR field, which is in the compressed VARDATA field. The databaseinterface does not transfer the WHERE condition for the field KUNNR to thedatabase.

Correspondingly, all data records from the logon client are read from the tablecluster RFBLG table cluster (client range scan). This means that data records arealso read that are not logically included in BSEG. The database interface evaluatesthe WHERE clause for the KUNNR field.

Alternatively, you can access the data by using secondary indexes. Secondaryindexes are transparent tables, where data can be redundantly stored for easieraccess. In the example, the required information can be obtained from the BSIDtransparent table (secondary index for accounts receivable).

If SAP does not provide an alternative access path, you can consider removingthe table from the table cluster. However, you must consult SAP (SAP Note orsupport) before doing this.

2001/Q3 © 2004 SAP AG. All rights reserved. 135

Page 144: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 97: Pooled Tables

A table pool stores data records from tables defined in the ABAP Dictionary. Thetables do not depend on each other. Small SAP tables are grouped together toform a database table.

The example shows that TABA and TABB have no key fields in common. Thedata records from TABA and TABB are nevertheless found in TABAB.

The key for a data record in the TABAB table pool consists of two fields,TABNAME and VARKEY. The TABNAME field adopts the name of the pooledtable. The VARKEY field consists of the concatenation of the key fields in thepooled table. Therefore, the key fields in a pooled table must be type C.

The database interface stores the non-key fields of the pooled tables in theVARDATA field. They are stored unstructured in compressed form. The DATALNfield stores the length of the VARDATA field.

136 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 145: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 98: Selective Access on Pooled Tables

In the example above, data is read from the AA005 pooled table. The SQLstatement is transferred to the database interface and converted into an SQLstatement for the KAPOL table pool.

The WHERE conditions specified in the WHERE clause of the SQL statementrefer to key fields in the AA005 table and are therefore all transferred to thedatabase in VARKEY field. The database interface incorporates the ORDER BYclause for TABNAME and VARKEY fields (key fields in the table pool).

Figure 99: Unselective Access on Pooled Tables

2001/Q3 © 2004 SAP AG. All rights reserved. 137

Page 146: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

SQL statements for pooled tables must have WHERE conditions specifyingthe key fields with an equals sign. The key fields must be specified startingwith the key field that is left-most in the table. In addition, any key fieldsspecified must be strictly contiguous, that is, no gaps should occur in thesequence of specified fields. In the top example, a WHERE condition is notspecified for KUNNR field. The database therefore uses the index search string:�AA005CSSAPZ000101___________01000000000000000027�.

The database uses the partial string �AA005CSSAPZ000101%�. This means thattoo many data blocks are read (see unit Unsuitable Access Path => UnselectiveIndex Range Scan).

To solve this problem, first check whether you can specify the missing WHEREconditions. If this is not possible, check whether changes can be made to SAPtable buffering (see topics at end of this unit).

If you cannot change SAP table buffering, you can remove the table from the tablepool and convert it to a transparent table. Then create a secondary index for thespecified fields to enable efficient access from the database.

Figure 100: Pooled and Cluster Tables: Roadmap

138 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 147: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Introducing SAP Table Buffering

Figure 101: SAP Table Buffering: Introduction (1)

The SAP System is scalable at application server level. This means that you canadd more application servers to an SAP System. The database, as the centraldata repository, is not scalable. That is, there can be only one database for eachSAP System.

Table contents, repository objects, ABAP Dictionary objects, and so on, are datarecords on the database. Every time these objects are called, they must be readfrom the database and transferred to the application server. To avoid this, theobjects are stored temporarily in the shared memory of the application serversin various buffer areas, for example:

� Table buffer (single-record buffer, generic buffer)� Repository buffer� Dictionary buffer� Number range buffer� Roll and paging buffers

2001/Q3 © 2004 SAP AG. All rights reserved. 139

Page 148: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 102: SAP Table Buffering: Introduction (2)

SAP table buffering buffers table contents on the application server to eliminatethe need for database accesses and thereby reduce the load on database resources(for example, CPU load and main memory).

There are two types of buffer: single-record buffer (technical name TABLP) andgeneric table buffer (technical name TABL). The single-record buffer containsdata records from tables with single-record buffering. The generic table buffercontains data records from generically buffered or fully buffered tables.

Accesses to buffered data records take approximately 0.2 - 6 ms, whereas between8 and 600 ms are required to read the data from the database. Using buffersreduces the waiting times for SAP work processes on the application server. Thus,the total system load decreases.

Data records are sorted according to the primary index and stored in the tablebuffers. You cannot access buffered tables with secondary indexes. You cannotuse SAP table buffering and index support for SQL statements in parallel. Youcan only use SAP table buffering as an alternative.

140 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 149: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 103: Types of Buffering

Full buffering: The first time the table is accessed, the contents of the entire tableloads into the table buffer (generic table buffer). Any further accesses to the tablecan be made through the table buffer.

Generic buffering: To generically buffer a table, you must first define the genericarea. The generic area is the first n key fields in the table. If an SQL statementwith a specific instance of the generic area (for example, SELECT * FROMTAB1 WHERE KEY1 = �002� or SELECT * FROM TAB2 WHERE KEY1 =�002� AND KEY2 IN (�A�,�C�) ) is executed for a generically buffered table, thecorresponding data records are loaded into the table buffer. Any further accesseswith the same specific instances can be made through the table buffer.

Single record buffering: Only single data records are read from the database andloaded into the table buffer (single-record buffer).

All types of buffering can be understood as variants of generic buffering withn key fields:

� Full buffering: n = 0� Generic buffering: 0 < n < number of key fields� Single-record buffering: n = number of key fields

2001/Q3 © 2004 SAP AG. All rights reserved. 141

Page 150: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 104: Buffer Synchronization

In the first step of a read access to a buffered table, the relevant data recordschange on the database. The data records are then changed (work area mode) orinvalidated (set mode) in the table buffer of the local SAP System instance (inthe example, application server A). The table buffers of all other SAP Systeminstances (in the example, application server B) are not changed.

In the second step, the local database interface (in the example, application serverA) passes on the changes to the other application server by making the appropriateentry in DDLOG database table. The table buffers of all other SAP Systeminstances have not yet been updated.

In the third step, the database interfaces of the SAP System instances call thebuffer synchronization (every 1 to 2 minutes, controlled by profile parameters).This is done by sending a SELECT statement to table DDLOG. If the data recordsreturned from DDLOG indicate that changes have been made to buffered tables,the data in the table buffer of the non-local SAP System instances are invalidatedaccordingly. SQL statements on invalidated data are then provided with datadirectly from the database. The table buffers of non-local SAP System instancesreload.

142 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 151: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Note that, in the time between two buffer synchronizations, SQL statements maybe supplied with obsolete data from the table buffers.

� Single record processing

� Full buffering: All records� Generic buffering: Generic area� Single record buffering: currently accessed data record

� Mass processing:

� All data records, independent of the type of buffering

Work area mode means that changes on the database are made by single recordaccessing. Single record accessing is performed using the ABAP statementsUPDATE/INSERT/MODIFY/DELETE dbtab (FROM wa) or INSERT dbtabVALUES wa.

You can also change a database table in set mode, which means that you use massprocessing. To make database changes using mass processing, formulate theABAP statements UPDATE/INSERT/MODIFY/DELETE dbtab FROM itab,UPDATE dbtab SET field = value WHERE field = condition or DELETE dbtabWHERE field = condition.

With fully buffered tables, all records are invalidated by database changes.

With generically buffered tables in work area mode, the records are invalidatedthat have the same specific instance in the generic area as the fields in the workarea of the SQL statement executed. If a generically buffered table is accessed inset mode, all data records are invalidated.

When a data record with single record buffering is changed in set mode, only thechanged single record is invalidated. In set mode, the whole table with singlerecord buffering is invalidated by database changes.

2001/Q3 © 2004 SAP AG. All rights reserved. 143

Page 152: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

The degree of invalidation corresponds to the degree to which the table buffersare filled.

� Native SQL� Subqueries, ABAP joins� SELECT ... BYPASSING BUFFER� SELECT FOR UPDATE� Aggregate functions (COUNT, MIN, MAX, SUM, and AVG)� SELECT DISTINCT� WHERE clause with �IS NULL�� ORDER BY, GROUP BY (HAVING)� For single-record buffered tables:

� All SQL statements except SELECT SINGLE ...� For generically buffered tables:

� All SQL statements except SELECT * .. with WHERE clause in theform Field = value for all fields in the generic area

Some SQL statements cannot be evaluated on table buffers. Instead, they aretransferred directly to the database from the database interface.

If you want an SQL statement to be executed at database level (for example, toensure that current data is read), use the addition BYPASSING BUFFER. SQLstatements on database Joins (database views with more than one table, ABAPJOINs, and subqueries) are always executed at database level, even if all tablesinvolved are buffered.

Database locks are set by SELECT FOR UPDATE. They must therefore beperformed at database level. Other statements that can only be executed atdatabase level include: SELECT statements with aggregate functions, SELECTDISTINCT, SELECT statements with WHERE conditions containing the operatorIS NULL, ORDER BY (except ORDER BY PRIMARY KEY), and GROUP BY(with HAVING, if applicable).

A table with single record buffering is filled and invalidated record by record.You can only read data records of a table with single record buffering from thetable buffer by using single record accesses (SELECT SINGLE with all key fieldentries).

The degree to which a generically buffered table is filled and invalidated dependson the generic area. If you want to read records of generically buffered tables fromthe table buffer, you must specify WHERE conditions with an equal sign (=) forall fields in the generic area.

144 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 153: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 105: SQL Statements that Bypass the Buffer (2)

In the first example, TCURR table is generically buffered with one key field.The generic area for the client-dependent table TCURR consists of the MANDTkey field.

In the example of the SQL statement on the left, the incorporation of a WHEREcondition is suppressed for the client by the addition CLIENT SPECIFIED. Thegeneric area is thus not specified, and the access bypasses the buffer. However, theSQL statement in the example on the right is read on the table buffer.

In the second example, T100 table has single record buffering. In the SQLstatements on the left and on the right, all key fields in the WHERE clause arespecified with �=�. In the example on the left, T100 is accessed using SELECT.The table contents are therefore returned from the database, not from the tablebuffers. In the example on the right, T100 is accessed using SELECT SINGLE.The table contents are returned from the table buffers.

� Technical criteria

� Small, usually < 1 MB� Often read, but seldom changed� Temporary data inconsistency acceptable� Access mainly from key fields

� Note:

� Buffer tables < 10 MB in exceptional cases only� Table buffers cannot be accessed via secondary indexes� Check available memory space before buffering more tables

2001/Q3 © 2004 SAP AG. All rights reserved. 145

Page 154: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

The records of the buffered tables are retained in the shared memory of therelevant application server, and are redundant. You should therefore only buffersmall tables. Only buffer tables larger than 10 MB in exceptional cases.

To keep the number of invalidations as low as possible, and thus keep the bufferloading process as short as possible, only buffer tables that have predominantlyread accesses (changes < 1% of read accesses).

Directly after changes to buffered tables, the table buffers of the non-local SAPR/3 Enterprise instances are not up-to-date (see Buffer Synchronization topic inthis unit). During this time, data may be read inconsistently.

Data records from buffered tables are stored and sorted according to primarykeys. You should therefore access them via key fields. Secondary indexes cannotbe used.

Before you decide to buffer tables, contact your SAP R/3 Enterprise Systemadministrator to ensure that there is enough space in the shared memory (singlerecord buffer: approximately 40 MB, generic table buffer: approximately 80 MB).If there is not enough space, displacement occurs in the table buffers, making tablebuffering counterproductive.

Before changing buffering settings for SAP standard tables, look for relevantSAP R/3 Enterprise Notes in SAPNet. To perform the changes, you need an SAPmodification key.

� Never buffer master and transaction data

� Tables too big� Tables changed frequently

� Avoid buffering master data

� Tables too big� Different access paths to data

� Buffer Customizing data

� Tables small� Few changes to tables

When you determine the buffering settings for a table, you must consider semanticcriteria as well as technical criteria.

Never buffer transaction data (for example, VBAK, LIKP, MKPF, or RESB).These tables can grow to several gigabytes. In addition, transaction data ischanged frequently.

Master data (for example, MARA, KNA1, or LFA1) does not grow as fast astransaction data. However, these tables can grow to several 100 megabytes. Alsoavoid buffering master data because it can be accessed by a number of different

146 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 155: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

access paths (for example, using search help). Access paths are usually supportedby secondary indexes. The technical criteria for table buffering are thereforenot met.

Customizing tables (for example, T000, T001, T001W, or TVKO) are usuallysmall and are seldom changed after production startup. They are therefore suitablefor buffering.

Figure 106: SAP Table Buffering: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 147

Page 156: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Other Methods for Suitable Access

Figure 107: Buffering in the Program

The best way to reduce the load on the database is to avoid database accesses. Youcan do this by buffering read table contents in an internal table (preferably of thetype SORTED or HASHED).

In the example above, the goal is to read data from database KKNA1 table(customer master data) in a SELECT ? ENDSELECT over VVBAK table (salesdocument headers). This can be achieved by a SELECT SINGLE or by a readroutine.

Using SELECT SINGLE would mean executing identical SQL statements.Therefore, you should read the KKNA1 records in a read routine. In the example,the read table contents from KKNA1 are buffered in an internal table. Beforethe database is accessed, the relevant table entry is checked to establish whetherit has already been read. If no corresponding entry exists on the database, thisinformation is also buffered in the internal table (EXIST field).

148 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 157: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

You can use read routines if data is buffered in the local program buffer and is notreused. If you want to buffer data across programs in an internal session (callchain), use a function module. Table contents are buffered in various locations inthe SAP standard (for example, FB STATUS_CHECK).

� Define minimum requirements for entries on selection screens and searchhelp (end-user training and operation concept)

� Self-defined selection screens

� Define selective fields (PARAMETER, SELECT-OPTIONS) asrequired entry fields

� Check user entries for minimum requirements� Implement appropriate SQL statements depending on user entries

� Own search help

� Create customer-owned search help following SAP standard� If necessary, define input fields as required entry fields

To enable efficient data selection, you must define minimum requirementsfor user entries on selection screens and search help (both SAP standard andcustomer-owned). To facilitate this, develop end user training and an operationconcept for the business process. Data selection must be supported by a databaseindex.

For customer-owned selection screens, define input fields (PARAMETER,SELECT OPTIONS) as required entry fields (use the addition OBLIGATORY).In addition, establish whether user entries make sense by checking them againstthe minimum requirements you defined. Data selection then only begins once theminimum requirements have been met. If data selection is complex (for example,if fields are read from different tables), implement appropriate SQL statementsdepending on the user entries.

Implement customer-owned search help in accordance with the SAP standard(on the search help selection screen, list input fields according to selectivity, withthe most selective fields at the top).

If you have implemented the above recommendations, and problems still occurwith SAP standard or customer-owned search help, you can define input fieldson search help selection screens as required entry fields. To do this, contactSAP�s Technical Core Competence Center (TCC) for a GoingLive Check or anEarlyWatch Check.

2001/Q3 © 2004 SAP AG. All rights reserved. 149

Page 158: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Figure 108: Similar SQL Statements

Within an SQL performance trace, individual and similar SQL statements may notbe expensive. However, in total, they may greatly increase system load. If this isthe case, you should group the similar statements together.

The database differentiates SQL statements according to their texts. For example,a statement text for the database differs in the following cases:

Different number of values in a WHERE clause with an IN operation

Different number of values in a WHERE clause with an OR operation

Different WHERE clauses (number, reference fields, order)

Different field lists

If SQL statements differ only in the composition of the field lists or in the orderof the WHERE clauses, they can often be grouped together. You can also grouptogether SQL statements where one statement returns a subset of another statement(for example, statements with WHERE clauses with IN or OR operations).

In addition to reducing SQL statements for the particular single object, groupingSQL statements together affects the performance of the whole system. Thedatabase manages fewer SQL statements in the DB SQL cache. The CPU loadon the database server is reduced (due to fewer parses). The memory load onthe database server is also reduced (due to fewer SQL statements in the DBSQL cache).

150 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 159: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Figure 109: See Topic Other Methods: Roadmap

Figure 110: Suitable Access Path: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 151

Page 160: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

152 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 161: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Exercise 3: Suitable Access Path for aTable

Exercise ObjectivesAfter completing this exercise, you will be able to:� Optimize an existing ABAP program that causes database accesses on one

table and shows poor performance

Business ExampleYou are a developer with ABC Limited, a petrochemical company. You need tooptimize an existing ABAP program that causes database accesses and showspoor performance.

Task:In your program ZBC490_##_PROJECT_CASE_STUDY, optimize the SELECTstatements that refer to a single database table.

Note: For this exercise, do not change the subroutineGET_ELIGIBLE_SALES_ITEMS and its subroutines ITEM_VALUEand PROCESS_SCHEDULE_LINES. In addition, do not change thesubroutines for data output.

1. You can optimize the subroutine SELECT_DELV_PGI by using anaggregation function. The database access is performed under particularconditions that you can specify using the SELECT statement.

Optimize the access on the table EEORD in the subroutineGET_SOURCE_LIST.

In general, you should use the field lists in the SELECT statements.

2001/Q3 © 2004 SAP AG. All rights reserved. 153

Page 162: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Solution 3: Suitable Access Path for aTableTask:In your program ZBC490_##_PROJECT_CASE_STUDY, optimize the SELECTstatements that refer to a single database table.

Note: For this exercise, do not change the subroutineGET_ELIGIBLE_SALES_ITEMS and its subroutines ITEM_VALUEand PROCESS_SCHEDULE_LINES. In addition, do not change thesubroutines for data output.

1. You can optimize the subroutine SELECT_DELV_PGI by using anaggregation function. The database access is performed under particularconditions that you can specify using the SELECT statement.

Optimize the access on the table EEORD in the subroutineGET_SOURCE_LIST.

In general, you should use the field lists in the SELECT statements.

a)*************************************************

PROCESS_GET_NAME1

*************************************************

>>> SOLUTION

SELECT SINGLE name1 FROM kkna1 INTO itab-name1

WHERE kunnr EQ vvbak-kunnr.

*************************************************

SELECT_DELV_PGI

*************************************************

The database access on table VVBFA only affects

the field RFMNG; this field is summed in the

program. This process can be optimized using the

aggregate function SUM.

The condition can be included in a HAVING clause.

FORM select_delv_pgi.

* SORT itab BY order_# ord_pos.

LOOP AT itab.

* IF itab-order_# NE issue-order_#

* OR itab-ord_pos NE issue-ord_pos.

* CLEAR issue.

** Select predecessor document

Continued on next page

154 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 163: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

* SELECT * FROM vvbfa

* WHERE vbelv = itab-order_#

* AND posnv = itab-ord_pos

* AND vbtyp_n = ’R’.

* ** Successor document positions and post good

issue quantity

* issue-order_# = itab-order_#.

* issue-ord_pos = itab-ord_pos.

* issue-pgi_qty = issue-pgi_qty + vvbfa-

rfmng.

*

* ENDSELECT.

>>> SOLUTION

* Use of aggregate functions and having clause

SELECT SUM( rfmng ) INTO issue-p

gi_qty

FROM vvbfa

WHERE vbelv = itab-order_#

AND posnv = itab-ord_pos

AND vbtyp_n = ’R’

GROUP BY vbelv posnv

HAVING SUM( rfmng ) > 0.

issue-order_# = itab-order_#.

issue-ord_pos = itab-ord_pos.

APPEND issue.

ENDSELECT.

ENDLOOP.

ENDFORM.

" SELECT_DELV_PGI

*************************************************

DETERMINE_PROCUREMENT_TYPE

*************************************************

FORM determine_procurement_type.

CLEAR: tmp_mat, tmp_plnt.

SORT itab BY matnr.

LOOP AT itab.

IF itab-matnr NE tmp_mat OR

itab-werks NE tmp_plnt.

Continued on next page

2001/Q3 © 2004 SAP AG. All rights reserved. 155

Page 164: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

CLEAR: mmara.

MOVE: itab-matnr TO tmp_mat,

itab-werks TO tmp_plnt.

* SELECT SINGLE * FROM mmarc WHERE matnr =

itab-matnr AND

* werks = itab-werks.

* * IF sy-subrc EQ 0.

* MOVE: mmarc-beskz TO itab-proc_type,

* mmarc-dispo TO itab-mrp_con.

* ELSE.

* ENDIF.

*

* SELECT SINGLE * FROM mmara WHERE matnr = itab-matnr.

>>> SOLUTION

SELECT SINGLE beskz dispo FROM mmarc

INTO (mmarc-beskz, mmarc-dispo)

WHERE matnr EQ itab-matnr

AND werks EQ itab-werks.

IF sy-subrc EQ 0.

MOVE: mmarc-beskz TO itab-proc_type,

mmarc-dispo TO itab-mrp_con.

ENDIF.

SELECT SINGLE prdha FROM mmara

INTO mmara-prdha

WHERE matnr = itab-matnr.

* Change the offset to take last five positions

of product hierarchy

IF sy-subrc EQ 0.

MOVE: mmara-prdha+13 TO itab-prod_hier.

ENDIF.

ELSE. "Same item & Plant

MOVE: mmara-prdha+13 TO itab-prod_hier.

MOVE: mmarc-beskz TO itab-proc_type,

mmarc-dispo TO itab-mrp_con.

ENDIF.

* Procurement types ’X’ and ’E’ are processed

Continued on next page

156 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 165: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

the same way and therefore type ’X’ is represented as a

type ’E’ in the internal table for sorting purposes

IF itab-proc_type = ’X’.

itab-proc_type = ’E’.

ENDIF.

MODIFY itab.

ENDLOOP.

ENDFORM. " DETERMINE_PROCUREMENT_TYPE

*******************************************************************

GET_SOURCE_LIST

******************************************************************

Instead of the EXIT condition in the SELECT, the addition

UP TO 1 ROWS is used. The LOOP over the internal table ITAB

cannot be performed using the FOR ALL ENTRIES, since the

application logic requires a single record

evaluation.

LOOP AT itab WHERE proc_type = ’F’.

. . . .

SELECT

lifnr

FROM eeord

INTO itab-primary

UP TO 1 ROWS

WHERE matnr = itab-matnr

AND werks = itab-werks

AND flifn = ’X’

AND vdatu LE itab-crd_date

AND bdatu GT itab-crd_date.

ENDSELECT.

. . . .

ENDLOOP.

2001/Q3 © 2004 SAP AG. All rights reserved. 157

Page 166: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

158 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 167: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Exercise 4: Suitable Access Paths forSeveral Tables

Exercise ObjectivesAfter completing this exercise, you will be able to:� Optimize an existing ABAP program that causes database accesses on

dependent tables and shows poor performance

Business ExampleYou are a developer with ABC Limited, a petrochemical company. You need tooptimize an existing ABAP program that causes database accesses on dependenttables and shows poor performance.

Task:Optimize the subroutine GET_ELIGIBLE_SALES_ITEMS and its� subroutinePROCESS_SCHEDULE_LINES.

1. Optimize the database accesses on the tables VVBAK, VVBAP, VVBEP,and MMARC. Avoid nested SELECTs.

Perform an SQL Trace (ST05) for your program and check the databaseaccess. What has changed and why has performance improved?

Hint:From the respective tables, you require the following fields:

VVBAK: KUNNR, AUDAT, VKORG

VVBAP: VBELN, POSNR, WAERK,

WERKS, MATNR, UMVKZ,

UMVKN, KWMENG, NETWR

VVBEP: WMENG, ETENR , BMENG

EDATU

2001/Q3 © 2004 SAP AG. All rights reserved. 159

Page 168: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

Solution 4: Suitable Access Paths forSeveral TablesTask:Optimize the subroutine GET_ELIGIBLE_SALES_ITEMS and its� subroutinePROCESS_SCHEDULE_LINES.

1. Optimize the database accesses on the tables VVBAK, VVBAP, VVBEP,and MMARC. Avoid nested SELECTs.

Perform an SQL Trace (ST05) for your program and check the databaseaccess. What has changed and why has performance improved?

Hint:From the respective tables, you require the following fields:

VVBAK: KUNNR, AUDAT, VKORG

VVBAP: VBELN, POSNR, WAERK,

WERKS, MATNR, UMVKZ,

UMVKN, KWMENG, NETWR

VVBEP: WMENG, ETENR , BMENG

EDATU

a)**************************************************************************

GET_ELIGIBLE_SALES_ITEMS

This subroutine features accesses on the tables VVBAK, VVBAP, MMARC, and

VVBEP in nested SELECTs.

The SELECT SINGLE on MMARC is the condition for the accesses on

the other three tables.

These selects can be avoided by connecting the tables VVBAK, VVBAP, and

VVBEP using an ABAP INNER JOIN; and the condition on MMARC can be created

in the form of a SUBQUERY.

* >>> SOLUTION

SELECT vvbak~kunnr vvbak~audat vvbak~vkorg

vbap~vbeln vvbap~posnr vvbap~waerk

vvbap~werks vvbap~matnr vvbap~umvkz

vvbap~umvkn vvbap~kwmeng vvbap~netwr

vvbep~wmeng vvbep~etenr vvbep~bmeng

vvbep~edatu

Continued on next page

160 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 169: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

FROM vvbak INNER JOIN vvbap

ON vvbak~vbeln = vvbap~vbeln

INNER JOIN vvbep

ON vvbep~vbeln = vvbap~vbeln

AND vvbep~posnr = vvbap~posnr

INTO (itab-kunnr, itab-entry, itab-vkorg,

itab-order_#, itab-ord_pos, itab-curr,

itab-werks, itab-matnr, vvbap-umvkz,

vvbap-umvkn, vvbap-kwmeng, vvbap-netwr,

itab-crd_qty, itab-sch_line, itab-mpd_qty,

vvbep-edatu)

WHERE vvbak~vbeln LT g_vbeln

AND vvbap~werks IN plant

AND vvbep~edatu LE sy-datum

AND EXISTS ( SELECT * FROM mmarc

WHERE matnr EQ vvbap~matnr

AND werks EQ vvbap~werks

AND dispo IN mrp_ctlr ).

**************************************************************************

PROCESS_SCHEDULE_LINES

*************************************************************************

* SELECT * FROM vvbep

* WHERE vbeln = itab-order_#

* AND posnr = itab-ord_pos

* AND edatu LE sy-datum..

*

* itab-crd_qty = vvbep-wmeng.

* itab-sch_line = vvbep-etenr.

* itab-mpd_qty = vvbep-bmeng.

IF itab-crd_qty > 0.

MOVE: vvbep-edatu TO itab-crd_date.

ENDIF.

APPEND itab.

Continued on next page

2001/Q3 © 2004 SAP AG. All rights reserved. 161

Page 170: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 3: Database Accesses BC490

* ENDSELECT.

162 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 171: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Suitable Access Paths

Lesson Summary

You should now be able to:� Explain general methods of reducing the number of data records to be

transferred� Describe ways of accessing individual and several tables� Describe Pooled and Cluster tables� Explain SAP table buffering

2001/Q3 © 2004 SAP AG. All rights reserved. 163

Page 172: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit Summary BC490

Unit SummaryYou should now be able to:� Explain database accesses� Identify suitable and unsuitable access paths� Identify database indexes� Identify database joins� Explore possible problems within the system database� Use database hints� Explain general methods of reducing the number of data records to be

transferred� Describe ways of accessing individual and several tables� Describe Pooled and Cluster tables� Explain SAP table buffering

164 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 173: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

Test Your Knowledge

1. State the purpose of the database optimizer.

2. State the criteria that determine the search range on the database.

3. When a join is processed using the SORT MERGE JOIN access strategy,which of the following steps are performed?Choose the correct answer(s).□ A The table records that correspond to the WHERE clause are

selected□ B The tables in the join are sorted according to the JOIN condition□ C The table records are merged□ D Key tables are determined

4. For a full table scan, the read table blocks are added at the beginning ofthe LRU list.Determine whether this statement is true or false.□ True□ False

5. Database reorganization or deliberately deleting database objects can causeinconsistencies between the indexes in the ABAP Dictionary and the indexeson the database.Determine whether this statement is true or false.□ True□ False

2001/Q3 © 2004 SAP AG. All rights reserved. 165

Page 174: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

6. As of SAP Basis Release 4.5A, can you use database hints directly fromOPEN SQL? If yes, how?

7. To reduce the number of data records to be transferred, for each SQLstatement you must specify a .Fill in the blanks to complete the sentence.

8. You can use RANGES table in ABAP. You can define RANGES tablesusing the ABAP statements and

.Fill in the blanks to complete the sentence.

9. A table pool stores data records from tables, which are dependent on eachother, defined in the ABAP dictionary.Determine whether this statement is true or false.□ True□ False

10. Transaction data should never be buffered.Determine whether this statement is true or false.□ True□ False

166 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 175: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

Answers

1. State the purpose of the database optimizer.

Answer: The database optimizer determines the strategy for accessing datarecords. Data records can be accessed using database indexes, which is calledindex access, or without database indexes, which is called a full table scan.

2. State the criteria that determine the search range on the database.

Answer: The search range is the number of records that need to be checkedin a table in order to satisfy an SQL statement. When the SQL statement isprocessed on the database, the search range is dynamically determined bythe WHERE clause.

3. When a join is processed using the SORT MERGE JOIN access strategy,which of the following steps are performed?

Answer: A, B, C

When a join is processed, the following steps are performed:

1. The table records that correspond to the WHERE clause are selected2. The tables in the join are sorted according to the JOIN condition3. The table records are merged

4. For a full table scan, the read table blocks are added at the beginning ofthe LRU list.

Answer: False

For a full table scan, the read table blocks are added to the end of the LRUlist.

5. Database reorganization or deliberately deleting database objects can causeinconsistencies between the indexes in the ABAP Dictionary and the indexeson the database.

Answer: True

Database reorganization or deliberately deleting database objects can causeinconsistencies between the indexes in the ABAP Dictionary and the indexeson the database.

2001/Q3 © 2004 SAP AG. All rights reserved. 167

Page 176: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

6. As of SAP Basis Release 4.5A, can you use database hints directly fromOPEN SQL? If yes, how?

Answer: Yes, as of SAP Basis Release 4.5A, you can use database hintsdirectly from OPEN SQL. To do this, add the addition%_HINTS DBMS ’DBHINT’

to the end of the SQL statement. Under DBMS, enter the applicable databasesystem (for example, ORACLE, INFORMIX). Under DBHINT, enter therelevant database-specific hint.

7. To reduce the number of data records to be transferred, for each SQLstatement you must specify a WHERE clause.

Answer: WHERE clause

8. You can use RANGES table in ABAP. You can define RANGES tables usingthe ABAP statements SELECT-OPTIONS and RANGES.

Answer: SELECT-OPTIONS, RANGES

9. A table pool stores data records from tables, which are dependent on eachother, defined in the ABAP dictionary.

Answer: False

A table pool stores data records from tables, which are not dependent on eachother, defined in the ABAP dictionary.

10. Transaction data should never be buffered.

Answer: True

Transaction data, such as VBAK, LIKP, MKPF or RESB, can grow to severalgigabytes. In addition, they are changed frequently.

168 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 177: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4Internal Tables

Unit OverviewThis unit covers the definition, composition, and uses of internal tables. Inaddition, the unit discusses working with internal tables.

Unit ObjectivesAfter completing this unit, you will be able to:

� Explain the advantages and disadvantages of the various table types� Explain the composition of internal tables� Access internal tables� Use internal tables

Unit ContentsLesson: Introduction to Internal Tables .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170Lesson: Working with Internal Tables ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181

Exercise 5: Table Types, Pointer Accesses, and Internal Buffering ofData Records .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .197

2001/Q3 © 2004 SAP AG. All rights reserved. 169

Page 178: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Lesson: Introduction to Internal Tables

Lesson OverviewThis lesson defines internal tables and explains their properties. It also explainsthe advantages and disadvantages of the various table types, and describes howto compose internal tables efficiently.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain the advantages and disadvantages of the various table types� Explain the composition of internal tables

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters performance problems due to errors in ABAP programming. As adeveloper, you need to use internal tables to resolve this problem. However, youneed to understand the properties and composition of internal tables before usingthem.

Realizing Internal Tables

Figure 111: Internal Table Attributes

170 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 179: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Internal Tables

An internal table is fully specified by the following information:

� Line type:

The line type of an internal table can be any ABAP data type. It is generallya structured data type.

� Key sequence:

The key fields and their sequence determine the criteria by which the systemidentifies table lines.

� Uniqueness attribute:

You can define the key of an internal table as either UNIQUE orNON-UNIQUE. If the key is unique, there can be no duplicate entries inthe internal table.

� Table type:

The table type defines how ABAP access individual table lines. This can beeither by table index (access by row ID) or by the key (access by key fields).

Figure 112: Defining Internal Tables

The following statement creates an internal table with <tabkind> type and<linetype> line type:

DATA <itab> TYPE <tabkind> OF <linetype>

[WITH [UNIQUE | NON-UNIQUE] <keydef>] [INITIAL SIZE <n>]

2001/Q3 © 2004 SAP AG. All rights reserved. 171

Page 180: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Normally, you also specify a user-defined key in the form <f1> ... <fn>. All of thefields in the key must have a flat structure. The addition DEFAULT KEY allowsyou to set the standard key (all non-numerical fields) as the table key as requiredby the definition of internal tables before Release 4.0.

You can use the UNIQUE or NON-UNIQUE addition to specify whether the tableshould be allowed to contain entries with duplicate keys.

If you know that your internal table will be smaller than 8KB, use the INITIALSIZE <n> addition to reserve its initial memory space.

Figure 113: Table Types

172 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 181: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Internal Tables

The table type defines how ABAP access individual table lines. There are threetypes of internal tables:

� In a standard table, you can access data using either the table index or thekey. If access proceeds via the primary key, the response time is linearlyrelated to the number of table entries. The key of a standard table is alwaysnon-unique.

� Sorted tables are always stored in ascending order according to their key.You can access them using either the table index or the key. If you use thekey, the response time is in logarithmic relation to the number of table entriesbecause the system uses a binary search to access the table. The key of asorted table can be either unique or non-unique.

� Standard tables and sorted tables are generically known as index tables, sincetheir values can be accessed via an index.

� Hashed tables can only be accessed via the primary key. The response timeis constant, regardless of the number of table because access proceeds viaa hash algorithm. The hash algorithm is determined internally. The key ofa hashed table must be unique. You can neither implicitly nor explicitlyaccess hash tables through indexes.

At runtime, you can find out the type of an internal table (ITAB) using thestatement DESCRIBE TABLE <ITAB> KIND <k>.

Index Operations on Internal Tables

Figure 114: Overview: Index Operations on Internal Tables

2001/Q3 © 2004 SAP AG. All rights reserved. 173

Page 182: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Internal table operations can be classified as follows:

� By their access method, as either index operations or key operations.� By the scope of their access, as either single record processing or mass

processing.

Single record processing accesses one line in each operation, while massprocessing accesses n lines.

� By the operation type, as Read, Append, Insert, Change, or Delete.

Index operations cannot be used for hashed tables. For index tables, indexoperations are faster than key operations.

Figure 115: Overview: Key Operations on Internal Tables

Rows can be identified either via the work area from which the key values aretaken (in an implicit key access); or via an explicit key specification using WITH[TABLE] KEY. Key accesses are possible for all table types, but they showdifferent levels of performance for each table type.

Hashed tables are useful for reading a single data record via the table key becausethe resulting access time is independent of the number of table entries. Thelocation of the data record to be read is determined using the hash function. Thetime required is independent of the number of table entries.

INSERT for a standard table or hashed table using the key has the same effect as anAPPEND statement. For hashed tables, however, the address of the data row to beentered must also be calculated. For inserts in sorted tables, the sort sequence mustbe strictly observed, which means the access costs grow with increasing table size.

174 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 183: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Internal Tables

With a COLLECT for standard tables, a hash function is created internally. Usingthis hash function results in good performance. The hash function for standardtables is, however, non-persistent, because it is destroyed by each INSERT,DELETE, and so on. After performance is reduced with a COLLECT all fieldsthat are not part of the key must have a numeric type.

The location of the table entry must be determined with the MODIFY andDELETE key operations.

Costs by Access Type

Figure 116: Costs by Access Type

Evaluating the costs of the various access types shows that index operationsprovide the most efficient access. For more detailed information on ABAPstatements, see the Appendix.

2001/Q3 © 2004 SAP AG. All rights reserved. 175

Page 184: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Inserting and Filling an Internal Table

Figure 117: ARRAY FETCH

Instead of building an internal table using single data records, use mass dataprocessing via a SELECT. This is known as an ARRAY FETCH. The ARRAYFETCH can be used for all target tables of any table type. ARRAY FETCH canbe used to extend an existing table (with APPENDING) or fill an existing tablewith new data (using INTO TABLE).

Mass data processing should not be used if the internal table has a deep rowstructure, that is, contains nested tables. In this case, you require single data recordprocessing with SELECT ... ENDSELECT.

The internal table should have a structure similar to the field list, so that it isunnecessary to use INTO CORRESPONDING FIELDS (which must perform theadditional work of comparing the field names).

If the target table is of type SORTED, the ARRAY FETCH automatically sortsthe inserted data. If APPENDING is used, the new data records are added in thesorted order. If the internal table key is part of the primary key of the databasetable, it cannot be defined as UNIQUE because duplicates may occur. Theseduplicates cause runtime errors.

176 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 185: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Internal Tables

Figure 118: Inserting Internal Tables

If you are augmenting an internal table from an internal table, use the indicatedmass processing instructions. The prerequisite for this is that internal tables havethe same fields. These fields do not need identical names.

The MOVE-CORRESPONDING statement (requiring identical names for fields)can only be used to work on work areas or headers.

APPEND/INSERT LINES can be used to extend an existing internal table(ITAB2). You can copy an interval of lines from the source table ITAB1 using aFROM...TO.

Figure 119: Filling an Internal Table with Cumulative Values

2001/Q3 © 2004 SAP AG. All rights reserved. 177

Page 186: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

With the COLLECT statement, the contents of the work area is added to an entrywith the same key or added to the table as a new entry. This allows you to createaggregated internal tables, thereby reducing data volume.

COLLECT searches in the internal table for a data record according to the tabletype and defined key. If it finds an entry in the table, it adds all numeric fieldsof the work area or header that are not part of the key to the corresponding fieldsof the entry. If no entry is found, the contents of the work area or header roware added as a new table entry.

You can only use the COLLECT statement with internal tables whose non-keyfields are all numeric (type I, P, or F). If not, you get a syntax error. From SAPBasis release 4.0A, the table key may contain numeric fields.

The COLLECT statement is internally optimized for standard tables so that theresponse time is constant. This optimization applies as long as the tables arenot modified with DELETE, INSERT, or SORT (non-persistent hash function).Using the latter instructions loses the rapid internal access, and leads to linearlyincreasing access costs for the COLLECT.

With hashed and sorted tables, the cost of the COLLECT statement is constant,even if you use DELETE, INSERT, or SORT.

Composition of Internal Tables: Roadmap

Figure 120: Composition of Internal Tables: Roadmap

178 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 187: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Introduction to Internal Tables

Figure 121: Composition from Database Tables: Roadmap

Figure 122: Composition from Internal Tables: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 179

Page 188: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Lesson Summary

You should now be able to:� Explain the advantages and disadvantages of the various table types� Explain the composition of internal tables

180 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 189: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Lesson: Working with Internal Tables

Lesson OverviewThis lesson describes the ways to access internal tables and use them.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Access internal tables� Use internal tables

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters performance problems due to errors in ABAP programming. As adeveloper, you need to use internal tables to resolve this problem.

Accessing Internal Tables

Figure 123: Limited Mass Data Accesses

Just as a SELECT ... WHERE is more optimal compared to a SELECT used inconjunction with CHECK, you should use a WHERE clause to work on internaltables.

2001/Q3 © 2004 SAP AG. All rights reserved. 181

Page 190: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

To improve the performance of a LOOP ... WHERE, the compared fields shouldbe of the same type. You should define the comparison fields as follows: DATAcomparison field LIKE table field.

LOOP ... WHERE: Because you cannot access part-fields of tables that do nothave a structured line type (for example, tables via type I), use a TABLE_LINE toaccess the entire table line within the WHERE clause.

Figure 124: Selective Field Transport

LOOP, READ, and MODIFY normally place all entries of a line into the tablework area: or move entries from the work area into the table body.

You can use TRANSPORTING to specify the fields you are interested in. Notthe whole line, but only the contents of the relevant fields are copied. This isespecially important if the table has a deep structure (with nested internal tables)because here copying costs can be reduced considerably. Since SAP Basis release4.5A, a technique allows direct access to the table body, thus causing zero copyingcosts. This technique uses field symbols (LOOP ... ASSIGNING).

You can use TRANSPORTING NO FIELDS to specify a number of row indexes(an index quantity) or table rows that satisfy a particular condition.

LOOP ... TRANSPORTING can only be used with a WHERE clause.

182 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 191: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Figure 125: Using Field Symbols

Field symbols in ABAP are similar to pointers in other programming languages.However, pointers (as used in PASCAL or C) differ from ABAP field symbols intheir reference syntax.

You declare field symbols using the FIELD-SYMBOLS statement. They canbe qualified using LIKE or TYPE. As of SAP R/3 Enterprise Release 4.6, afield symbol should always be qualified. For a qualification that is as generalas possible, use TYPE ANY.

The statement ASSIGN f TO <fs> assigns the field to the fs field symbol. The fsfield symbol then points to the contents of the f field f at runtime. This means thatall changes to the contents of f are visible in fs and vice versa.

Before using MOVE for a field symbol, you must use ASSIGN to point the fieldsymbol to a data object. To find out whether the field symbol is assigned to adata abject, use IF <fy> IS ASSIGNED.

If you declare a non-qualified field symbol, or a field symbol of type ANY, itautomatically receives the type of the field it points to. If you declare a qualifiedfield symbol, you can only let it point to data objects with a compatible type.

2001/Q3 © 2004 SAP AG. All rights reserved. 183

Page 192: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Figure 126: Access on Tables without Field Transfer

As of SAP Basis release 4.5A, table rows can be accessed directly in the tablebody. This means that a work area or header row is not required. Instead, a tablerow is accessed using LOOP AT itab ... ASSIGNING <fs> and field symbols.

ASSIGNING is available for READ and LOOP.

Note that ASSIGNING always works directly on the table body. You cannotchange the key components of a sorted or hashed internal table. Within a LOOP...ASSIGNING you must not let the field symbol point to another data object withan ASSIGN.

LOOP AT <itab> ... ASSIGNING is faster than LOOP AT <itab> ... INTO <wa>,regardless of the table width, providing the table is larger than 10 lines.

After the loop, the field symbol is positioned on the last line.

If you want to access individual components using the field symbol within aLOOP, use the addition TYPE/LIKE with the instruction FIELD-SYMBOLS.

A value assignment performs changes of field contents and must not be performedusing MODIFY.

184 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 193: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Figure 127: Reading Single Records

The index access shows the best performance. Index accesses are not possible withhashed tables. Accesses on single data records in hash tables are always realizedusing a unique key. This is between 2.5 and 3 times slower than an index access.

The READ variants FROM <wa> and WITH TABLE KEY..., new in Release4.0, are defined for all table types. The internal access is optimized accordingto the table type. The cost of the READ statement is linear for standard tables,logarithmic for sorted tables, and constant for hashed tables.

If you frequently wish to access a standard table via the key, sort the tableaccording to the relevant fields and then use the addition BINARY SEARCH. TheBINARY SEARCH reduces the access cost to a logarithmically increasing value.The required SORT has a cost of O(n*log n), where n is the number of rows inthe internal table.

When you specify all keys and use the WITH KEY statement, a full table scan isrequired instead of a binary search or a hash algorithm.

The addition WITH TABLE KEY is internally translated into a FROM <wa>.

2001/Q3 © 2004 SAP AG. All rights reserved. 185

Page 194: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Internal Tables: Roadmap

Figure 128: Internal Tables: Roadmap

Figure 129: Optimizing Read Access: Roadmap

186 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 195: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Figure 130: Reading Single Records: Roadmap

Figure 131: Changing Existing Records: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 187

Page 196: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Hashed, Sorted, and Standard Tables

Figure 132: Hashed Table

Use a hashed table whenever multiple single record accesses are required for aninternal table via the fully specified key.

Hashed tables are useful for read modules. These function modules buffer the readdata in an internal table. Before sending the SELECT to the database, the buffer ischecked to see if the data record is already there. If so, the SELECT is not used;if the SELECT is performed, the new data record is added to the buffer. In thisread module, more application logic is required. For example, more than one datarecord is read by the SELECT, controlling of the buffer size is performed, and soon. You can find such function modules in the function group V45I.

Another use for hashed tables is when accessing the intersection of two groupsof data. Finding out whether an entry is present in an internal table requires aneffort of O(1) if you use a hashed table. Therefore, accessing the intersection oftwo groups of data is possible with an effort of O(n) if you use a hashed table withn entries for the (probably) larger table.

The operating system limits the maximum number of entries in a hash table.

188 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 197: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Figure 133: Sorted Table

In partial sequential processing for sorted tables, you process optimized loops(that is, only the lines that fulfill the WHERE condition are processed), providedthe WHERE condition has the following form: WHERE k1 = v1 AND k2 = v2AND ... AND kn = vn, and the components k1 to kn exactly reflect the beginningof the table key.

If gaps are left in the sequence of key fields when specifying the WHEREcondition, the access cannot be optimized.

If the internal table has n entries and the WHERE clause is satisfied by m entries,an optimized access requires an effort of O(m+log n).

For tables of type STANDARD or HASHED, processing a WHERE clauseinvolves processing all table entries in a full table scan. Therefore, these tablesrequire a time of O(n).

The instructions MODIFY and DELETE are optimized by a suitable WHEREclause. This optimization does not occur when a standard table is sorted andsubsequently processed with a WHERE clause.

2001/Q3 © 2004 SAP AG. All rights reserved. 189

Page 198: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Figure 134: Standard Table

It is appropriate to use a standard table whenever the data to be accessed bydifferent processing steps varies.

This is the case when one key operation accesses one group of fields, whileanother key operation accesses a different group of fields. This is true especially ifsome of the specified fields are not key fields. In this case, the other table typesalso require a full table scan. A standard table has the advantage of being able tobe sorted by any field, and subsequently processed by, for example, a READ...BINARY SEARCH (logarithmic cost).

You can also use the stable SORT (by adding STABLE to the SORT instruction).This preserves the relative order of data records that have the same sort key.

If you are working mainly with index accesses, a standard table is a good choicebecause it can be augmented faster than the other two table types: For a standardtable, INSERT acts like an APPEND. During an INSERT with a sorted table, thesystem must observe the sort order while with a hashed table, the system mustrepeatedly reapply the hash algorithm.

190 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 199: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Composing and Processing Internal Tables

Figure 135: Composing Unique Internal Tables

Sometimes you should build an internal table using a SELECT ... INTO ... sothat the internal table has fewer key fields than the database table. In this case,duplicates may occur in the internal table. If you decide to use a hashed table, itmust be unique. In this case, use a non-unique sorted or standard table, delete theduplicates, and subsequently use a MOVE on the hashed table.

Building a non-unique table with ARRAY FETCH and then deleting anyduplicates is faster than building a unique table with SELECT... ENDSELECTand checking whether the current entry already exists in the internal table. If youwant all key fields of the database table to appear in the internal table, but not inthe key, you cannot use a SELECT DISTINCT.

Instead, this can be optimally realized using DELETE ADJACENT DUPLICATESFROM This checks whether adjacent rows have the same key. The internal tableshould be sorted.

COMPARING lets you define duplicates in terms of other keys.

You can use DELETE ADJACENT DUPLICATES FROM <itab> to subsequentlyaggregate internal tables.

2001/Q3 © 2004 SAP AG. All rights reserved. 191

Page 200: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Figure 136: Processing Nested Tables

This causes high copying costs when working with a work area, especially withdeep structures (where a component of the line type is itself an internal table).The ASSIGNING variant is quicker with deep internal tables because there areno associated copying costs.

You can change the field contents by value assignments. Thus, you do not requirea MODIFY.

Be aware of memory consumption with nested tables. You can display the memoryconsumption in the debugger.

192 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 201: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Figure 137: Mass Processing Using an Index Interval

In the example, the index access is used to partly process the dependent tablesequentially, from the respective starting point. To use this technique, the tablesmust be sorted and a criterion must exist to move the starting point in thedependent table. Typical examples are header tables and item tables that connectvia common key fields. For each loop on the external table, the cost decreases forthe internal loop.

In the left-hand example, the inner-LOOP has a cost of O(log n) where n is thenumber of rows in sort_vbap.

2001/Q3 © 2004 SAP AG. All rights reserved. 193

Page 202: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Reading and Modifying Data

Figure 138: Secondary Index: Reading Data

If you often need to access a field that is not specified by the key of the internaltable, a full table scan is performed. It may be useful to create a hash_sec_indexinternal table, whose key consists exactly of the specified fields. The only non-keyfield consists of an internal table via which you can access the correspondingfields of the original table.

The graphic shows an approach that is useful for read accesses on an internaltable. In contrast, for write accesses this approach causes a large cost whenrefreshing the secondary index.

Since you are accessing the <hash_sec_index> internal table via single recordprocessing and the table key, a hashed table is useful. The <sort_vbak> internaltable is only accessed via an index. You can use a standard table or a sorted table.

A secondary index is especially useful for a sorted table because you cannot keepresort the table by different fields. For a standard table, it is generally betterperformance to sort according to the relevant fields and subsequently execute aREAD... BINARY SEARCH.

194 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 203: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Figure 139: Secondary Index: Modifying Data

To modify accesses on an internal table, you can use a secondary index procedurelike that for the database. Add the rowid field to your internal table. This field isthen added to the index table.

Since you are accessing the <hash_sec_index> internal table via single recordprocessing and the table key, a hashed table is useful. The <sort_vbak> internaltable is only accessed via the full key (rowid field). A hashed table is also usefulhere.

Selecting the Table Type: Roadmap

Figure 140: Selecting the Table Type: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 195

Page 204: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

196 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 205: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Exercise 5: Table Types, Pointer Accesses,and Internal Buffering of Data Records

Exercise ObjectivesAfter completing this exercise, you will be able to:� Optimize the internal tables

Business ExampleYou are a developer with ABC Limited, a petrochemical company. You installedthe SAP R/3 Enterprise System to improve the efficiency of your company�sactivities. To optimize program runtime, you need to optimize the processingof internal tables.

Task:1. At the moment, all internal tables are standard tables. Does it make sense to

change the type of some of the tables?

In the subroutine MATCH_ORDERS_TO_PGI, the fully filled internaltable itab is processed in a LOOP...ENDLOOP. Optimize this LOOP andits modification of the internal table. Changing the LOOP affects thesubroutines APPLY_PGI_DOCS and CURRENCY_CONVERSION.

Avoid identical SELECT statements on the table KKNAI by buffering datarecords using internal tables.

Define a suitable internal table for buffering the read data records from thetable KKNAI. Think about which type of table is best for buffering.

2001/Q3 © 2004 SAP AG. All rights reserved. 197

Page 206: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

Solution 5: Table Types, Pointer Accesses,and Internal Buffering of Data RecordsTask:1. At the moment, all internal tables are standard tables. Does it make sense to

change the type of some of the tables?

In the subroutine MATCH_ORDERS_TO_PGI, the fully filled internaltable itab is processed in a LOOP...ENDLOOP. Optimize this LOOP andits modification of the internal table. Changing the LOOP affects thesubroutines APPLY_PGI_DOCS and CURRENCY_CONVERSION.

Avoid identical SELECT statements on the table KKNAI by buffering datarecords using internal tables.

Define a suitable internal table for buffering the read data records from thetable KKNAI. Think about which type of table is best for buffering.

a) Three improvements were made to the program.

1. Table type

The internal table issue is replaced by a table of the type HASHED.

**************************************************************

DATA

*********************************************************************

DATA itab TYPE TABLE OF ty_tab WITH HEADER LINE.

*DATA issue TYPE TABLE OF ty_issue WITH HEADER LINE.

DATA issue TYPE HASHED TABLE OF ty_issue

WITH UNIQUE KEY order_# ord_pos WITH

HEADER LINE

Changing the table type affects the subroutines

**************************************************

SELECT_DELV_PGI

*************************************************

>>> SOLUTION

* Use of aggregate functions and having clause

SELECT SUM( rfmng ) INTO issue-pgi_qty

FROM vvbfa

WHERE vbelv = itab-order_#

AND posnv = itab-ord_pos

AND vbtyp_n = ’R’

GROUP BY vbelv posnv

HAVING SUM( rfmng ) > 0.

issue-order_# = itab-order_#.

Continued on next page

198 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 207: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

issue-ord_pos = itab-ord_pos.

* APPEND issue.

INSERT TABLE issue

********************************************

MATCH_ORDERS_TO_PGI

********************************************

. . . . .

* READ TABLE issue

COMPARING order_# ord_pos.

READ TABLE issue WITH TABLE

KEY order_# =<fs_itab>-order_ #ord_pos =<fs_itab>-ord_pos.

2. A LOOP on the internal table itab is performed using ASSIGNING.

***********************************************

* FIELD SYMBOLS

**********************************************

FIELD-SYMBOLS: <fs_itab>TYPE ty_tab.

***********************************************

MATCH_ORDERS_TO_PGI

**********************************************

* >>> SOLUTION

LOOP AT itab ASSIGNING <fs_itab>.

IF <fs_itab>-order_# NE tmp_ord OR

<fs_itab>-ord_pos NE tmp_pos.

MOVE:<fs_itab>-order_#TO issue-order_#,

<fs_itab>-ord_pos TO issue-ord_pos.

MOVE:<fs_itab>-order_# TO tmp_ord,

<fs_itab>-ord_pos TO tpm_pos.

* READ TABLE issue COMPARING order_# ord_pos.

READ TABLE issue WITH TABLE KEY order_#

= <fs_itab>-order_#

ord_pos =<fs_itab>-ord_pos.

IF sy-subrc EQ 0.

MOVE: issue-pgi_qty TO mpd_pgi,

issue-pgi_qty TO crd_pgi.

ELSE.

CLEAR: mpd_pgi,

crd_pgi.

ENDIF.

ENDIF.

PERFORM apply_pgi_docs.

Continued on next page

2001/Q3 © 2004 SAP AG. All rights reserved. 199

Page 208: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

ENDLOOP.

**********************************************

APPLY_PGI_DOCS

**********************************************

FORM apply_pgi_docs.

* >>> SOLUTION

* All ’itab’ is replaced by ’<fs_itab>’

* Manufactured Promised - issue Qty

IF mpd_pgi >=<fs_itab>-mpd_qty.

mdp_pgi=mpd_pgi - <fs_itab>-mpd_qty.

<fs_itab>-mpd_qty = 0.

ELSE

<fs_itab>-mpd_qty = <fs_itab>-mpd_qty - mpd_pgi.

mpd_pgi = 0.

ENDIF.

* Customer Requested - issue qty

IF crd_pgi >= <fs_itab>-crd_qty.

crd_pgi = crd_pgi -<fs_itab>-crd_qty.

<fs_itab>-crd_qty = 0.

ELSE.

<fs_itab>-crd_qty =<fs_itab>-crd_qty - crd_pgi.

crd_pgi = 0.

ENDIF.

* Modify itab table to reflect open quantities.

IF <fs_itab>-mpd_qty = 0 AND <fs_itab>-crd_qty = 0.

DELETE itab.

ELSE.

IF <fs_itab>-curr NE currency.

PERFORM currency_conversion.

ELSE.

<fs_itab>-ext_mpd =

(<fs_itab>-mpd_qty *<fs_itab>-itm_val ).

<fs_itab>-ext_crd =

(<fs_itab>-crd_qty *<fs_itab>-itm_val ).

ENDIF.

* The MODIFY command is not necessary anymore

Continued on next page

200 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 209: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

MODIFY itab

ENDIF.

ENDFORM.

" APPLY_PGI_DOCS

*********************************************

CURRENCY_CONVERSION

*********************************************

FORM currency_conversion.

CALL FUNCTION ’READ_EXCHANGE_RATE’ "added hhv

EXPORTING

date = <fs_itab>-entry

foreign_currency =<fs_itab> -curr

local_currency = currency

type_of_rate = ’M’

IMPORTING

exchange_rate = imprate

foreign_factor = ffact

local_factor = tfact

EXCEPTIONS

no_rate_found = 01.

* ITAB-EXT_MPD = ( ITAB-MPD_QTY * ITAB-ITM_VAL )

* XCURR-UKURS. "hhv

<fs_itab>-ext_mpd = (<fs_itab>-mpd_qty *<fs_itab>-itm_val )

* imprate / ffact * tfact. "hhv

* ITAB-EXT_CRD = ( ITAB-CRD_QTY * ITAB-ITM_VAL )

* XCURR-UKURS. "hhv

<fs_itab>-ext_crd = (<fs_itab>-crd_qty *

<fs_itab>-itm_val )

* imprate / ffact * tfact.

"hhv

ENDFORM.

" CURRENCY_CONVERSION

3.The identical SELECTs on table KKNA1 are avoided

by internal buffering in the program.

************************************************

* TYPES

************************************************

TYPES: BEGIN OF ty_buffer_kkna1,

Continued on next page

2001/Q3 © 2004 SAP AG. All rights reserved. 201

Page 210: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 4: Internal Tables BC490

kunnr LIKE kkna1-kunnr,

name1 LIKE kkna1-name1,

END OF ty_buffer_kkna1.

. . . . . .

************************************************

* DATA

************************************************

* Buffer table KKNA1

DATA buffer_kkna1 TYPE HASHED TABLE OF ty_buffer_kkna1

WITH UNIQUE KEY kunnr WITH HEADER LINE.

. . . . .

************************************************

PROCESS_GET_NAME1

***********************************************

FORM process_get_name1.

* SELECT SINGLE * FROM kkna1

* WHERE kunnr EQ vvbak-kunnr.

*

* itab-name1 = kkna1-name1.

* >>> SOLUTION

READ TABLE buffer_kkna1 WITH TABLE KEY kunnr = itab-kunnr.

IF sy-subrc <> 0.

* >>> SOLUTION

SELECT SINGLE name1 FROM kkna1

INTO buffer_kkna1-name1 WHERE kunnr EQ itab-kunnr.

buffer_kkna1-kunnr = itab-kunnr.

INSERT TABLE buffer_kkna1.

ELSE.

itab-name1 = buffer_kkna1-name1.

ENDIF.

ENDFORM.

" PROCESS_GET_NAME1

202 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 211: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Working with Internal Tables

Lesson Summary

You should now be able to:� Access internal tables� Use internal tables

2001/Q3 © 2004 SAP AG. All rights reserved. 203

Page 212: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit Summary BC490

Unit SummaryYou should now be able to:� Explain the advantages and disadvantages of the various table types� Explain the composition of internal tables� Access internal tables� Use internal tables

204 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 213: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

Test Your Knowledge

1. Unlike the index tables, hashed tables can only be accessed via the primarykey.Determine whether this statement is true or false.□ True□ False

2. Mass data processing should be used if the internal table contains nestedtables.Determine whether this statement is true or false.□ True□ False

3. If you frequently wish to access a standard table via the key, you cansort the table according to the relevant fields and then use the addition

.Fill in the blanks to complete the sentence.

4. It is appropriate to use a standard table whenever the data to be accessedby different processing steps varies.Determine whether this statement is true or false.□ True□ False

2001/Q3 © 2004 SAP AG. All rights reserved. 205

Page 214: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

Answers

1. Unlike the index tables, hashed tables can only be accessed via the primarykey.

Answer: True

Index tables can be accessed by using either the key or index access.

2. Mass data processing should be used if the internal table contains nestedtables.

Answer: False

Mass data processing should not be used if the internal table contains nestedtables. Instead, field symbols should be used.

3. If you frequently wish to access a standard table via the key, you can sortthe table according to the relevant fields and then use the addition BINARYSEARCH.

Answer: BINARY SEARCH

4. It is appropriate to use a standard table whenever the data to be accessedby different processing steps varies.

Answer: True

A standard table has the advantage of being able to be sorted by any field.

206 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 215: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5R/3 System Analysis

Unit OverviewThis unit covers the SAP R/3 Enterprise system analysis in detail. The unitdiscusses SAP R/3 Enterprise workload analysis, database SQL cache analysis,and snapshot analysis.

Unit ObjectivesAfter completing this unit, you will be able to:

� Identify individual objects that reduce performance� Determine whether the problem is mainly a database problem or CPU

problem� Identify database locks

Unit ContentsLesson: Types of R/3 System Analysis .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208

2001/Q3 © 2004 SAP AG. All rights reserved. 207

Page 216: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Lesson: Types of R/3 System Analysis

Lesson OverviewThe lesson provides an overview of SAP R/3 Enterprise System Analysis. Itdescribes the various types of SAP R/3 Enterprise System Analysis, such as R/3Workload Analysis, Database SQL Cache Analysis, and Snapshot Analysis. Thelesson also explains the need for each of these types of analyses.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Identify individual objects that reduce performance� Determine whether the problem is mainly a database problem or CPU

problem� Identify database locks

Business ExampleABC Limited is a petrochemical company. It has installed the SAP R/3 Enterprisesystem to improve the efficiency of its activities. However, the companyencounters performance problems due to errors in ABAP programming. As adeveloper, you need to diagnose the errors in ABAP programming by using theR/3 System Analysis process.

Overview of R/3 System Analysis

� What is an R/3 System analysis?

� This is a method for identifying performance-critical individual objects.� Where should the R/3 System analysis be performed?

� Only in the production system� Who should perform the R/3 System analysis?

� Developers, system or database administrators, or performance tuners� What are the prerequisites for an R/3 System analysis?

� Absence of basic problems (R/3 Basis, database, or hardware)� Functioning R/3 and database monitors� Representative user activity

208 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 217: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

SAP R/3 Enterprise System analysis enables you to identify performance-criticalobjects in a production R/3 System and to gather the information required for thefurther analysis of these objects. R/3 System analysis is performed reactively.The SAP R/3 Enterprise System to be analyzed will have been in productionfor some time.

The R/3 System analysis may be performed by the developer, the system ordatabase administrator, or by a performance analyst. R/3 System analysisidentifies individual objects and conveys the information required for the analysisof those objects to the developer or performance analyst. The developer improvesthe performance-critical objects and verifies the improvements through an R/3System analysis.

The SAP R/3 Enterprise System and database are configured so that no basicproblems occur that would affect performance. The monitors required for theanalysis are available and are running correctly. Relevant system prerequisitesmust be fulfilled, such as the scheduling of particular background jobs.

Since the R/3 System analysis is only performed on the production system,the available data will be representative. Perform the analysis at times ofrepresentative user activity.

� Name of the object

� Program� Transaction� Function module

� Classification of the object

� Name of developer or person responsible (with organization),application component or project, development class

� Problem type

� Database problem� CPU problem

� Detail information

� Specific to the database or CPU problem

The result of the analysis is a list of performance-critical objects. In addition to thetechnical name of the object, note down any descriptive information.

You also need to characterize the problem as either a database problem or aCPU problem. (Problems caused by poor modeling of business processes arenot treated here.)

2001/Q3 © 2004 SAP AG. All rights reserved. 209

Page 218: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

For database problems, you require the following detail information:

� Text of the SQL statement (especially the WHERE clause)� DDIC information (names of tables or views, technical table attributes,

indexes)� The access strategy of the database optimizer (obtained through the Explain

SQL function)� If possible: The ABAP code that resulted in the SQL statement

For CPU problems, you require the following detail information:

� If possible: Performance-critical program parts or statements� For problems with internal tables, the names of the tables and the relevant

ABAP code

R/3 Workload Analysis

� Criterion

� Number of transaction steps� Total response time, database time, and CPU time

� Aim

� To identify performance-critical objects� Critical threshold

� Larger than acceptable dialog response time per transaction step� Excessively long-running background jobs

� Required information

� Name and classification of the object� Problem characterization

The statistics per transaction step that were explained in the unit on AnalyzingIndividual Objects are written to the performance database with various levels ofaggregation. This makes aggregated data available for various time periods.

Of particular interest is how much an object affected the system over the periodunder consideration. The performance criteria are the number of transaction stepsand the total response time, database time, and CPU time (both the absolute andpercentage time per transaction step).

The aim of the analysis is to identify, classify, and characterize performance-criticalobjects. The values defining the critical threshold may vary considerably. DuringSAP R/3 Enterprise implementation, you should define specific thresholds. Forexample, you may define a maximum of one second for the response time of adialog transaction step, or a maximum of 15 minutes for running backgroundprocesses parallel to dialog processes.

210 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 219: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

Figure 141: R/3 Workload Analysis: Initial Screen

To view the initial screen of the R/3 Workload monitor, from the SAP standardmenu choose Tools→ CCMS→ Control/Monitoring→ Performance menu→ Workload→ Analysis, or use Transaction ST03. From the resulting screen,choose Performance database. In the dialog box that appears, select a server(the database or application server), a time period (for example, previous weeks),and the concrete dates.

The main screen of the Workload Monitor appears, showing an overview of theworkload in the SAP R/3 Enterprise System in the period under consideration.Under the Task types heading, use the buttons to toggle between the various typesof SAP R/3 Enterprise work processes.

The statistics of particular interest are: the number of transaction steps (indicatedas Dialog steps), the average response time (indicated as Av. Response time), theaverage CPU time (indicated as Av. CPU time), and the average database time(indicated as Av. DB req. time). From these figures you can determine whetherthe SAP R/3 Enterprise System has a general performance problem, such asa hardware bottleneck.

You can use the buttons in the tool bar to display the performance databasestatistics in various other views, such as Top time, Transaction profile, Timeprofile, Memory profile, and Accounting profile. These views display the statisticsfor the work process type you selected under the Task types heading.

2001/Q3 © 2004 SAP AG. All rights reserved. 211

Page 220: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Figure 142: R/3 Workload Analysis: Transaction profile

The transaction profile is a list of individual objects with time statistics, sortedaccording to the number of transaction steps. In the initial Workload Monitorscreen, by selecting Total and choosing Transaction profile, you receive thetotal response time for the SAP R/3 Enterprise System in the period underconsideration. For further analysis, you should consider dialog processing andbackground processing separately. Of particular interest are objects that consumea large portion of the total response time.

To analyze a dialog transaction, sort the list according to the average response time(indicated as Response time avg(ms)) and begin analyzing the entries at the top ofthe list. The average response time per transaction step corresponds to the numberof positions and the scope of the transaction�s functionality. Multiple transactionsteps are usually performed during the execution of a transaction.

The average response times for each transaction step are usually higher forbackground transactions than for transactions running in dialog processing mode.A single transaction step may correspond to a program started as a backgroundjob. Particularly performance-critical are reports that run in the background at thesame time as dialog users are working in the system (usually during the day). Thecritical time threshold for a program running as a background job depends on thetype of general usage made of the SAP R/3 Enterprise System.

212 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 221: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

Figure 143: R/3 Workload Analysis: Roadmap

Database SQL Cache Analysis

� Criterion

� Number of logical and physical read accesses� Logical and physical read accesses per data record

� Aim

� To identify performance-critical SQL statements� Critical threshold

� Expensive SQL statement: = 5 % of all logical read accesses = 3 % ofall physical read accesses

� With no appropriate access path: = 5 logical reads per data record� With appropriate access path: = 5 logical reads per data record

� Required information

� Object name, SQL statement, access strategy, ABAP code, names oftables, views, and indexes

� Problem characterization

The database SQL cache is an overview of all SQL statements that were executedby the database in a given time period.

In the cache, you can use threshold values to identify expensive SQL statementsand classify them as having or not having a suitable access path. The indicatedthreshold values only provide a guideline.

2001/Q3 © 2004 SAP AG. All rights reserved. 213

Page 222: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Note the detail information for subsequent use in the individual object analysis.

Figure 144: DB SQL Cache Analysis: Overview (2)

With an appropriate access path:

� The SQL statement reads many data blocks in the database. The statement isexpensive because it transfers many data records from the database to theapplication server. Database performance is satisfactory. The criterion usedis that less than 5 data blocks should be read per data record.

� Expensive SQL statements with a suitable access path are listed at the topof the database SQL cache since they execute frequently. A problem withthe application logic is usually indicated. This problem can be fixed throughchanges to the ABAP code or to the business process.

Unsuitable Access Path:

� The SQL statement reads many data blocks in the database but does nottransfer many data records from the database to the application server.Database performance is not optimal. The criterion used is that more than 5data blocks should be read per data record.

� Expensive SQL statements with no appropriate access paths can be optimizedeither by creating or improving the design of an index, or modifying theABAP code to improve a poorly designed WHERE clause.

214 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 223: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

Figure 145: DB SQL Cache Analysis: Initial Screen

There is a database monitor for each type of database system that is used with SAPR/3 Enterprise System. To call the database monitor, use Transaction code ST04or, from the SAP R/3 Enterprise initial screen, choose Tools→ Administration→Monitor→ Performance→ Database→ Activity.

The initial screen of the database monitor shows an overview of importantparameters:

� Reads (data blocks logically read from the database buffer)� Physical reads (data reads physically read from the hard disk)� Data buffer size and Data buffer quality (size and quality of the database

buffer)� User calls (number of SQL statements sent to the database)� Reads / User calls (ratio of reads to user calls)

The Reads / User calls ratio indicates whether it would be worthwhile to performa Database SQL Cache analysis. If the ratio is larger than 20 (20:1), an analysis isurgently required. The SAP R/3 Enterprise System and the database must havebeen running for several days prior to performing a Database SQL Cache analysis.

To perform a Database SQL Cache analysis, you require the number of data blockslogically read since database startup (Reads) and the number of physically readdata blocks (Physical reads).

2001/Q3 © 2004 SAP AG. All rights reserved. 215

Page 224: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Figure 146: DB SQL Cache Analysis: Suitable Access Path

From the initial screen of the database monitor, choose Detailed Analysis. Toaccess the Database SQL Cache for the respective database systems, choose SQLrequest (Oracle), SQL statement (Informix), Stored proc. stats (MS SQL Server)or Diagnosis monitor (SAP DB).

� Total Execution (Oracle): Number of executions of the SQL statement� Buffer Gets (Oracle): Number of logical reads required for the execution� Records processed (Oracle): Number of transferred (read) data records� Budgets/record (Oracle): Average number of logical reads required for each

data record

You can identify an SQL statement as expensive if it causes more than 5% of alllogical reads, or more than 3% of all physical reads.

Next you should classify the SQL statement as having or not having a suitableaccess path. The diagram shows a Database SQL Cache (for Oracle) sorted by thenumber of logical reads. For each data record, the number of logical reads is lessthan 5. Therefore, you can regard the access path as suitable.

The SQL statement is not able to be optimized with database means (creating ormodifying indexes). Many data records are read (see Records processed), sincethe SQL statement is executed frequently (see Total Executions). An optimizationcan only be attempted in terms of the ABAP coding or the business process level.

216 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 225: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

Figure 147: DB SQL Cache Analysis: Unsuitable Access Path

This example features an SQL statement with more than 5 logical reads per datarecord. You should try to optimize this SQL statement with database means(creating or modifying indexes).

Begin by selecting the line containing the SQL statement or position the cursor onthat line and choose Detail. In the resulting detail view, choose DDIC Info to viewdata on the relevant dictionary object (table or view), choose Explain to view theaccess path, or choose ABAP display to view the source code of the last ABAPprogram that triggered a PREPARE for this SQL statement.

The database SQL cache analysis thus provides you with the followinginformation:

� The text of the SQL statement� The access path� Names of all relevant tables, views, and indexes

Now you must find out the name of the object that called the SQL statement. Todo this, choose ABAP display. This enables you to access the ABAP code thatcaused the last PREPARE for the SQL statement under examination.

2001/Q3 © 2004 SAP AG. All rights reserved. 217

Page 226: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Figure 148: DB SQL Cache Analysis: Where-Used List

To verify that the SQL statement was called from the object revealed with ABAPdisplay, view the where-used list for the relevant dictionary objects as follows:

� Call the ABAP Dictionary (Transaction SE12)� Enter the name of the relevant table or view� Choose Utilities→ Where-used list� Select Programs and Screens and choose Enter� Select the relevant programs and choose Display� Examine the significant parts of the SQL statement, such as the WHERE

clause

If you cannot find the part of the ABAP code that called the SQL statement dueto the large number of entries in the where-used list, use the Snapshot Analysisin the Work Process Overview to search for long-running SQL statements thattarget the respective dictionary object.

218 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 227: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

Figure 149: DB SQL Cache Analysis: Exceptions

Not all SQL statements that are listed in the database SQL cache are called byABAP programs and can be optimized.

ABAP OPEN SQL Statements can be recognized by the upper-case text andnames of variables appearing in inverted commas. All SQL statements originatingfrom OPEN SQL can be optimized using the procedure described in this course.

This course doesn�t cover Native SQL statements, or recursive calls (Oracle)originating from SAP tools or third-party software. These SQL statements canbe recognized by variable names not appearing in inverted commas or parts ofthe text written in lower case.

Figure 150: DB SQL Cache Analysis: Roadmap

2001/Q3 © 2004 SAP AG. All rights reserved. 219

Page 228: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Snapshot Analysis

� Criterion

� Excessively long-running ABAP programs (SQL statements)� Long-lasting database locks

� Aim

� To identify performance-critical objects� Critical threshold

� Larger than acceptable dialog response time per transaction step� Excessively long-running background jobs

� Required information:

� For CPU problems: Object name� For DB problems: Object name, SQL statement, access strategy, ABAP

code, names of tables, views, indexes

The Snapshot analysis provides you with an overview of the processes currentlyrunning in your SAP R/3 Enterprise System. You are looking for long-runningABAP programs that are usually caused by long-running SQL statements ordatabase locks.

Figure 151: Snapshot Analysis: SAP R/3 Enterprise System Work ProcessOverview

To access the local or global SAP R/3 Enterprise System Work Process Overview,use Transaction SM50 or SM66 respectively. Alternatively, from the SAP R/3Enterprise initial screen, choose Tools >> CCMS >> Control/Monitoring >>Performance Menu >> Exceptions/Users >> Active Users >> Processes or (forthe global monitor) All Processes.

220 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 229: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

The Work Process Overview provides an overview of current SAP R/3 Enterprisesystem processing. Look for long-running programs occupying dialog workprocesses. These can be recognized by the fact that they remain in the samework process over several refreshes of the monitor screen. These programscreate considerable system load and must be regarded as performance-critical. Inaddition, look for long-running background programs.

If the columns Action and Table reveal that the performance-critical objects arecausing mainly database accesses, continue your analysis using the DatabaseProcess Monitor or the Database Lock Monitor.

Figure 152: Snapshot Analysis: Database Process Monitor

To access the Database Process Monitor from the initial screen of the DatabaseMonitor, choose Detailed analysis menu→ ORACLE session (or Informix sessionor SQL processes, and so on, as appropriate).

The Database Process Monitor lists the database processes and the correspondingSAP R/3 Enterprise System work processes. The Monitor also shows statusinformation and the text of SQL statements.

If you identify a program with poor database performance in the Work ProcessOverview, note down the SAP R/3 Enterprise System work process ID to locatethe corresponding SQL statement in the Database Process Monitor.

To access a detailed view of the SQL statement, select the line containing thestatement or position the cursor on the line and choose Detail. To find out theexecution plan of an SQL statement, choose Explain.

2001/Q3 © 2004 SAP AG. All rights reserved. 221

Page 230: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit 5: R/3 System Analysis BC490

Figure 153: Snapshot Analysis: Database Lock Monitor

To call the Database Lock Monitor, use Transaction code DB01 or, from the SAPR/3 Enterprise System initial screen, choose Tools→ Administration→ Monitor→ Performance→ Database→ Exclusive lock waits. If there is a lock situation,you can find out the user causing the lock and contact them to release it. If thedatabase lock cannot be released by the user, delete it so that other SAP R/3Enterprise System users can resume work. If you delete the lock, the transactionthat caused it is rolled back and must be repeated.

Database locks are normally released at the end of a transaction step to enable animplicit database commit. If you want data records to be locked for more than onetransaction step, you can do this using SAP R/3 Enterprise System enqueues.

Database locks should be requested as late as possible. After the lock, long-runningSQL statements or internal-table processing should no longer be possible.

Figure 154: Snapshot Analysis: Roadmap

222 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 231: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Lesson: Types of R/3 System Analysis

Lesson Summary

You should now be able to:� Identify individual objects that reduce performance� Determine whether the problem is mainly a database problem or CPU

problem� Identify database locks

2001/Q3 © 2004 SAP AG. All rights reserved. 223

Page 232: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Unit Summary BC490

Unit SummaryYou should now be able to:� Identify individual objects that reduce performance� Determine whether the problem is mainly a database problem or CPU

problem� Identify database locks

224 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 233: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Test Your Knowledge

Test Your Knowledge

1. The is a list of individual objects withtime statistics, sorted according to the number of dialog steps.Fill in the blanks to complete the sentence.

2. Which of the following detail information do you require for CPU problems?Choose the correct answer(s).□ A DDIC information (names of tables or views, technical table

attributes, indexes)□ B If possible: Performance-critical program parts or statements□ C For problems with internal tables, the names of the tables and

the relevant ABAP code□ D If possible: The ABAP code that resulted in the SQL statement

3. The Database Process Monitor only lists down the database processes andthe corresponding SAP R/3 Enterprise work processes.Determine whether this statement is true or false.□ True□ False

2001/Q3 © 2004 SAP AG. All rights reserved. 225

Page 234: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Test Your Knowledge BC490

Answers

1. The Transaction Profile is a list of individual objects with time statistics,sorted according to the number of dialog steps.

Answer: Transaction Profile

2. Which of the following detail information do you require for CPU problems?

Answer: B, C

For CPU problems, you require the following detail information:

� If possible: Performance-critical program parts or statements� For problems with internal tables, the names of the tables and the

relevant ABAP code

3. The Database Process Monitor only lists down the database processes andthe corresponding SAP R/3 Enterprise work processes.

Answer: False

In addition to listing down the database processes and the correspondingSAP R/3 Enterprise work processes, the Database Process Monitor alsoshows the status information and the text of SQL statements.

226 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 235: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Course Summary

Course SummaryYou should now be able to:

� Use SAP�s tools for monitoring ABAP performance� Systematically analyze ABAP performance problems� Solve ABAP performance problems that cause:� High database load (frequent accesses to the database)� High CPU load (frequent accesses to internal tables)

2001/Q3 © 2004 SAP AG. All rights reserved. 227

Page 236: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Course Summary BC490

228 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 237: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Appendix 1Access Costs and Inline Runtime Processing

Figure 155: Estimating the Cost of Single Record Processing

2001/Q3 © 2004 SAP AG. All rights reserved. 229

Page 238: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Appendix 1: Access Costs and Inline Runtime Processing BC490

Figure 156: Estimating the Cost of Mass Processing

Partly sequential processing means processing multiple values of a table.

During mass data processing, in general, single record operations must beperformed m times.

If the WHERE clause refers to an interval in mass processing with MODIFY,DELETE, or LOOP, only the start of this interval must be found (O(log n)) andthen the m values can be processed, therefore, the execution time is O(m+logn). For this type of processing, a sorted table is optimal. Intervals can be usedoptimally when the keys are included with an equal sign (=) in the WHEREclause, beginning with the key that is located at the extreme left of the table.Further keys are added to the WHERE clause, in the order in which they appearin the table from left to right, and are strictly successive (no key is added to theWHERE clause whose immediate successor in the table is not its immediatesuccessor in the WHERE clause).

Partly sequential accesses to a hashed table reduce performance because theyrequire a full table scan. Here, use a sorted table if the access uses the key and thekey is specified in strict succession from the left. Otherwise, you may need to usea standard table and perform a SORT on the required fields.

Index operations cannot be used for hashed tables. For index tables, indexoperations enable a high level of performance and are, therefore, usually preferableto key operations.

230 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 239: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Appendix 1: Access Costs and Inline Runtime Processing

Figure 157: Access Costs: Single Record Access via Key

In the figure, an external table is processed sequentially; and for each entry in theexternal table, the system performs a single record access in the internal table.

With a standard table, the external and internal tables are both processedsequentially. For each value located in the external table, the internal table issearched with a full table scan. The response times increase as the square of thenumber of entries.

For sorted tables, the internal table is accessed with logarithmic effort.

With a hashed table, every table access has a constant response time. This reducesthe runtime even further.

The above statistics show how the new table types can dramatically reduce accesstimes where the internal tables are sorted tables and hashed tables.

2001/Q3 © 2004 SAP AG. All rights reserved. 231

Page 240: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Appendix 1: Access Costs and Inline Runtime Processing BC490

Figure 158: Inline Runtime Measurement GET RUN TIME FIELD

The first time GET RUN TIME FIELD is executed, the field <f> is initialized.Each subsequent time the statement is executed, the system places the runtime inmicroseconds since the first call in field <f>

To measure the duration of a statement sequence, you can create a time t1 beforeexecution and a time t2 after execution using GET RUN TIME FIELD andsubsequently subtract time t1 from time t2.

The measurement results are proportional to the system load and may differ,therefore. Time differences can also be caused, for example, by a data record beingread from the buffer on one occasion, and from the database on another occasion.

Figure 159: Inline Runtime Measurement: Test Framework (1)

232 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 241: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Appendix 1: Access Costs and Inline Runtime Processing

When performing inline measurement, create a test framework program formeasuring particular SQL statement sequences. To do this, create a loopcontaining the statements to be measured. The shorter the runtime of the statementsequence, the more loop runs you should use.

Since system times are included in these measurements, it is advisable to createanother loop that measures system times, and then determine a minimummeasurement to filter out system times as much as possible.

To compare several statement sequences, you can perform the respective loopsconsecutively.

Figure 160: Inline Runtime Measurement: Test Framework (2)

To compare several statement sequences, you can encapsulate them in formroutines and execute the measurement loops for all statement sequences. In thefigure, this process is indicated with form routines f0, f1, and f2.

2001/Q3 © 2004 SAP AG. All rights reserved. 233

Page 242: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Appendix 1: Access Costs and Inline Runtime Processing BC490

Figure 161: Inline Runtime Measurement: ABAP Code (1)

You can use this test framework program to measure the runtime of differentcoding variants.

Use parameters to determine the number of loop runs in accordance with theruntime of the statements.

Figure 162: Inline Runtime Measurement: ABAP Code (2)

In the subroutines f1 and f2, program the variants whose runtime you want tocompare.

Subroutine f0 can contain statements that are common to both variants(initialization, closing processing, and so on). Even the PERFORM requirestime, so to compare the various statements, subtract the runtime of f0 from theruntime for f1 and f2.

234 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 243: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Appendix 1: Access Costs and Inline Runtime Processing

Figure 163: Inline Runtime Measurement: ABAP Code (3)

You use two loop counters to determine the number of test runs.

If the statement sequence you want to measure requires little time, choose a highnumber of repetitions for the inner loop. For example: For MOVE c1 TO c1 , therun time is less than the measurement accuracy of 1 microsecond, therefore thisstatement is frequently repeated and the runtime is subsequently divided by thenumber of repetitions.

You use the outer loop to determine the number of test runs, from which you thentake the minimum runtime. This process should eliminate factors that can makeindividual measurements inaccurate, such as changing the work process.

In addition, subtract the base time (runtime of f0) from the runtimes of f1 and f2.

2001/Q3 © 2004 SAP AG. All rights reserved. 235

Page 244: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Appendix 1: Access Costs and Inline Runtime Processing BC490

Figure 164: Inline Runtime Measurement: ABAP Code (4)

Finally, divide the times f1 and f0 by the number of inner loop runs in_cnt.

The results are realized as an internal table result with two columns: Textspecifying what is to be measured and the measured time in microseconds.

After creating a test framework program, copy it in order to use it, enter thestatement sequences to be measured in the subroutines, enter possible datadefinitions, and provide the internal table with suitable texts (FORM routinefill_result).

Exercise - Additional Material

Figure 165: Exercise - Additional Material

236 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 245: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Appendix 1: Access Costs and Inline Runtime Processing

******************************************************************Program Structure******************************************************************

Data Definitions

AT SELECTION-SCREEN Checking the entered currency (TCURT)

TOP-OF-PAGE Page overview

START-OF-SELECTION PERFORM GET_ELIGABLE_SALES_ITEMS.PERFORM SELECT_DELV_PGI.PERFORM MATCH_ORDERS_TO_PGI.PERFORM DETERMINE_PROCUREMENT_TYPE.SORT ITAB BY PROC_TYPE WERKS MATNR.PERFORM GET_SOURCE_LIST.PERFORM PRINT_ROUTINE.

Figure 166: Exercise - Additional Material

Figure 167: Exercise - Additional Material

2001/Q3 © 2004 SAP AG. All rights reserved. 237

Page 246: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Appendix 1: Access Costs and Inline Runtime Processing BC490

Figure 168: Exercise - Additional Material

Figure 169: Exercise - Additional Material

Figure 170: Exercise - Additional Material

238 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 247: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

IndexAABAP Debugger, 43ABAP Dictionary, 109ABAP JOIN, 125ABAP OPEN SQLStatements, 219

ABAP performance analysis,3

ABAP runtime analysis, 34ACCEPTING DUPLICATEKEYS, 119

Aggregate functions, 114APPEND, 122Application layer, 3ARRAY FETCH, 116Arrow, 4Av. CPU time, 211Av. DB req. time, 211Av. Response time, 211AVG, 114BBasis tables, 121BINARY SEARCH, 185Buffer trace, 21CCALL FUNCTION ... INUPDATE TASK, 119

Call hierarchy, 39CHECK statement, 109Client/server architecture, 3COLLECT, 175Concatenation, 75Cost-based databaseoptimizer, 63

CPU time, 18Critical threshold, 210

DData Block, 70Database Hints, 100Database indexes, 62Database layer, 3Database Lock Monitor, 222Database optimizer, 62Database Process Monitor,221

Database SQL cache, 213Database SQL cache analysis,217

Database time, 18Database view, 124DB Index, 70, 75DB Indexes, 69DB Join, 77DB SQL cache, 63DDIC information, 210DELETE FROM TABLEitab, 119

Dictionary object, 124Dispatcher wait time, 18Driver table, 112EEarlyWatch, 13Enqueue time, 18Enqueue trace, 21Exclamation mark, 4EXEC/REEXEC operation,25

Expensive SQL statements,64, 214

Explain SQL, 26FFETCH operation, 25Field symbols, 183Full Table Scan, 76

2001/Q3 © 2004 SAP AG. All rights reserved. 239

Page 248: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Index BC490

GGoingLive, 13Gross time, 40GROUP BY clause, 114�115Group hit list, 39HHashed table, 173Hashed tables, 188HAVING clause, 115Histogram, 94, 96Hit list, 39Hit list of internal tables, 39Iindex operations, 174Index Range Scan, 72�74Index Unique Scan, 71Individual objects, 12Individual objects analysis, 12INNER JOIN, 121Interference Analysis, 98�99Internal table, 171Kkey operations, 174Key sequence, 171LLEFT OUTER JOIN, 121Line type, 171Load time, 18LOOP ... TRANSPORTING,182

LOOP ... WHERE, 182Mmass processing, 174MODIFY .. .. FROMTABLE, 119

Monitor icon, 4MOVE-CORRESPONDINGstatement, 177

NNested Loop, 78Nested SELECT, 123Net time, 40

OOPEN/REOPEN operation,25

OUTER JOIN, 121PPREPARE operation, 25Presentation layer, 3Primary Index, 69Processing time, 18Production system, 12QQuality assurance system, 12Question mark, 4RR/3 Basis, 13R/3 System analysis, 208R/3 work process, 3RANGES, 113RANGES table, 113Remote Function Calls, 21Reports, 12Response time, 18Response time avg(ms), 212RFC trace, 21Roadmaps, 4Roll-in, 18Roll-out, 18Roll-wait time, 18rsdb/max_blocking_factorparameter, 112

SSAP R/3 Enterprise, 3Secondary index, 194Secondary Index, 69SELECT FOR ALLENTRIES, 111

SELECT... ENDSELECT,109

SELECT...UP TO n ROWS,117

SELECT-OPTIONS, 113Selectivity Analysis, 92�96single record processing, 174Single-object analysis, 12

240 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 249: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

BC490 Index

Snapshot analysis, 220Sort Merge Join, 79Sorted table, 173Sorted tables, 189Spool process, 16SQL Performance Trace, 22SQL Trace, 21Standard table, 173STAT, 17Subquery, 127SUM, 114TTable hit list, 39Table type, 173Tool icon, 4Trace list, 24Transaction profile, 212Transaction ST05, 21

Transaction step, 16transactions, 12TRANSPORTING, 182TRANSPORTING NOFIELDS, 182

UUnsuitable Access Path, 214UPDATE .. SET, 66UPDATE ... SET statement,118

UPDATE dbtab FROMTABLE itab, 119

WWHERE clause, 108WITH KEY, 185WITH TABLE KEY, 185Work Process Overview, 221

2001/Q3 © 2004 SAP AG. All rights reserved. 241

Page 250: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

Index BC490

242 © 2004 SAP AG. All rights reserved. 2001/Q3

Page 251: ABAP Performance Tuning-BC490 - 2001-Q3 - A4

FeedbackSAP AG has made every effort in the preparation of this course to ensure theaccuracy and completeness of the materials. If you have any corrections orsuggestions for improvement, please record them in the appropriate place in thecourse evaluation.

2001/Q3 © 2004 SAP AG. All rights reserved. 243