SAP Business One performance - featured image for slow query diagnosis tutorial

Publications

SAP Business One Performance: Diagnose and Fix Slow Queries with SQL

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

The SAP Business One performance It rarely degrades all at once. It degrades little by little, until on a closing Monday someone says the phrase every IT manager knows: «the system is slow.» Nobody knows exactly what that means. Billing says opening a document takes forty seconds. Accounting says the general ledger won't load. Management says the ERP «can't take it anymore.» And you, without data, end up arguing about perceptions instead of facts.

I have seen that conversation dozens of times. In almost every case, the initial diagnosis was wrong. It wasn't the server. It wasn't the network. It wasn't «SAP being slow.» It was a poorly written query running eight hundred times a day, a table with twelve years of unpurged history, or a formatted search triggering on every single key the user pressed.

Therefore, this tutorial is not about buying more hardware. It is about measuring. Next, you are going to build five executable diagnostics—each in a SQL Server and SAP HANA version—that turn «the system is slow» into a prioritized list of concrete causes with names, times, and responsible parties.

SAP Business One performance - server infrastructure where the ERP database runs
The hardware is almost never to blame. The evidence is in the database, not in the rack.

When the ERP «is slow»: one symptom, three different causes

The perceived slowness in SAP Business One almost always stems from one of three families of causes, and each requires a different response.

Cause 1: expensive queries. Reports, views, and formatted searches that scan entire tables without a date filter. They are cheap to fix and expensive to ignore, because they run thousands of times a day.

Cause 2: accumulated volume. Tables such as OINM, JDT1, or ADOC grow without limit. In addition, the change log duplicates history that no one consults. Consequently, operations that ran well with two years of data crawl with ten.

Cause 3: Containment. A user leaves a payment wizard, a counting process, or an unconfirmed transaction open. As a result, twenty others are left waiting for a lock that no one sees.

However, all three get confused with each other from the user's seat. That's why you need to measure them separately.

Why measuring SAP Business One performance changes the conversation

There is a business reason behind this exercise, and it is not technical. When slowness is not measured, the discussion is resolved by hierarchy: whoever complains the loudest or has the biggest budget wins. Therefore, you end up buying servers that solve nothing.

Once the slowness is quantified, the discussion is settled based on impact. You can say, «This query consumes 38% of the database’s total time, runs 1,200 times a day, and costs the company eleven minutes of wait time daily.» That’s no longer a complaint. It’s a business case with a calculable return.

Additionally, measurement protects you. When the partner proposes a migration or a license expansion «for performance reasons,» you arrive with your own evidence. This way, you make decisions based on knowledge rather than faith.

Prerequisites before running diagnostics

  • Read access to system views. In SQL Server you need the permission VIEW SERVER STATE. In SAP HANA you need the role MONITORING or equivalent privileges on the schema SYS.
  • Query tool. SQL Server Management Studio or SAP HANA Studio / Database Explorer. The SAP Business One Query Manager no It works for these queries: blocks access to system views.
  • Observation window. Run diagnostics after a full day of operation, never after restarting the service. Statistics are cleared with every restart.
  • A test environment. None of these queries modify data. However, any resulting corrective action must first be validated on a copy.

Step-by-step tutorial: five performance diagnostics

Step 1: identify the queries that actually cost money

Start from the end: which statements consume the most time. Not the ones they look like slow ones, but the ones that add the most milliseconds per day. A 300 ms query executed 5,000 times does more damage than a 40-second report that is run once a month.

SQL Server

-- Top 20 queries by average execution time
SELECT TOP 20
    qs.execution_count                                   AS Executions,
    qs.total_elapsed_time / 1000                         AS TotalMs,
    (qs.total_elapsed_time / qs.execution_count) / 1000  AS AverageMs,
    qs.total_logical_reads / qs.execution_count          AS AverageReads,
    qs.last_execution_time                               AS LastExecution,
    SUBSTRING(st.text, (qs.statement_start_offset / 2) + 1,
        ((CASE qs.statement_end_offset
              WHEN -1 THEN DATALENGTH(st.text)
              ELSE qs.statement_end_offset
          END - qs.statement_start_offset) / 2) + 1)     AS Statement
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
WHERE st.text NOT LIKE '%dm_exec%'
ORDER BY AverageMs DESC;

SAP HANA

-- Top 20 statements by average time in the cache
SELECT
    "STATEMENT_STRING"                          AS "Statement",
    "EXECUTION_COUNT"                           AS "Executions",
    ROUND("TOTAL_EXECUTION_TIME" / 1000, 0)     AS "TotalMs",
    ROUND("AVG_EXECUTION_TIME" / 1000, 0)       AS "AverageMs",
    "TOTAL_RESULT_RECORD_COUNT"                 AS "RowsReturned",
    "LAST_EXECUTION_TIMESTAMP"                  AS "LastExecution"
FROM "SYS"."M_SQL_PLAN_CACHE"
WHERE "EXECUTION_COUNT" > 10
  AND "STATEMENT_STRING" NOT LIKE '%M_SQL_PLAN_CACHE%'
ORDER BY "AVG_EXECUTION_TIME" DESC
LIMIT 20;

How to read the result. Multiply mentally MsPromedio by Executions. That figure, not the isolated average, is your real priority. Also, check Average ReadingsValues over one hundred thousand indicate that the query performs full table scans instead of using indexes.

For example, if a sentence appears in the top with SELECT Regarding the OINV without a date clause, you are almost certainly looking at a formatted search or a poorly parameterized Crystal report. That is your first fix.

Step 2: measure the actual weight of your boards

The second diagnosis answers a simple question: where is the volume? In SAP Business One, the answer is usually surprising, because the heaviest tables are almost never the ones the business mentions.

SQL Server

-- Disk size and number of rows per table
SELECT TOP 25
    t.name                                                        AS Table,
    SUM(p.row_count)                                              AS Rows,
    CAST(SUM(p.used_page_count) * 8.0 / 1024 AS DECIMAL(12, 2))   AS MB
FROM sys.dm_db_partition_stats p
INNER JOIN sys.tables t ON t.object_id = p.object_id
WHERE p.index_id IN (0, 1)
GROUP BY t.name
ORDER BY MB DESC;

SAP HANA

-- Memory used and number of rows per columnar table
SELECT
    "TABLE_NAME"                                  AS "Table",
    "RECORD_COUNT"                                AS "Rows",
    ROUND("MEMORY_SIZE_IN_TOTAL" / 1048576, 2)    AS "MB_Memory"
FROM "SYS"."M_CS_TABLES"
WHERE "SCHEMA_NAME" = CURRENT_SCHEMA
ORDER BY "MEMORY_SIZE_IN_TOTAL" DESC
LIMIT 25;

Pay attention to three names. OINM track every inventory movement from day one. JDT1 Save every accounting line. ADOC and their sister tables store the document version history, and they grow especially fast if the change log is active for all objects.

However, do not confuse size with a problem. A large table is only a problem if your queries do a full scan of it. Therefore, this step is always interpreted together with Step 1.

Step 3: detect missing indexes and sequential accesses

SQL Server records which indexes would have helped the queries it executed. SAP HANA does not expose that metric in the same way, because its columnar engine works differently. Consequently, for HANA we use the expensive statements trace.

SQL Server

-- Indexes the engine would have liked to have
SELECT TOP 15
    ROUND(s.avg_total_user_cost * s.avg_user_impact
          * (s.user_seeks + s.user_scans), 0)  AS EstimatedImpact,
    d.statement                                AS Table,
    ISNULL(d.equality_columns, '')             AS EqualityColumns,
    ISNULL(d.inequality_columns, '')           AS Range_Columns,
    ISNULL(d.included_columns, '')             AS Included_Columns,
    s.user_seeks                               AS Seeks
FROM sys.dm_db_missing_index_group_stats s
INNER JOIN sys.dm_db_missing_index_groups g
        ON s.group_handle = g.index_group_handle
INNER JOIN sys.dm_db_missing_index_details d
        ON g.index_handle = d.index_handle
WHERE d.database_id = DB_ID()
ORDER BY EstimatedImpact DESC;

SAP HANA

-- Statements that took longer than 1 second
-- Requires expensive statement tracing to be enabled
SELECT
    "APP_USER"                              AS "User",
    "START_TIME"                            AS "Start",
    ROUND("DURATION_MICROSEC" / 1000, 0)    AS "Duration (ms)",
    "RECORDS"                               AS "Records Read",
    "STATEMENT_STRING"                      AS "Statement"
FROM "SYS"."M_EXPENSIVE_STATEMENTS"
WHERE "DURATION_MICROSEC" > 1000000
ORDER BY "DURATION_MICROSEC" DESC
LIMIT 15;

Critical warning. Do not create indexes on standard SAP Business One tables on your own. SAP defines specific rules regarding this —Notes 896891 and 1376447 are the usual reference— and manual indexes are removed during every upgrade. Therefore, always validate with your partner and maintain a versioned script that allows recreating them after each update.

SAP Business One performance - connections and dependencies that explain session locks
Locks are invisible to the user: they only perceive that «the system has crashed».

Step 4: Discover locks and hung sessions

This is the diagnosis that changes the perception of the business the fastest. When twenty people are waiting for a single open transaction, the problem is not capacity: it is operational discipline.

SQL Server

-- Active sessions, waits, and blocking chain
SELECT
    r.session_id            AS Session,
    r.blocking_session_id   AS BlockedBy,
    r.status                AS Status,
    r.wait_type             AS WaitType,
    r.wait_time / 1000      AS WaitSeconds,
    s.login_name            AS UserLogin,
    s.host_name             AS HostName,
    t.text                  AS Statement
FROM sys.dm_exec_requests r
INNER JOIN sys.dm_exec_sessions s ON s.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.session_id  @@SPID
ORDER BY r.wait_time DESC;

SAP HANA

-- Blocked transactions and who blocks them
SELECT
    b."BLOCKED_CONNECTION_ID"        AS "BlockedConnection",
    b."LOCK_OWNER_CONNECTION_ID"     AS "BlockingConnection",
    b."WAITING_SCHEMA_NAME"          AS "Schema",
    b."WAITING_TABLE_NAME"           AS "Table",
    b."LOCK_TYPE"                    AS "LockType",
    SECONDS_BETWEEN(b."BLOCKED_TIME", CURRENT_TIMESTAMP) AS "Wait Seconds",
    c."USER_NAME"                    AS "User",
    c."CLIENT_HOST"                  AS "Host"
FROM "SYS"."M_BLOCKED_TRANSACTIONS" b
LEFT JOIN "SYS"."M_CONNECTIONS" c
       ON c."CONNECTION_ID" = b."LOCK_OWNER_CONNECTION_ID"
ORDER BY "WaitTime" DESC;

Run this query during peak operations, not at seven in the evening. Also, save the result: the column Team It will tell you whether the block is caused by a user, an integration, or a poorly programmed automated process.

Step 5: quantify the accumulated history in your transactional tables

The latest diagnosis translates volume into business language: how years of history you are carrying in each critical table. With that data, you can discuss archiving, partitioning, or purging with arguments.

SQL Server

-- Age and volume of key SAP B1 transaction tables
SELECT 'OINM - Inventory Movements' AS Table,
       COUNT(*)                                        AS Rows,
       MIN(T0.DocDate)                                 AS EarliestDate,
       DATEDIFF(DAY, MIN(T0.DocDate), GETDATE())       AS DaysOfHistory
FROM OINM T0
UNION ALL
SELECT 'JDT1 - Accounting Entry Lines',
       COUNT(*), MIN(T1.RefDate),
       DATEDIFF(DAY, MIN(T1.RefDate), GETDATE())
FROM JDT1 T1
UNION ALL
SELECT 'ADOC - Document History',
       COUNT(*), MIN(T2.DocDate),
       DATEDIFF(DAY, MIN(T2.DocDate), GETDATE())
FROM ADOC T2
UNION ALL
SELECT 'AITM - Item Master Data History',
       COUNT(*), MIN(T3.UpdateDate),
       DATEDIFF(DAY, MIN(T3.UpdateDate), GETDATE())
FROM AITM T3
ORDER BY Rows DESC;

SAP HANA

-- Age and volume of key SAP B1 transactional tables
SELECT 'OINM - Inventory Movements' AS "Table",
       COUNT(*)                                            AS "Rows",
       MIN(T0."DocDate")                                   AS "OldestDate",
       DAYS_BETWEEN(MIN(T0."DocDate"), CURRENT_DATE)       AS "DaysOfHistory"
FROM OINM T0
UNION ALL
SELECT 'JDT1 - Accounting Entry Lines',
       COUNT(*), MIN(T1."RefDate"),
       DAYS_BETWEEN(MIN(T1."RefDate"), CURRENT_DATE)
FROM JDT1 T1
UNION ALL
SELECT 'ADOC - Document History',
       COUNT(*), MIN(T2."DocDate"),
       DAYS_BETWEEN(MIN(T2."DocDate"), CURRENT_DATE)
FROM ADOC T2
UNION ALL
SELECT 'AITM - Item Master Data History',
       COUNT(*), MIN(T3."UpdateDate"),
       DAYS_BETWEEN(MIN(T3."UpdateDate"), CURRENT_DATE)
FROM AITM T3
ORDER BY "Rows" DESC;

If AITM has more rows than OITM multiplied by twenty, your change log is capturing irrelevant modifications. Therefore, check which objects have active logging and adjust it to what you actually audit.

Variations and real-world use cases

Weekly performance dashboard. Turn Step 1 into a view and schedule it to run every Monday. This way you get a trend instead of isolated snapshots. The technique is detailed in reusable SQL views in SAP Business One.

Diagnostics by user. add s.login_name Go to Step 4 and group them. You'll often find that a single integration accounts for 70% of the wait times.

Date-parameterized report. If you want to deliver Step 5 to management without giving access to the database, wrap it in a parameterized query following the method of parameterized queries.

Before and after an upgrade. Run the five diagnostics one week before and one week after each version update. As a result, you will have objective evidence of the upgrade's actual impact, not the vendor's promise.

SAP Business One performance - server room where the ERP database is hosted
Measure first, invest later: the reverse order is the most expensive mistake in IT.

Best practices and common performance pitfalls in SAP Business One

Always take measurements during working hours. A diagnosis run at seven in the evening shows a system that nobody is using. Therefore, it proves nothing.

Prioritize by total time, not by unit time. The thirty-second report that runs once a month is irrelevant. The 200 ms query that runs ten thousand times a day is not.

Do not touch standard indices without formal backing. It is the most frequent and most expensive error. Furthermore, every upgrade silently deletes them and no one remembers to recreate them.

Review the formatted searches before the hardware. A formatted search set to refresh on every field executes its query dozens of times per document. However, it almost never appears in the suspects list.

Do not archive without a policy. It is acceptable to purge historical data, but there must be a formal retention policy approved by the finance and audit departments. Otherwise, you are destroying accounting evidence.

Document the baseline state. Save today's five diagnostic results. Without a baseline, any future improvement will just be an opinion.

Official SAP Resources

Conclusion: performance is a management decision

The slowness of an ERP is not a technical problem. It is a silent tax collected in minutes of waiting, in postponed decisions, and in eroded trust in the system. Every time a user says, «I'd better write it down in Excel and upload it later,» the ERP lost a battle that no one recorded.

These five diagnoses require no investment, consulting, or additional licenses. They require one hour of your time and the willingness to replace perceptions with evidence. Therefore, the question is not whether you can do it, but why you haven't done it yet.

Run them this week. Save the results. The next time someone says the system is slow, you will know exactly what to answer—and what to fix first.

Do you want the rest of the library? This tutorial is part of the exclusive content of Strategic Circle: practical SAP Business One tutorials with production-ready SQL code, in both SQL Server and SAP HANA versions. If you found it useful, share in the comments what you found when running Step 1 on your own database. Community findings are often the best part.

Most Read

QlikSense Hierarchy: parent-child chart of accounts expanded by levels
QlikSense Hierarchy: the Chart of Accounts That Doesn't Add Up
QlikSense Sum TOTAL: share of each family over the total
QlikSense Sum TOTAL: the Percentage That Changes When You Filter
SAP Business One Inventory Revaluation - featured image of the tutorial
SAP Business One Inventory Revaluation: Fix Wrongly Loaded Costs
Empty chamber with wooden benches: the counterweight that required being present to be used
The Veto You Had to Say in Person: Your Decisions With No Counterweight
SAP Business One customizations - featured image of the pre-upgrade audit tutorial
SAP Business One Customizations: Pre-Upgrade Audit
SAP Business One Customer Concentration - featured image of the tutorial
SAP Business One Customer Concentration: Measure Your Risk with SQL

RELATED ARTICLES