Skip to main content

Use named windows in duckdb to simplify business questions

sql
data analysis
Author

Joram Mutenge

Published

2026-12-03

Most of the SQL consulting work I do with clients involves writing window functions. This isn’t surprising. Clients often want to know how sales on a particular day compare with sales around that date. However, window functions can become tedious to maintain, especially when a client asks you to include additional calculations that use the same window. Fortunately, named windows help simplify this process.

The dataset

Since I can’t use actual data from my clients, I’ll use a clothing store sales dataset to demonstrate how I use named windows when working with client data. You can download the full dataset from my GitHub repository.

I’ll read the data directly from the URL and load it into a temporary table called sales.

CREATE TEMP TABLE sales AS (
    SELECT * FROM read_csv_auto('https://raw.githubusercontent.com/jorammutenge/learn-rust/refs/heads/main/sample_sales.csv')
);

I’ll display a sample of five rows to check that the data has been loaded correctly.

FROM sales
USING SAMPLE 5;
┌────────────────┬──────────────────┬──────────┬──────────┬───┬────────────┬───────────┬─────────────────────┐
│ Account Number │   Account Name   │   sku    │ category │ … │ unit price │ ext price │        date         │
│     int64      │     varchar      │ varchar  │ varchar  │ … │   double   │  double   │      timestamp      │
├────────────────┼──────────────────┼──────────┼──────────┼───┼────────────┼───────────┼─────────────────────┤
│         269278 │ Luettgen-Ritchie │ ZC-07383 │ Sweater  │ … │      20.64 │     41.28 │ 2014-09-27 15:47:56 │
│         225551 │ Huels LLC        │ QS-76400 │ Sweater  │ … │      82.51 │    660.08 │ 2014-08-28 11:16:54 │
│         542855 │ Kuhlman and Sons │ RU-25060 │ Sweater  │ … │       86.2 │    1551.6 │ 2013-10-28 20:08:42 │
│         345320 │ Jenkins Inc      │ AE-95093 │ Socks    │ … │      76.06 │    1521.2 │ 2014-09-06 02:06:08 │
│         431043 │ Grimes-Schmidt   │ ZC-07383 │ Sweater  │ … │      20.47 │    327.52 │ 2014-08-25 08:40:46 │
└────────────────┴──────────────────┴──────────┴──────────┴───┴────────────┴───────────┴─────────────────────┘
  5 rows                         use .last to show entire result                         8 columns (7 shown)

I don’t like having spaces in column names, so I’ll rename a few columns.

ALTER TABLE sales RENAME COLUMN "Account Name" TO account;
ALTER TABLE sales RENAME COLUMN "unit price" TO unit_price;
ALTER TABLE sales RENAME COLUMN "ext price" TO ext_price;

Regular window functions

Suppose I want to analyze daily sales trends and calculate the following metrics for each day:

  • 7-day moving sales average
  • 7-day minimum sales
  • 7-day maximum sales

Notice that all three calculations require exactly the same window definition, which covers seven days.

Here’s how I’d write the query without using named windows. Since transaction-level data is usually too granular for moving-window analysis, I’ll first create a common table expression (CTE) called daily_sales that aggregates daily transactions by category.

WITH daily_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        category,
        SUM(ext_price) AS daily_revenue
    FROM sales
    GROUP BY 1, 2
)

SELECT
    sales_date,
    category,

    AVG(daily_revenue) OVER (
        PARTITION BY category
        ORDER BY sales_date
        RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
              AND INTERVAL 3 DAYS FOLLOWING
    ) AS avg_7day_sales,

    MIN(daily_revenue) OVER (
        PARTITION BY category
        ORDER BY sales_date
        RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
              AND INTERVAL 3 DAYS FOLLOWING
    ) AS min_7day_sales,

    MAX(daily_revenue) OVER (
        PARTITION BY category
        ORDER BY sales_date
        RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
              AND INTERVAL 3 DAYS FOLLOWING
    ) AS max_7day_sales

FROM daily_sales;
┌────────────┬──────────┬────────────────────┬────────────────┬────────────────────┐
│ sales_date │ category │   avg_7day_sales   │ min_7day_sales │   max_7day_sales   │
│    date    │ varchar  │       double       │     double     │       double       │
├────────────┼──────────┼────────────────────┼────────────────┼────────────────────┤
│ 2013-10-05 │ Hat      │             352.56 │         281.82 │              423.3 │
│ 2013-10-07 │ Hat      │             250.41 │          46.11 │              423.3 │
│ 2013-10-09 │ Hat      │             634.43 │          46.11 │            1575.36 │
│ 2013-10-12 │ Hat      │ 500.73249999999996 │          46.11 │            1575.36 │
│ 2013-10-13 │ Hat      │  652.2733333333333 │          171.7 │            1575.36 │
│     ·      │  ·       │          ·         │            ·   │               ·    │
│     ·      │  ·       │          ·         │            ·   │               ·    │
│     ·      │  ·       │          ·         │            ·   │               ·    │
│ 2014-09-26 │ Sweater  │  825.7071428571429 │         256.96 │ 1594.8600000000001 │
│ 2014-09-27 │ Sweater  │  970.5228571428571 │         256.96 │ 1594.8600000000001 │
│ 2014-09-28 │ Sweater  │ 1013.4216666666667 │         256.96 │ 1594.8600000000001 │
│ 2014-09-29 │ Sweater  │           1046.422 │         256.96 │ 1594.8600000000001 │
│ 2014-09-30 │ Sweater  │          1029.1975 │         256.96 │ 1594.8600000000001 │
└────────────┴──────────┴────────────────────┴────────────────┴────────────────────┘
  639 rows (10 shown)          use .last to show entire result           5 columns

Notice how the window definition is repeated for every calculation. This is the code that defines the seven-day window:

PARTITION BY category
ORDER BY sales_date
RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
      AND INTERVAL 3 DAYS FOLLOWING

The named window feature solves this repetition problem.

Named window functions

I’ll now rewrite the query using a named window. This allows me to define the window once and reuse it across all three calculations.

WITH daily_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        category,
        SUM(ext_price) AS daily_revenue
    FROM sales
    GROUP BY 1, 2
)

SELECT
    sales_date,
    category,

    AVG(daily_revenue) OVER sales_window AS avg_7day_sales,
    MIN(daily_revenue) OVER sales_window AS min_7day_sales,
    MAX(daily_revenue) OVER sales_window AS max_7day_sales

FROM daily_sales

WINDOW sales_window AS (
    PARTITION BY category
    ORDER BY sales_date
    RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
          AND INTERVAL 3 DAYS FOLLOWING
);
┌────────────┬──────────┬────────────────────┬────────────────┬────────────────────┐
│ sales_date │ category │   avg_7day_sales   │ min_7day_sales │   max_7day_sales   │
│    date    │ varchar  │       double       │     double     │       double       │
├────────────┼──────────┼────────────────────┼────────────────┼────────────────────┤
│ 2013-10-05 │ Hat      │             352.56 │         281.82 │              423.3 │
│ 2013-10-07 │ Hat      │             250.41 │          46.11 │              423.3 │
│ 2013-10-09 │ Hat      │             634.43 │          46.11 │            1575.36 │
│ 2013-10-12 │ Hat      │ 500.73249999999996 │          46.11 │            1575.36 │
│ 2013-10-13 │ Hat      │  652.2733333333333 │          171.7 │            1575.36 │
│     ·      │  ·       │          ·         │            ·   │               ·    │
│     ·      │  ·       │          ·         │            ·   │               ·    │
│     ·      │  ·       │          ·         │            ·   │               ·    │
│ 2014-09-26 │ Sweater  │  825.7071428571429 │         256.96 │ 1594.8600000000001 │
│ 2014-09-27 │ Sweater  │  970.5228571428571 │         256.96 │ 1594.8600000000001 │
│ 2014-09-28 │ Sweater  │ 1013.4216666666667 │         256.96 │ 1594.8600000000001 │
│ 2014-09-29 │ Sweater  │           1046.422 │         256.96 │ 1594.8600000000001 │
│ 2014-09-30 │ Sweater  │          1029.1975 │         256.96 │ 1594.8600000000001 │
└────────────┴──────────┴────────────────────┴────────────────┴────────────────────┘
  639 rows (10 shown)          use .last to show entire result           5 columns

Now the complex window definition lives in one place. Whenever DuckDB encounters OVER sales_window, it uses the entire window definition associated with that name.

Tip

It helps to think of a named window as being similar to a CTE. A CTE gives a query a reusable name, while a named window gives a window definition a reusable name.

Practical business question

Now that I’ve explained what a named window is and how to use it, let’s look at a business question a client wanted answered:

Which days had sales performance that was unusually strong or weak compared with nearby days in the same product category?

To understand how to answer this question, I’ll start by looking at the part of the query that calculates the percentile distributions.

WITH daily_category_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        category,
        SUM(ext_price) AS daily_revenue
    FROM sales
    GROUP BY 1, 2
)

SELECT
    sales_date,
    category,
    daily_revenue,

    ROUND(MIN(daily_revenue) OVER seven_days, 2) AS local_min,
    ROUND(MAX(daily_revenue) OVER seven_days, 2) AS local_max,

    QUANTILE(
        daily_revenue,
        [0.25, 0.50, 0.75]
    ) OVER seven_days AS quartiles

FROM daily_category_sales

WINDOW seven_days AS (
    PARTITION BY category
    ORDER BY sales_date
    RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
          AND INTERVAL 3 DAYS FOLLOWING
)

ORDER BY category, sales_date;
┌────────────┬──────────┬────────────────────┬───────────┬───────────┬────────────────────────────────────────┐
│ sales_date │ category │   daily_revenue    │ local_min │ local_max │               quartiles                │
│    date    │ varchar  │       double       │  double   │  double   │                double[]                │
├────────────┼──────────┼────────────────────┼───────────┼───────────┼────────────────────────────────────────┤
│ 2013-10-05 │ Hat      │              423.3 │    281.82 │     423.3 │ [281.82, 281.82, 423.3]                │
│ 2013-10-07 │ Hat      │             281.82 │     46.11 │     423.3 │ [46.11, 281.82, 423.3]                 │
│ 2013-10-09 │ Hat      │              46.11 │     46.11 │   1575.36 │ [46.11, 281.82, 1575.36]               │
│ 2013-10-12 │ Hat      │            1575.36 │     46.11 │   1575.36 │ [46.11, 171.7, 209.76]                 │
│ 2013-10-13 │ Hat      │             209.76 │     171.7 │   1575.36 │ [171.7, 209.76, 1575.36]               │
│     ·      │  ·       │                ·   │       ·   │      ·    │            ·                           │
│     ·      │  ·       │                ·   │       ·   │      ·    │            ·                           │
│     ·      │  ·       │                ·   │       ·   │      ·    │            ·                           │
│ 2014-09-26 │ Sweater  │            1115.32 │    256.96 │   1594.86 │ [403.97, 847.29, 1115.32]              │
│ 2014-09-27 │ Sweater  │             847.29 │    256.96 │   1594.86 │ [713.13, 848.4200000000001, 1417.6799… │
│ 2014-09-28 │ Sweater  │             256.96 │    256.96 │   1594.86 │ [847.29, 848.4200000000001, 1417.6799… │
│ 2014-09-29 │ Sweater  │ 1594.8600000000001 │    256.96 │   1594.86 │ [847.29, 1115.32, 1417.6799999999998]  │
│ 2014-09-30 │ Sweater  │ 1417.6799999999998 │    256.96 │   1594.86 │ [256.96, 847.29, 1417.6799999999998]   │
└────────────┴──────────┴────────────────────┴───────────┴───────────┴────────────────────────────────────────┘
  639 rows (10 shown)                        use .last to show entire result                        6 columns

So, how do we make sense of these results? Consider the first row:

  • daily_revenue = 423.3: Hat sales generated $423.30 that day.
  • local_min = 281.82: The lowest Hat revenue observed within the surrounding seven-day window.
  • local_max = 423.3: The highest Hat revenue observed within the surrounding seven-day window.
  • quartiles = [281.82, 281.82, 423.3]

Here’s what the values in quartiles represent:

  • Q1 or 25th percentile = $281.82 - This means about a quarter of the transactions in this local 7-day period were worth $281.82 or less.
  • Median or 50th percentile = $281.82 - This means half of the transactions are smaller and half are larger than $281.82.
  • Q3 or 75th percentile = $423.30 - This means 75% of transactions are below $423.30.

Now that I know the typical range of sales, represented by the first and third quartiles (Q1 and Q3), I can classify each day as unusually low, typical, or unusually high by comparing its daily revenue against these values. Here’s the query that answers the business question.

WITH daily_category_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        category,
        SUM(ext_price) AS daily_revenue
    FROM sales
    GROUP BY 1, 2
),

category_stats AS (
    SELECT
        sales_date,
        category,
        daily_revenue,

        QUANTILE(
            daily_revenue,
            [0.25, 0.75]
        ) OVER seven_days AS quartiles

    FROM daily_category_sales

    WINDOW seven_days AS (
        PARTITION BY category
        ORDER BY sales_date
        RANGE BETWEEN INTERVAL 3 DAYS PRECEDING
              AND INTERVAL 3 DAYS FOLLOWING
    )
)

SELECT
    sales_date,
    category,
    daily_revenue,
    quartiles[1] AS q1,
    quartiles[2] AS q3,

    CASE
        WHEN daily_revenue < quartiles[1]
            THEN 'Unusually Low'

        WHEN daily_revenue > quartiles[2]
            THEN 'Unusually High'

        ELSE 'Typical'
    END AS sales_flag

FROM category_stats
ORDER BY category, sales_date;
┌────────────┬──────────┬────────────────────┬────────┬────────────────────┬────────────────┐
│ sales_date │ category │   daily_revenue    │   q1   │         q3         │   sales_flag   │
│    date    │ varchar  │       double       │ double │       double       │    varchar     │
├────────────┼──────────┼────────────────────┼────────┼────────────────────┼────────────────┤
│ 2013-10-05 │ Hat      │              423.3 │ 281.82 │              423.3 │ Typical        │
│ 2013-10-07 │ Hat      │             281.82 │  46.11 │              423.3 │ Typical        │
│ 2013-10-09 │ Hat      │              46.11 │  46.11 │            1575.36 │ Typical        │
│ 2013-10-12 │ Hat      │            1575.36 │  46.11 │             209.76 │ Unusually High │
│ 2013-10-13 │ Hat      │             209.76 │  171.7 │            1575.36 │ Typical        │
│     ·      │  ·       │                ·   │    ·   │               ·    │    ·           │
│     ·      │  ·       │                ·   │    ·   │               ·    │    ·           │
│     ·      │  ·       │                ·   │    ·   │               ·    │    ·           │
│ 2014-09-26 │ Sweater  │            1115.32 │ 403.97 │            1115.32 │ Typical        │
│ 2014-09-27 │ Sweater  │             847.29 │ 713.13 │ 1417.6799999999998 │ Typical        │
│ 2014-09-28 │ Sweater  │             256.96 │ 847.29 │ 1417.6799999999998 │ Unusually Low  │
│ 2014-09-29 │ Sweater  │ 1594.8600000000001 │ 847.29 │ 1417.6799999999998 │ Unusually High │
│ 2014-09-30 │ Sweater  │ 1417.6799999999998 │ 256.96 │ 1417.6799999999998 │ Typical        │
└────────────┴──────────┴────────────────────┴────────┴────────────────────┴────────────────┘
  639 rows (10 shown)               use .last to show entire result               6 columns
Note

The quartiles column contains a list of values for each row, such as [281.82, 281.82, 423.3]. Using quartiles[1] in the query above retrieves the first element of that list, which in this case is 281.82. Similarly, quartiles[2] retrieves the second element.

Now we can easily identify which days had unusually strong or weak sales compared with nearby days in the same product category. This gives us a simple way to flag sales performance that deviates from the typical range.

What to remember

Named windows let you define a complex window once and reuse it across multiple window functions. This makes analytical SQL easier to read, maintain, and modify, particularly when several calculations rely on the same window definition.