SAP Business One Cash Flow: SQL Query to Anticipate Your Liquidity - featured image from the tutorial

Publications

SAP Business One Cash Flow: SQL Query to Anticipate Your Liquidity

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

There is a conversation that repeats itself in the management team of almost any company: the business is profitable, sales are growing and, even so, the finance manager shows up on Monday with the same question: «do we have enough to pay this week?». This is where SAP Business One cash flow stops being an optional report and becomes your compass. Profit shows up in the income statement, but cash is lived at the bank; and those two things rarely happen on the same day.

In this tutorial you will build, step by step, a SQL query that turns your accounts receivable and accounts payable into a clear liquidity map for the coming weeks. You will stop reacting to overdrafts and start anticipating them. This is not about more reports, but about seeing the near future with data that already lives inside your ERP.

SAP Business One cash flow - financial analysis and liquidity projection
Projected cash flow turns operational data into treasury decisions.

Why profit does not tell you whether you will survive the month

A company can be profitable and still go under. It sounds contradictory, but it happens all the time: the sale is booked today, the cost is paid at 30 days and the customer only pays at 60. The income statement shows a profit while the bank account dries up. Profitability measures whether the business is good; liquidity measures whether it is still alive to take advantage of it.

The SAP Business One cash flow targets exactly that blind spot. Instead of looking backward, it projects forward using the real due dates of every open document. A manager can then answer with evidence the questions that used to be settled by gut feel: is there enough for payroll on the 30th? is it better to bring that supplier payment forward or negotiate terms? can we commit to an investment this quarter?

What you need before you start

Before writing a single line of code, lock down these prerequisites. There are few of them, but they determine the quality of the result:

  • Access to Query Manager or Query Generator with read-only permissions on the database.
  • Correct due dates on your invoices. The report is worth exactly what your payment terms are worth; if the DocDueDate is wrong, so is the projection.
  • Discipline in reconciliation: an invoice already collected but not reconciled will keep showing up as open and will inflate your inflows.
  • Knowing whether your database runs on SQL Server or SAP HANA, because the syntax changes. That is why you will find each query below in both versions.

How SAP thinks about cash flow

SAP builds its native cash flow report on a simple idea: analyze open, unreconciled transactions to estimate future inflows and outflows. We will replicate and extend that logic with SQL, leaning on two central tables.

The first is OINV, the header of customer invoices (what your customers owe you). The second is OPCH, the header of supplier invoices (what you owe your suppliers). Both share the fields we care about: Document Status («O» for open), DocDueDate (the date the money should move), Document Total (the document amount) and PaidToDate (what has already been paid or collected). The real outstanding balance is therefore DocTotal – PaidToDate. The whole model rests on that subtraction.

Step by step: build your cash flow query in SAP Business One

We will put the report together in three layers. First, an aggregated view by due-date bucket to get the overall picture. Then, the current cash position, so you know where you are starting from. Finally, a daily detail with a running balance, to pinpoint the exact day liquidity goes red.

Step 1: Projection by due-date bucket

This query classifies each open document into buckets (overdue, 0 to 7 days, 8 to 15, and so on) and calculates the net flow of each one. For example, if the «0 to 7 days» bucket comes out negative, you know that next week you pay more than you collect.

SQL Server

SELECT
    Bucket,
    SUM(Inflows)              AS Expected_Collections,
    SUM(Outflows)             AS Committed_Payments,
    SUM(Inflows - Outflows)   AS Net_Flow
FROM (
    -- Accounts receivable: open customer invoices (inflows)
    SELECT
        CASE
            WHEN DATEDIFF(DAY, GETDATE(), T0.DocDueDate) < 0   THEN '1. Overdue'
            WHEN DATEDIFF(DAY, GETDATE(), T0.DocDueDate) <= 7  THEN '2. 0 to 7 days'
            WHEN DATEDIFF(DAY, GETDATE(), T0.DocDueDate) <= 15 THEN '3. 8 to 15 days'
            WHEN DATEDIFF(DAY, GETDATE(), T0.DocDueDate) <= 30 THEN '4. 16 to 30 days'
            WHEN DATEDIFF(DAY, GETDATE(), T0.DocDueDate) <= 60 THEN '5. 31 to 60 days'
            ELSE '6. Over 60 days'
        END                              AS Bucket,
        (T0.DocTotal - T0.PaidToDate)    AS Inflows,
        0                                AS Outflows
    FROM OINV T0 WITH (NOLOCK)
    WHERE T0.DocStatus = 'O'
      AND (T0.DocTotal - T0.PaidToDate) > 0
    UNION ALL
    -- Accounts payable: open supplier invoices (outflows)
    SELECT
        CASE
            WHEN DATEDIFF(DAY, GETDATE(), T1.DocDueDate) < 0   THEN '1. Overdue'
            WHEN DATEDIFF(DAY, GETDATE(), T1.DocDueDate) <= 7  THEN '2. 0 to 7 days'
            WHEN DATEDIFF(DAY, GETDATE(), T1.DocDueDate) <= 15 THEN '3. 8 to 15 days'
            WHEN DATEDIFF(DAY, GETDATE(), T1.DocDueDate) <= 30 THEN '4. 16 to 30 days'
            WHEN DATEDIFF(DAY, GETDATE(), T1.DocDueDate) <= 60 THEN '5. 31 to 60 days'
            ELSE '6. Over 60 days'
        END,
        0,
        (T1.DocTotal - T1.PaidToDate)
    FROM OPCH T1 WITH (NOLOCK)
    WHERE T1.DocStatus = 'O'
      AND (T1.DocTotal - T1.PaidToDate) > 0
) Flow
GROUP BY Bucket
ORDER BY Bucket;

SAP HANA

SELECT
    "Bucket",
    SUM("Inflows")                AS "Expected_Collections",
    SUM("Outflows")               AS "Committed_Payments",
    SUM("Inflows" - "Outflows")   AS "Net_Flow"
FROM (
    SELECT
        CASE
            WHEN DAYS_BETWEEN(CURRENT_DATE, T0."DocDueDate") < 0   THEN '1. Overdue'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T0."DocDueDate") <= 7  THEN '2. 0 to 7 days'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T0."DocDueDate") <= 15 THEN '3. 8 to 15 days'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T0."DocDueDate") <= 30 THEN '4. 16 to 30 days'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T0."DocDueDate") <= 60 THEN '5. 31 to 60 days'
            ELSE '6. Over 60 days'
        END                                    AS "Bucket",
        (T0."DocTotal" - T0."PaidToDate")      AS "Inflows",
        0                                      AS "Outflows"
    FROM OINV T0
    WHERE T0."DocStatus" = 'O'
      AND (T0."DocTotal" - T0."PaidToDate") > 0
    UNION ALL
    SELECT
        CASE
            WHEN DAYS_BETWEEN(CURRENT_DATE, T1."DocDueDate") < 0   THEN '1. Overdue'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T1."DocDueDate") <= 7  THEN '2. 0 to 7 days'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T1."DocDueDate") <= 15 THEN '3. 8 to 15 days'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T1."DocDueDate") <= 30 THEN '4. 16 to 30 days'
            WHEN DAYS_BETWEEN(CURRENT_DATE, T1."DocDueDate") <= 60 THEN '5. 31 to 60 days'
            ELSE '6. Over 60 days'
        END,
        0,
        (T1."DocTotal" - T1."PaidToDate")
    FROM OPCH T1
    WHERE T1."DocStatus" = 'O'
      AND (T1."DocTotal" - T1."PaidToDate") > 0
) "Flow"
GROUP BY "Bucket"
ORDER BY "Bucket";

The «Overdue» bucket deserves separate attention. On the collections side it is money that should already be in your account and never arrived; on the payments side, commitments you have already missed. Both hit your immediate liquidity, so it pays to keep them visible in the top row.

SAP Business One cash flow - review of accounts receivable and accounts payable
Every open invoice is a future inflow or outflow in your projection.

Step 2: Current cash position

The projection above tells you how much will move, but not where you are starting from. You therefore need the current balance of your bank and cash accounts, which lives in the chart of accounts (table OACT). Replace the sample codes with the ones your company uses.

SQL Server

SELECT
    T0.AcctCode     AS Account,
    T0.AcctName     AS Account_Name,
    T0.CurrTotal    AS Current_Balance
FROM OACT T0 WITH (NOLOCK)
WHERE T0.AcctCode IN ('11101001', '11101002')  -- your bank/cash accounts
ORDER BY T0.AcctName;

SAP HANA

SELECT
    T0."AcctCode"    AS "Account",
    T0."AcctName"    AS "Account_Name",
    T0."CurrTotal"   AS "Current_Balance"
FROM OACT T0
WHERE T0."AcctCode" IN ('11101001', '11101002')
ORDER BY T0."AcctName";

Add up those balances and you have your starting point. And if you combine that opening position with the net flow from Step 1, you get an estimated cash balance at the close of each bucket. The question «is there enough?» stops being a feeling and becomes a number.

Step 3: Daily flow with running balance

The bucket aggregate is useful for the overall picture, but treasury is played day by day. This last query orders every movement by date and calculates a running balance, so you can see the exact moment the flow crosses into negative territory within the next 45 days.

SQL Server

SELECT
    X.Due_Date,
    SUM(X.Net)                                      AS Daily_Flow,
    SUM(SUM(X.Net)) OVER (ORDER BY X.Due_Date)      AS Cumulative_Flow
FROM (
    SELECT T0.DocDueDate AS Due_Date,
           (T0.DocTotal - T0.PaidToDate) AS Net
    FROM OINV T0 WITH (NOLOCK)
    WHERE T0.DocStatus = 'O' AND (T0.DocTotal - T0.PaidToDate) > 0
      AND T0.DocDueDate <= DATEADD(DAY, 45, GETDATE())
    UNION ALL
    SELECT T1.DocDueDate,
           -1 * (T1.DocTotal - T1.PaidToDate)
    FROM OPCH T1 WITH (NOLOCK)
    WHERE T1.DocStatus = 'O' AND (T1.DocTotal - T1.PaidToDate) > 0
      AND T1.DocDueDate <= DATEADD(DAY, 45, GETDATE())
) X
GROUP BY X.Due_Date
ORDER BY X.Due_Date;

SAP HANA

SELECT
    X."Due_Date",
    SUM(X."Net")                                          AS "Daily_Flow",
    SUM(SUM(X."Net")) OVER (ORDER BY X."Due_Date")         AS "Cumulative_Flow"
FROM (
    SELECT T0."DocDueDate" AS "Due_Date",
           (T0."DocTotal" - T0."PaidToDate") AS "Net"
    FROM OINV T0
    WHERE T0."DocStatus" = 'O' AND (T0."DocTotal" - T0."PaidToDate") > 0
      AND T0."DocDueDate" <= ADD_DAYS(CURRENT_DATE, 45)
    UNION ALL
    SELECT T1."DocDueDate",
           -1 * (T1."DocTotal" - T1."PaidToDate")
    FROM OPCH T1
    WHERE T1."DocStatus" = 'O' AND (T1."DocTotal" - T1."PaidToDate") > 0
      AND T1."DocDueDate" <= ADD_DAYS(CURRENT_DATE, 45)
) X
GROUP BY X."Due_Date"
ORDER BY X."Due_Date";

The column Cumulative_Flow is the jewel of the report. When that running total, added to your opening balance, drops below zero, you have the precise date of the problem. You can act days or weeks ahead: chase a collection, reschedule a payment or draw on a credit line before the bank calls you.

Variations and use cases

The skeleton above takes adjustments to fit your reality. Here are a few frequent extensions:

  • By currency: add DocCur to the SELECT and group by it if you operate in several currencies. That keeps you from mixing pesos and dollars in the same total.
  • By critical customer or supplier: add CardCode and CardName to identify who concentrates your inflows or outflows. A single large customer running late can explain an entire gap.
  • Post-dated checks: if you work with post-dated checks, add the information from the payment means table so you do not underestimate committed outflows.
  • Adjustment for actual behavior: if a customer always pays 10 days late, you can shift their projected DocDueDate . Start simple, though, and add realism later.

Best practices and common mistakes

The most frequent mistake is confusing open invoices with guaranteed money. An invoice 90 days overdue still shows as «receivable», but it may never arrive. Always cross the flow with your aging analysis and apply judgment on collectability.

The second mistake is forgetting reconciliation. If your team does not reconcile on time, documents already paid will keep contaminating the report. Also avoid running these queries at peak hours against production: even though they use NOLOCK in SQL Server so as not to block, it is better to reserve them for low-load windows or dedicated views. Finally, save each one as a saved Query and feed it into a dashboard, so liquidity stops being a manual Friday exercise.

Official SAP Resources

To go deeper into the native report and its selection criteria, review the official documentation: Cash Flow Report – SAP Business One (SAP Help Portal). Complement it with the treasury and payment management module of your version.

Conclusion: navigate with a map, not from memory

A manager who only looks at the income statement is driving by the rear-view mirror. The SAP Business One cash flow, by contrast, hands you the windshield: the ability to see the curve before you take it. With these three queries you move from reacting to anticipating, and that difference is often what separates the company that seizes an opportunity from the one that barely survives the month.

Want the full set of ready-to-paste queries, along with the treasury dashboard templates and the rest of the practical tutorials? All of it lives in the Strategic Circle, the membership where I share the technical detail that does not fit in an open article. Join at hectorpincheira.com and turn your ERP into a real financial compass.

Most Read

Ballena jorobada bajo el agua con su aleta pectoral extendida: la esperanza en la tecnología y la biomimética
La ballena que volvió: la esperanza en la tecnología y la que no cabe en un tablero
SAP data in ChatGPT: an open door at the far end of a dark room
The Tab Next Door: The SAP Data in ChatGPT That Nobody Authorized
SAP Business One Purchase Price Variance - featured image of the tutorial
SAP Business One Purchase Price Variance: Detect the Inflation in Your Buying Costs
QlikSense format changeovers: actual minutes against the standard
QlikSense Format Changeovers: the Minutes Nobody Bills
QlikSense buttons and actions: executive dashboard with indicators
QlikSense Buttons and Actions: the Dashboard that Runs the Meeting
SAP Business One Internal Reconciliation - featured image of the tutorial
SAP Business One Internal Reconciliation: Clear False Open Items

RELATED ARTICLES