Skip to the page
Tecyfy

SQL interview question · hard

How can you use SQL to analyze time-series data?

The short answerSQL analyses time series with four tools: bucketing timestamps into periods and aggregating, window functions for running totals and moving averages, LAG and LEAD to compare each period with earlier ones, and a generated calendar to fill missing periods.

The full answer

SQL analyses time series with four tools: bucketing timestamps into periods and aggregating, window functions for running totals and moving averages, LAG and LEAD to compare each period with earlier ones, and a generated calendar to fill missing periods. The examples use PostgreSQL syntax.

1. Aggregate by period

SELECT DATE_TRUNC('month', sale_date) AS month,
       SUM(amount) AS revenue,
       COUNT(DISTINCT customer_id) AS customers
FROM sales
GROUP BY 1
ORDER BY 1;

2. Fill missing periods first Days with no sales have no rows, which breaks moving averages and charts. Join to a generated calendar:

WITH days AS (
    SELECT d::date AS day
    FROM generate_series(DATE '2026-01-01', DATE '2026-12-31', INTERVAL '1 day') AS d
),
daily AS (
    SELECT sale_date AS day, SUM(amount) AS revenue
    FROM sales
    GROUP BY sale_date
)
SELECT days.day, COALESCE(daily.revenue, 0) AS revenue
FROM days
LEFT JOIN daily ON daily.day = days.day;

3. Moving averages and running totals

SELECT day, revenue,
       AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7d,
       SUM(revenue) OVER (PARTITION BY DATE_TRUNC('month', day) ORDER BY day)   AS month_to_date
FROM daily_filled;

ROWS BETWEEN 6 PRECEDING means seven rows, which is seven days only if every day has exactly one row, which is why step 2 comes first. A RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW frame works on dates directly.

4. Period-over-period change

SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month)      AS change_vs_last_month,
       revenue / NULLIF(LAG(revenue, 12) OVER (ORDER BY month), 0) - 1 AS growth_vs_last_year
FROM monthly_revenue;

5. Other useful patterns

  • Gaps and islands to find streaks and outages.
  • Anomalies: compare each value with its moving average and standard deviation (STDDEV over a window).
  • First and last values per period with FIRST_VALUE and LAST_VALUE.

Practical points

  • Store timestamps in UTC and convert to local time zones for reporting periods.
  • Index or partition by the time column, and pre-aggregate large raw data into daily or hourly tables.
  • Choose the granularity for the question: daily data is noisy, monthly data hides short spikes.
  • Compare like with like: months have different numbers of days and weekends, so compare averages per day or the same period a year earlier, not raw monthly totals.
  • Watch for late-arriving data: the most recent day or hour is often incomplete, so a sudden drop at the end of a chart may only mean the data hasn't all landed yet. Mark or leave out the open period.
  • For very large event tables, time-series extensions and engines (TimescaleDB for PostgreSQL, or columnar warehouses) keep these queries fast with automatic time partitioning and continuous aggregates.

Last updated 16 October 2026

Sources

Where each fact comes from

  1. 1Window functions
  2. 2Set returning functions