icon Join with us for Oracle DBA Training Live Session ENROLL NOW

Fraud Detection Using Window Functions in PostgreSQL: A Practical Guide with Real SQL Patterns

Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Fraud Detection Using Window Functions in PostgreSQL
  • 21 Nov, 2026
  • 0 Comments
  • 6 Mins Read

Fraud Detection Using Window Functions in PostgreSQL: A Practical Guide with Real SQL Patterns

Fraud Detection Using Window Functions in PostgreSQL

Fraud detection in transactional systems is fundamentally a pattern-matching problem. Fraudsters rarely commit a single, obviously anomalous act; instead, they create sequences of behavior that deviate from a customer’s baseline—a sudden spike in spending, a burst of transactions across multiple merchants in minutes, or a long-dormant account that suddenly springs to life. PostgreSQL window functions are uniquely suited to this task because they allow you to compare each transaction against a peer group of related rows—the same account, the same merchant, or a rolling time window—without collapsing those rows into a single aggregate output.

This guide walks through the mechanics of window functions in PostgreSQL and demonstrates concrete fraud-detection patterns you can implement directly in SQL.

Why Window Functions Beat Traditional Aggregates for Fraud Detection

Standard aggregate functions (SUM, AVG, COUNT) with GROUP BY reduce multiple rows into one. If you want to compare a transaction against its account’s average, you either need a self-join or a subquery. Window functions solve this by retaining every row while computing aggregates over a defined “window” of related rows.

The OVER clause is the syntactic marker of a window function. It contains three optional components:

  • PARTITION BY: Divides rows into groups (e.g., by account_id). The function resets for each partition.

  • ORDER BY: Defines the sequence within each partition (e.g., by transaction_timestamp).

  • Frame clause (e.g., ROWS BETWEEN 5 PRECEDING AND CURRENT ROW): Restricts the window to a subset of rows relative to the current row.

For fraud detection, PARTITION BY account_id ORDER BY transaction_time is the workhorse pattern. It lets you ask: “For this account, how does this transaction compare to the previous ones?”

Core Fraud Signals You Can Build with Window Functions

Signal 1: Transactions Unusually Large Relative to Account History

A common first-pass fraud signal is a transaction that is statistically anomalous for a specific account. Rather than applying a global threshold (which fails for customers with different spending profiles), compute each account’s historical mean and standard deviation using window functions.

sql
WITH account_stats AS (
    SELECT
        transaction_id,
        account_id,
        transaction_time,
        amount,
        AVG(ABS(amount)) OVER (PARTITION BY account_id) AS account_avg,
        STDDEV(ABS(amount)) OVER (PARTITION BY account_id) AS account_stddev
    FROM transactions
)
SELECT *
FROM account_stats
WHERE ABS(amount) > account_avg + 3 * account_stddev;

This query flags transactions more than three standard deviations above the account’s own average. The OVER (PARTITION BY account_id) ensures each account is evaluated against its own baseline, not the entire portfolio.

Signal 2: Velocity and Burst Detection

Fraudsters often test stolen cards with rapid-fire small transactions or attempt to extract funds before detection. Window functions can count transactions within a rolling time window.

sql
SELECT
    transaction_id,
    account_id,
    transaction_time,
    amount,
    COUNT(*) OVER (
        PARTITION BY account_id
        ORDER BY transaction_time
        ROWS BETWEEN 10 PRECEDING AND CURRENT ROW
    ) AS txn_count_last_10
FROM transactions;

The ROWS BETWEEN 10 PRECEDING AND CURRENT ROW frame looks at the current transaction and the nine that preceded it for that account. A sudden count spike—or a sequence where every transaction is near a threshold—warrants scrutiny. For time-based windows rather than row-count-based ones, use RANGE with an interval when the ordering column is a timestamp.

Signal 3: Dormancy-Then-Spike (Account Takeover Pattern)

Account takeover frequently manifests as an account that has been inactive for months and then suddenly initiates a high-value transaction. The LAG function retrieves the previous transaction’s timestamp, enabling gap analysis.

sql
WITH activity_gaps AS (
    SELECT
        transaction_id,
        account_id,
        transaction_time,
        amount,
        LAG(transaction_time) OVER (
            PARTITION BY account_id
            ORDER BY transaction_time
        ) AS prev_txn_time,
        AVG(ABS(amount)) OVER (PARTITION BY account_id) AS account_avg,
        STDDEV(ABS(amount)) OVER (PARTITION BY account_id) AS account_stddev
    FROM transactions
)
SELECT *
FROM activity_gaps
WHERE prev_txn_time IS NOT NULL
  AND transaction_time - prev_txn_time > INTERVAL '90 days'
  AND ABS(amount) > account_avg + 3 * account_stddev;

This combines two signals: a dormancy gap exceeding 90 days and an amount exceeding three standard deviations. The conjunction is far more discriminating than either signal alone.

Signal 4: Rank and Peer Comparison

Sometimes the fraud signal is relative: a transaction that is the largest ever seen for an account, or a merchant that suddenly accounts for a disproportionate share of a customer’s spending. RANK and DENSE_RANK assign ordinal positions within partitions.

sql
SELECT
    transaction_id,
    account_id,
    amount,
    RANK() OVER (PARTITION BY account_id ORDER BY amount DESC) AS amount_rank
FROM transactions
WHERE amount_rank = 1; -- largest transaction per account

While a single large transaction is not inherently fraudulent, ranking every transaction within its account provides a feature that can be combined with others in a scoring model.

Structuring a Fraud Detection Query: A Complete Example

A production-ready fraud query often chains multiple CTEs, each computing a different window-based feature, before applying thresholds in the final SELECT. The following skeleton illustrates the pattern:

sql
WITH base_features AS (
    SELECT
        t.transaction_id,
        t.account_id,
        t.transaction_time,
        t.amount,
        -- Baseline statistics
        AVG(ABS(t.amount)) OVER w AS avg_amt,
        STDDEV(ABS(t.amount)) OVER w AS std_amt,
        -- Velocity
        COUNT(*) OVER (
            PARTITION BY t.account_id
            ORDER BY t.transaction_time
            ROWS BETWEEN 5 PRECEDING AND CURRENT ROW
        ) AS recent_count,
        -- Previous timestamp for gap detection
        LAG(t.transaction_time) OVER w AS prev_time
    FROM transactions t
    WINDOW w AS (PARTITION BY t.account_id ORDER BY t.transaction_time)
),
scored AS (
    SELECT
        *,
        CASE
            WHEN ABS(amount) > avg_amt + 3 * std_amt THEN 2
            WHEN recent_count >= 5 THEN 1
            ELSE 0
        END AS risk_score
    FROM base_features
)
SELECT *
FROM scored
WHERE risk_score >= 1
  AND (prev_time IS NULL OR transaction_time - prev_time < INTERVAL '1 hour');

The WINDOW clause names a reusable window definition, avoiding repetition when multiple functions share the same partitioning and ordering.

Performance Considerations for PostgreSQL

Window functions are powerful but not free. A few practical notes for production use:

  • Indexing: Ensure indexes exist on the PARTITION BY and ORDER BY columns (e.g., (account_id, transaction_time)). Without them, PostgreSQL must sort the entire table before computing windows.

  • Frame size: ROWS BETWEEN ... PRECEDING frames are generally more efficient than large RANGE frames over timestamps because they require less lookback logic.

  • Filtering before windowing: Window functions execute after WHERE, GROUP BY, and HAVING. Filter out irrelevant rows (e.g., already-flagged transactions, test accounts) before the window computation to reduce the working set.

  • Materialized views: For dashboards or recurring batch scoring, consider materializing the feature table and refreshing it on a schedule. Fraud detection is often a two-stage process: real-time streaming checks for immediate blocks, and periodic batch scoring using window functions for deeper analysis.

Limitations and When to Look Beyond SQL

Window functions excel at per-entity, historical comparisons. They are less suited for:

  • Real-time streaming: Window functions in standard PostgreSQL operate on data at rest. For sub-second velocity checks, a streaming engine or an application-layer cache is typically required.

  • Graph-based fraud rings: Detecting collusion (multiple accounts controlled by the same actor) requires graph traversal, not window functions. Recursive CTEs can handle simple chains, but dedicated graph databases or network analysis tools are more appropriate for complex rings.

  • Adaptive baselines: Static thresholds (3 * stddev) work reasonably well but can be gamed. Fraud teams increasingly use machine learning models that consume window-function-derived features as inputs rather than relying on the SQL thresholds directly.

Conclusion

PostgreSQL window functions provide a declarative, expressive toolkit for building fraud detection features directly in the database. By partitioning transactions by account and ordering them by time, you can compute per-account baselines, detect velocity bursts, identify dormancy-then-spike patterns, and rank transactions by relative size all without leaving SQL. The patterns in this guide are starting points: the most effective fraud systems layer multiple signals, validate them against labeled outcomes, and iterate on thresholds as fraud tactics evolve. Window functions give you the foundation to build that iteration loop where the data already lives.

lets talk - learnomate helpdesk

Book a Free Demo

lets talk - learnomate helpdesk

Book a Free Demo