Performance, SQL Trace and Profiling

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Sooner or later a program that worked fine with ten test rows meets ten million rows in production and becomes slow. This page explains the two halves of that problem. The first half is prevention: a short list of rules for reading from the database and for working with internal tables that keep most programs fast from the start. The second half is diagnosis: how to measure a slow program instead of guessing, with the SQL trace (which shows every database statement), the ABAP Profiler and the runtime analysis (which show where the time goes in the ABAP code), and the tools that watch a whole system over days. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). The rules apply to ABAP Cloud and to classic Standard ABAP alike. The ADT tools (the SQL trace and the ABAP Profiler) are used from the Eclipse editor. The SAP GUI transactions (ST05, SAT, ST12, SQLM, SWLT, ST10, S_MEMORY_INSPECTOR) belong to classic Standard ABAP on premise and in Private Edition, where SAP GUI is available.

Before you read

Key terms

  • ABAP Profiler: the ADT tool that records how long each part of a running ABAP program takes.

  • SQL trace: a recording of every database statement a program sends, with its duration and parameters.

  • Hot spot: a statement or call that uses a large share of the total run time.

  • Table buffering: keeping rows of a rarely changed database table in the memory of the application server, so a read does not go to the database.

  • Secondary index: an extra index on a database table that speeds up reads on columns other than the primary key.

  • Code pushdown: moving calculation from the ABAP program to the database.

  • SQL Monitor: a tool that records, in a running system and over a long time, which ABAP SQL statements are executed and how often.

Measure first, then change

Performance work has one rule that comes before all others: do not tune what you have not measured. A program may feel slow because of one expensive database statement, because of a loop that reads the database a thousand times, because of a slow lookup in an internal table, or because the whole system is overloaded. Each cause has a different cure, and a guess usually fixes the wrong one. The Runtime Analysis documentation says the same for a system-wide slowdown: if everything in the system is slow, analysing one program will not help, and monitors such as the workload monitor and the database monitor are the first place to look.

The usual order is therefore: notice that something is slow, find out whether the time is spent in the database or in ABAP code, find the one statement or call that costs most, change it, and measure again. The tools in this page fit into that order.

flowchart TD A[A program or transaction is slow] --> B{Is the whole system slow?} B -- Yes --> C[System monitors: workload, database, operating system] B -- No --> D[Trace one run with the ABAP Profiler in ADT, or SAT] D --> E{Where is the run time?} E -- Database --> F[SQL trace in ADT or ST05: find the expensive statement] E -- ABAP code --> G[Hit list and call tree: find the hot spot] E -- Memory --> H[Memory Inspector] F --> I[Apply the ABAP SQL rules: fewer rows, columns and reads] G --> J[Apply the internal table rules: right kind, key and statement] I --> K[Trace again and compare] J --> K

The ABAP SQL performance rules

Most slow ABAP programs are slow because of the database access, and the Keyword Documentation gathers the advice in five rules. It adds that how much each rule matters depends on the data, on the evaluations needed and on the database system, so the rules have to be weighed case by case.

  1. Keep the number of hits low. Use a specific WHERE condition so that only the rows you need leave the database. A row that is read and then thrown away in the program was moved for nothing.

  2. Keep the data volume low. Name the columns you need instead of reading every column, or read from a view that has only those columns. Aggregate expressions with a grouping, such as a sum per status, reduce the data because the database aggregates before it sends anything.

  3. Keep the number of reads low. Use one mass operation instead of many single operations. Do not place an ABAP SQL statement inside a loop; use a join, a view or a subquery to read several tables in one statement.

  4. Use local buffers. Do not read the same data twice. Buffering a rarely changed table can save a lot of time, and data that must be sorted in several orders is sorted in the ABAP program.

  5. Search efficiently with indexes. Create and use a secondary index where it improves the selection.

The Performance Notes cheat sheet of the SAP-samples repository turns the rules into concrete statements: a WHERE clause instead of a LOOP that filters, SELECT SINGLE when only one row is needed, UP TO n ROWS to limit a result, UPDATE ... SET for a set-based change instead of one update per row, and one MODIFY from an internal table instead of one per row. It also warns that FOR ALL ENTRIES reads all rows if its driver table is empty, so the table has to be checked first, and it prefers a join or WHERE EXISTS to that clause. Static SQL (names written in the statement) performs better than dynamic SQL (names in character fields).

Rules 1 to 3 in a program you can run

The listing below runs the first three rules on five claim rows and counts what moves. It first reads all rows and filters in ABAP, then lets the database filter. It then reads three claims with one SELECT SINGLE per claim in a loop, and finally reads the same three with a single SELECT and a range table. The lab table is a reduced version of the running example: only claim_id, status and amount. The listing runs in the local playground and prints the four lines below it. The statement counts are the number of SELECT statements the program itself issued, not a time, so the output is the same on every run.

REPORT zperf.

TYPES: BEGIN OF ty_claim,
         claim_id TYPE c LENGTH 10,
         status   TYPE c LENGTH 1,
         amount   TYPE i,
       END OF ty_claim.
TYPES ty_claims TYPE STANDARD TABLE OF ty_claim WITH EMPTY KEY.
TYPES ty_ids TYPE STANDARD TABLE OF zexp_claim-claim_id WITH EMPTY KEY.
TYPES ty_id_range TYPE RANGE OF zexp_claim-claim_id.

DATA selects TYPE i.

INSERT zexp_claim FROM TABLE @( VALUE ty_claims(
  ( claim_id = 'C000000001' status = 'A' amount = 120 )
  ( claim_id = 'C000000002' status = 'S' amount = 45 )
  ( claim_id = 'C000000003' status = 'A' amount = 300 )
  ( claim_id = 'C000000004' status = 'R' amount = 80 )
  ( claim_id = 'C000000005' status = 'S' amount = 64 ) ) ).

" Rule 1, slow: read every row, then filter in ABAP
SELECT claim_id, status, amount FROM zexp_claim INTO TABLE @DATA(everything).
DATA(rows_moved_1) = lines( everything ).
DELETE everything WHERE status <> 'S'.
WRITE / |filter in ABAP: moved { rows_moved_1 } rows, kept { lines( everything ) }|.

" Rule 1, fast: let the database filter
SELECT claim_id, status, amount FROM zexp_claim WHERE status = 'S' INTO TABLE @DATA(submitted).
WRITE / |WHERE in SQL:    moved { lines( submitted ) } rows, kept { lines( submitted ) }|.

" Rule 3, slow: one SELECT per id inside a loop
DATA(ids) = VALUE ty_ids( ( 'C000000001' ) ( 'C000000003' ) ( 'C000000005' ) ).
DATA total_loop TYPE i.
selects = 0.
LOOP AT ids INTO DATA(id).
  SELECT SINGLE amount FROM zexp_claim WHERE claim_id = @id INTO @DATA(one_amount).
  selects = selects + 1.
  total_loop = total_loop + one_amount.
ENDLOOP.
WRITE / |SELECT in loop:  { selects } statements, total { total_loop }|.

" Rule 3, fast: one SELECT for the whole list, using a range table
DATA(id_range) = VALUE ty_id_range(
  FOR id_value IN ids ( sign = 'I' option = 'EQ' low = id_value ) ).
DATA total_one TYPE i.
selects = 0.
SELECT amount FROM zexp_claim WHERE claim_id IN @id_range INTO TABLE @DATA(amounts).
selects = selects + 1.
LOOP AT amounts INTO DATA(a).
  total_one = total_one + a-amount.
ENDLOOP.
WRITE / |one SELECT:      { selects } statement, total { total_one }|.

Output of the run:

filter in ABAP: moved 5 rows, kept 2
WHERE in SQL:    moved 2 rows, kept 2
SELECT in loop:  3 statements, total 484
one SELECT:      1 statement, total 484

Both ways give the same answer, which is the point: the slow version is not wrong, it is wasteful. With five rows the difference is invisible. With a loop over a hundred thousand claims, the first way moves every row across the network and the loop sends a hundred thousand statements, each with its own round trip to the database. The lab database is a small in-memory SQLite database, so it cannot show the time difference, and it supports no GROUP BY; the aggregate example in the next section therefore requires an SAP system.

Rules 1 to 3 on the full running example

On the full ZEXP_CLAIM table the same ideas look like this. The first listing reads the items of every submitted claim with a loop, which sends one statement per claim. The second reads the same data with one join. zexp_item is the item table of the running example with the fields claim_id, item_no, category and amount, as on the page about joins. The third listing lets the database add up the amounts per currency and status, so that only a handful of rows travels, instead of every claim. The listings need an SAP system, with the Dictionary tables of the running example; they were not run here.

" Slow: one statement per claim (rule 3 broken)
SELECT claim_id FROM zexp_claim WHERE status = 'S' INTO TABLE @DATA(claim_ids).
LOOP AT claim_ids INTO DATA(claim).
  SELECT item_no, category, amount
    FROM zexp_item
    WHERE claim_id = @claim-claim_id
    INTO TABLE @DATA(items).
  " ... use the items of one claim ...
ENDLOOP.

" Better: one statement for all submitted claims
SELECT c~claim_id, i~item_no, i~category, i~amount
  FROM zexp_claim AS c
  INNER JOIN zexp_item AS i ON i~claim_id = c~claim_id
  WHERE c~status = 'S'
  INTO TABLE @DATA(all_items).

" Fewer rows and columns still (rules 1 and 2): aggregate in the database
SELECT currency_code, status, SUM( total_amount ) AS total
  FROM zexp_claim
  GROUP BY currency_code, status
  INTO TABLE @DATA(totals).

This listing requires an SAP system; not run here.

Table buffering

Table buffering is rule 4 in practice. When a DDIC database table, a DDIC view or a CDS view entity is marked as buffered, the ABAP system keeps its rows in a table buffer in the shared memory of the current application server instance. The next read of a row that is already in the buffer does not touch the database at all. The Keyword Documentation says buffering generally improves performance by factors of between 50 and 500, and names the typical candidates: customizing tables and system tables, and in some cases master-data-like tables. Transactional tables that change all the time, such as the claims of the running example, are poor candidates, because every write invalidates the buffer entry and, by default, the next five reads of that entry go to the database anyway.

Whether and how a table is buffered is a technical setting of the table, not something the program asks for. The buffering type decides which rows are loaded when one row is read: single entries, a generic area defined by the leading key fields, or the whole table. The SELECT statement then uses the buffer by itself, as long as the statement is one that the buffer can serve. There is a catch that matters for performance: some statements silently bypass the buffer and go to the database. The restrictions page names, among others, a statement that the ABAP SQL in-memory engine does not support, a WHERE condition on a single-record-buffered table that does not name all key fields with equality joined by AND, and every JOIN on a database table, which currently always bypasses the buffer. A buffered table that is read through a join is therefore read from the database each time.

The opposite need exists too: sometimes the current database content matters more than speed. BYPASSING BUFFER forces the read to the database. It belongs to the additions of SELECT that are placed at the end of the statement and introduced with OPTIONS:

SELECT SINGLE status
  FROM zexp_claim
  WHERE claim_id = 'C000000001'
  INTO @DATA(current_status)
  OPTIONS BYPASSING BUFFER.

The statement shows the position of the addition and requires an SAP system; not run here. The running example’s claim table is not buffered, so in a real system the addition would have no effect on it. The Keyword Documentation advises always writing the addition when the buffer must be bypassed, because relying on the implicit bypass is not enough.

Rules for internal tables

After the data has arrived, the ABAP program works on it in internal tables, and the cheat sheet has a second group of rules for that. They follow from how the table kinds work, which is explained on the page about internal tables.

  • Choose the table kind by the way the table is used: a standard table for small amounts of data and sequential processing, a hashed table for large, mostly read tables that are accessed by the complete key.

  • Read with the key whenever you can. A hashed table needs the complete key, a sorted table can use the leading part of its key, and a read on other fields searches line by line.

  • Prefer a secondary key to BINARY SEARCH on a standard table, which needs a previous SORT to be correct. Secondary keys cost administration and slow down changes, so they pay off for large tables that are read often and changed rarely.

  • Put the condition in LOOP AT ... WHERE instead of testing it with IF inside the loop.

  • Read only what you need: TRANSPORTING NO FIELDS when only the existence of a row matters, and field symbols or data references instead of copying each row into a work area, especially for tables whose rows contain other tables.

  • Give SORT an explicit BY list instead of the default key.

  • Do not repeat a table expression for the same row; assign the row to a field symbol once.

  • When you must write a READ TABLE with a WHERE condition, the cheat sheet notes that the pragma ##read_where_ok suppresses the warning that the code check gives for it.

Finding the slow part with the ABAP Profiler in ADT

The ABAP Profiler analyses the run time of ABAP programs, transactions, function modules, global classes and Web Dynpro applications. Its result is called an ABAP trace. SAP describes it as the successor of the Runtime Analysis toolset (transaction SAT) and recommends it from SAP NetWeaver 7.4 SP2 on; below that, SAT in the embedded SAP GUI is the alternative. From the trace you can find the hot spots to concentrate your effort on, excessive use of modularisation units such as methods that are called far more often than needed, and CPU-intensive parts, and you can follow the flow of the program. SAP notes that, for comparing program flow, the profiler can be faster than the ABAP Debugger.

Before you profile, run the program once. The first run pays for compilation and for filling caches, and an ABAP trace of that run would blame costs that disappear afterwards. There are several ways to start a trace: from the source editor or the Project Explorer for a program that can start directly, through a wizard where you pick any development object, through a trace request for code that is only run by a transaction, an HTTP request, an RFC call or a background process, through a profile configuration, or from the ABAP Debugger.

The trace appears in the ABAP Traces view. A double-click opens its overview, which has three parts:

  • the general data: title, trace file name, date, server, user, size and the aggregation mode (None, Call Stack or Call Position);

  • the runtime distribution: the overall time, the time in ABAP code (not counting system programs), the time in the database and the time in system programs;

  • the links to the analysis tools.

The runtime distribution is the first answer to the question "database or ABAP code?": a trace that is mostly database time points to the SQL rules, one that is mostly ABAP time points to loops and internal table access. The Aggregated Call Tree then adds up all executions that came by the same call path into one entry and shows how often each ran (the Executions column) and the total time, which finds a method that runs a hundred thousand times from one caller. Aggregating by call stack or call position keeps a trace small and is the right start for a performance question; an unaggregated trace records every event and is for following the flow.

This part requires an ADT project connected to an SAP system; not run here.

The SQL trace

An SQL trace records the statements that really reached the database: how the ABAP SQL statement was translated to the SQL of the database, with which parameters, how long it took, where the program committed and where it repeated the same read. A loop of single SELECT statements is easy to see in it, because the same statement appears again and again.

ADT offers two ways to take one.

  • With the Technical Monitoring Cockpit. In the Project Explorer choose SQL Trace from the context menu of the ABAP project, and use Activate in the dialog. Run the program, choose Deactivate, and choose View Trace Directory, which opens the SQL trace analysis in your browser. SAP recommends deactivating the trace afterwards, otherwise data is collected all the time. The browser app is organised from left to right: Trace Directory (by default the traces of your user from the last 24 hours), Trace Records (every statement in time order, which you can sort by duration or filter by statement text), SQL Statement (the statement and its place in the ABAP source), and Prepared Plan and Executed Plan (the access plan, with a PlanViz file to download for the executed plan). SAP states that this way is supported from SAP S/4HANA 1909 FPS00.

  • Inside an ABAP trace. Switch on Enable SQL trace in the trace preferences before you start the profiler. Afterwards open the trace, and follow the SQL Trace link of the analysis tools section; the list appears in the embedded SAP GUI.

In a classic system the same recording is made with transaction ST05, the performance trace, whose SQL trace you switch on, run the program, switch off and display. The SAP documentation says the SQL trace functions in ADT are similar to those of ST05. The performance trace of ST05 has further trace types beyond the SQL trace: an enqueue trace for locks, an RFC trace and a buffer trace for table buffer access.

To read an SQL trace, look for three things: statements that repeat with only a parameter changing (a read inside a loop), statements with a long duration (an expensive access plan, perhaps a missing index), and statements that return far more rows or columns than the program uses.

This part requires an SAP system; not run here.

The classic transactions

On a system where you work in SAP GUI, the same questions are answered with transactions, and an older book will teach only these.

  • SAT, the ABAP Runtime Analysis. Start it with transaction SAT or from the menu System, Utilities, Runtime Analysis, Execute. It replaced the older SE30. SAP’s guide for a performance analysis chooses a variant whose aggregation is set to Per Call Position, so that ten calls of a function module in a loop become one record with ten hits and the summed time. The Evaluate tab then shows the default desktop with the Profile and the Hit List tools. The hit list is sorted by default by net runtime, the time spent in an operation without the time of the traced operations it calls, and the entries at the top, especially those with many hits, are the ones to examine.

  • ST05, the performance trace, described above.

  • ST12, the single transaction analysis. It combines the ABAP trace of SAT and the SQL trace of ST05 in one transaction. The SAP support pages that describe it state that ST12 is not officially documented or supported and exists only in English, so use it when you find it in a system or a colleague recommends it, and prefer the documented tools for your own work.

  • SQLM and SWLT, SQL Monitor and SQL Performance Tuning Worklist. A trace shows one run. The SQL Monitor, started with transaction SQLM, records the ABAP SQL statements of a running system for as long as you want, even days or weeks, so that you can see how often a table is read and through which access paths. The SQL Performance Tuning Worklist (transaction SWLT) combines that runtime data, which normally comes from the production system, with static check results from a test system and builds a ranked worklist. The worklist always aggregates the records by source code position. To start SWLT you need at least display authorisation for the authorization object S_DEVELOP with activity 03, and for the full function the values SQMA (administration) and SQMD (display of data) of S_ADMI_FCD. SAP recommends the predefined Code Inspector variant PERFORMANCE_DB for the static checks. In ADT the same data opens in the SQL Monitor view, and the SAP GUI transaction for displaying it is SQLMD.

  • ST10, the table call statistics. It shows how often buffered and unbuffered tables were accessed, how much data was transferred and how long the calls took, which is the check that a table you think is buffered really is read from the buffer.

  • S_MEMORY_INSPECTOR, the Memory Inspector. When the problem is memory, the Memory Inspector analyses memory snapshots taken from a running program. It comes as a standalone transaction and as a tool in the ABAP Debugger.

All of these transactions require an SAP system; not run here.

Common mistakes

  • Tuning without a trace. A change made on a guess may cost readability and gain nothing. Trace, change, trace again.

  • Profiling the first run. Compilation and cold caches distort it; run the program once before the trace.

  • Measuring with too little data. A test table with a few rows hides every cost that depends on volume. Measure on data of production size, or at least look at the number of statements, which does not depend on volume.

  • Forgetting to deactivate the SQL trace. An active trace keeps collecting data.

  • A SELECT inside a LOOP. The most common cause of a program that gets slower in proportion to its data.

  • FOR ALL ENTRIES with an empty driver table. It reads all rows; check the table first, or use a join.

  • Assuming a join uses the buffer. A join on a database table bypasses the table buffer.

  • Adding a secondary key or index everywhere. Both speed up reads and slow down changes.

What older books show, and what has changed

The book Complete ABAP (1st edition, 2016) has a chapter on testing and analysis tools that teaches the performance trace ST05 with its SQL, enqueue, RFC and buffer traces, the runtime analysis SAT (the successor of SE30) with its hit list, the table call statistics ST10, the Memory Inspector and the single transaction analysis ST12, all through SAP GUI. That material is still correct for a classic system. What the book does not show, because it came later or sits outside its subject, is the ADT side: the SQL trace opened in the Technical Monitoring Cockpit, the ABAP Profiler with its aggregated call tree, and the SQL Monitor view. It also does not cover the SQL Monitor and the SQL Performance Tuning Worklist for finding expensive statements in a production system, nor the table buffering restrictions of the current ABAP SQL (for example that a join always bypasses the buffer).

Source: SAP PRESS: Complete ABAP (the publisher page lists the current edition; the copy consulted is the 1st edition)

Summary

  • A slow program is fixed by measuring, not by guessing: find out whether the time goes to the database, to ABAP code or to memory, then change the one thing that costs most and measure again.

  • The ABAP SQL rules are: few rows, few columns, few reads, local buffers and useful indexes. A SELECT inside a loop and filtering in the program instead of in WHERE are the usual faults.

  • Table buffering saves database reads for rarely changed tables, but a statement the buffer cannot serve, and every join on a database table, goes to the database; OPTIONS BYPASSING BUFFER forces that on purpose.

  • The ABAP Profiler and the SQL trace in ADT are the tools for a single run; ST05, SAT and ST12 are their classic counterparts, and SQLM with SWLT watches a whole system over time.

  • The listing that runs in the local playground shows the effect on the number of statements. The tools themselves need an SAP system.