10 min readBy Evren Branewick

    One Rule for Gap-Free Daily SQL Reports: Let the Calendar Drive the Query

    Why does the daily signups chart jump from 3 March straight to 5 March, as if 4 March never happened? The product manager who asks this usually suspects the tracking. The tracking is fine.

    On 4 March nobody signed up from the campaign being filtered, so the query had nothing to group, and a GROUP BY cannot invent a row for a value that does not exist in its input. The chart library then drew a straight line from the 3rd to the 5th, and the line hid the zero.

    Every fix for this problem is a variation of one rule: the rows of a time series report must come from a list of dates, never from the facts. The facts only supply numbers to attach to those rows.

    Once that rule is in place, missing days, missing countries and broken moving averages stop being separate bugs. What follows tears down the typical broken query, applies the rule, extends it to dimensions such as country or product, and then looks at the cases where filling with zero gives the wrong answer.

    Teardown of the query that loses days

    Here is the query behind most daily report charts, found in some form in nearly every analytics codebase:

    SELECT created_at::date AS day, count(*) AS signups
    FROM signups
    WHERE created_at >= date '2026-03-01'
      AND created_at <  date '2026-03-08'
      AND campaign = 'spring_promo'
    GROUP BY 1
    ORDER BY 1;
    

    It is correct SQL and it answers a slightly different question from the one being asked. It returns one row per date on which at least one matching signup exists. For a busy, unfiltered metric that is every day, so the defect stays invisible for months.

    Add a filter for a small campaign, a minor country or a new product, and the activity becomes sparse enough that some days have none. Over the 7 days in this example, the result might contain 5 rows, with 4 March and 6 March missing.

    Three things then go wrong downstream, and only one of them is visible. The visible one is the chart that connects 3 March to 5 March. The second is any average computed over the rows: 5 rows totalling 40 signups average 8 per day, while the true daily average over 7 days is about 5.7, so the dashboard overstates the run rate by roughly 40%.

    The third is any window function that counts rows instead of days. A "7-day" moving average defined as AVG over ROWS BETWEEN 6 PRECEDING AND CURRENT ROW quietly averages the last 7 active days, which on a sparse series can stretch across 10 or 12 calendar days.

    Spreadsheet exports carry the same problem further. A finance analyst pastes the result next to a column of dates, the rows shift by 2, and every figure after 4 March sits next to the wrong date. Nobody sees an error message; the numbers simply line up with the wrong days.

    The tempting patch is to fill the gaps in the BI tool or in a pandas step after the query. That works for one chart and fails for the next consumer of the same SQL, whether that is a scheduled export, a downstream model or another dashboard. The fix belongs in the query, because the query is where the rows are decided.

    The rule applied: dates on the left, aggregates on the right

    Applying the rule means building the list of dates first and attaching the facts to it with a LEFT JOIN. If the warehouse already has a calendar table, select the range from it. If not, PostgreSQL and DuckDB can generate the dates inline with generate_series; other engines have equivalents. The query becomes three short steps:

    WITH days AS (
      SELECT date_day
      FROM calendar
      WHERE date_day BETWEEN date '2026-03-01' AND date '2026-03-07'
    ),
    daily AS (
      SELECT created_at::date AS day, count(*) AS signups
      FROM signups
      WHERE created_at >= date '2026-03-01'
        AND created_at <  date '2026-03-08'
        AND campaign = 'spring_promo'
      GROUP BY 1
    )
    SELECT d.date_day, COALESCE(s.signups, 0) AS signups
    FROM days d
    LEFT JOIN daily s ON s.day = d.date_day
    ORDER BY d.date_day;
    

    The result now has exactly 7 rows. Days with no signups come back with NULL from the join, and COALESCE turns that NULL into 0. Three details in this shape matter more than they look.

    First, aggregate before you join. If you join the dates directly to raw signup rows and then GROUP BY date with count(), every empty day still contains one row: the date itself with NULLs on the right side. count() counts that row, so every day with zero signups reports 1.

    Either aggregate the facts in their own CTE, as above, or count a column from the fact table, such as count(s.signup_id), which ignores NULLs. This is the single most common bug in "fixed" gap-filling queries, and it is nasty because a 1 looks plausible on a sparse series.

    Second, keep fact filters away from the final WHERE clause. Writing WHERE s.campaign = 'spring_promo' after the LEFT JOIN discards the rows where s.campaign is NULL, which are exactly the filled days, and the query silently becomes an inner join again. Filters on the fact table go inside the fact CTE or into the ON clause. Filters on dates go on the date list.

    Third, make both sides use the same date logic. If signups are stored in UTC and the business reports in Lisbon time, convert before truncating: (created_at AT TIME ZONE 'Europe/Lisbon')::date. A date list in local time joined to facts truncated in UTC shifts an hour of activity across midnight twice a year and produces days that look half-empty for reasons that have nothing to do with gaps.

    Teams that write many of these queries often wrap the pattern in a view or a dbt macro that takes a fact CTE and a date range. That is reasonable, provided the macro keeps the aggregation step separate from the join and exposes the time zone as a parameter instead of hiding it.

    The same shape works at other grains with one change: the date list. A weekly report needs one row per week start, which a calendar table provides with SELECT DISTINCT week_start, and the fact CTE truncates with date_trunc('week', created_at). Monthly works the same way.

    What breaks is mixing grains, for example a weekly date list joined to facts truncated to ISO weeks while the calendar uses Sunday week starts. In that case every row joins to nothing, the whole report fills with zeros, and the query looks broken in a new and confusing way. Check that both sides produce identical keys for 2 or 3 sample dates before trusting the output.

    Once the query returns a filled series, add one assertion to the model or the scheduled job: the number of rows must equal the number of days in the range. For the March example that is 31. A count of 29 means the date list itself is short, usually because a calendar table ends too early or a filter was applied to it by mistake, and that failure is easy to miss on a chart.

    Gaps per dimension: building the grid before the join

    The rule gets more interesting once the report is split by something: signups per day per country, revenue per day per product, sessions per day per platform. The single-column date list is no longer enough, because a day can have activity in Portugal and none in Austria, and the LEFT JOIN from dates alone will never produce an Austria row for that day. The list on the left has to become a grid of every date crossed with every member of the dimension:

    WITH days AS (
      SELECT date_day FROM calendar
      WHERE date_day BETWEEN date '2026-03-01' AND date '2026-03-31'
    ),
    countries AS (
      SELECT country_code FROM dim_country WHERE is_active
    ),
    grid AS (
      SELECT d.date_day, c.country_code
      FROM days d CROSS JOIN countries c
    ),
    daily AS (
      SELECT created_at::date AS day, country_code, count(*) AS signups
      FROM signups
      WHERE created_at >= date '2026-03-01' AND created_at < date '2026-04-01'
      GROUP BY 1, 2
    )
    SELECT g.date_day, g.country_code, COALESCE(x.signups, 0) AS signups
    FROM grid g
    LEFT JOIN daily x
      ON x.day = g.date_day AND x.country_code = g.country_code;
    

    Before running a grid query, size it. The arithmetic is simple and it tells you whether a dense grid is reasonable or whether you are about to generate millions of zero rows:

    expected_rows = days_in_range × members_dim_1 × members_dim_2 × ...
    filled_rows   = expected_rows - rows_with_activity
    zero_share    = filled_rows / expected_rows
    

    Worked through: March has 31 days, and with 12 active countries the grid has 372 rows. If signups occurred on 301 of those country-days, the query fills 71 rows with zero, a zero share of about 19%. Add 4 platforms and the grid grows to 1,488 rows, still trivial.

    Now try 365 days times 200 products times 50 stores: 3,650,000 rows, most of them zero. At that size the grid stops being a report and becomes a storage problem, and many of those combinations are meaningless anyway, such as a product never stocked in a store.

    The choice of member list decides what the report means. Taking members from a dimension table, as above, shows every active country every day, including ones with no activity all month. That is right for a coverage report, where a zero row is information. Taking members from the facts, for example SELECT DISTINCT country_code FROM signups over the same month, shows only countries that had at least one signup in the period and fills their quiet days.

    That is right for a trend chart, where 40 permanently empty lines would be noise. A third option, members that had activity at any time in the last 90 days, is a good compromise for product catalogues. Pick deliberately, and write the choice into the model description, because two dashboards using different member lists will disagree on the count of rows and on every average computed over them.

    Dense grids also change how totals behave in BI tools. A pivot that sums the filled rows gives the same total as before, since the extra rows are zeros, but a "count of rows" tile or a distinct count of country-days now reports the grid size instead of active days. If a dashboard shows "active country-days", compute it from the facts as count(DISTINCT (day, country_code)) rather than from the filled output, or the number will always equal 372.

    When zero is the wrong fill, and where gap filling is heading

    The rule says every date gets a row. It does not say every empty value becomes 0, and the difference matters for anything that is not a count or a sum.

    Counts and sums of events are safe to fill with zero: no signups means 0 signups, no orders means 0 revenue. Averages are different. An average order value on a day with no orders is undefined, so filling it with 0 drags a weekly average down and suggests customers spent nothing. Ratios follow the same logic. A conversion rate should be computed from the filled counts with a guard on the denominator:

    conversion_rate = COALESCE(conversions, 0) / NULLIF(COALESCE(visits, 0), 0)
    

    On a day with 0 visits this returns NULL, which charts usually draw as a gap, and that gap is honest: there was nothing to convert. Running totals behave well after filling, because SUM over an ordered window simply carries the previous total forward across zero days. Moving averages finally mean what their name says once each row is one calendar day; on the filled 31-day March series, a 7-row window really is 7 days.

    Two kinds of empty day should not be zero at all. The first is today: a partial day with 6 hours of data is not a day with low activity, so either cut the range at yesterday or flag the current day. The second is data that has not arrived yet. If the pipeline loads with a 2-day lag, yesterday's zero may simply mean "not loaded". A load watermark solves it: compare each date with the latest fully loaded date and return NULL beyond it.

    value = CASE WHEN date_day > last_complete_date THEN NULL
                 ELSE COALESCE(metric, 0) END
    

    The direction tools are moving in makes the rule easier to apply without making it optional. Time series databases already ship gap filling as a function: TimescaleDB has time_bucket_gapfill, and BigQuery added a GAP_FILL table function for time series. Semantic layers go further, so a metric in dbt's semantic layer can declare that it should join to the time spine and fill nulls with zero, which moves the decision from every individual query into the metric definition. BI tools increasingly offer "show empty dates" as a checkbox.

    That shift is welcome, and it relocates the hard part instead of removing it. A checkbox can fill dates with zero, but it cannot know that average order value should stay NULL, that yesterday is not loaded yet, or that the member list for a coverage report differs from the one for a trend chart.

    As gap filling moves into metric definitions, the teams that keep their reports consistent will be the ones that write those semantics down once, next to the metric, and test them like any other piece of logic.

    Share:XLinkedInTelegramWhatsAppEmail