Skip to content

AWS Athena: How do I generate a sequence of timestamps as individual records?

0

I am wanting to retrieve the min datetime and max datetime from a table and use those two values to generate records for every 5 minutes between those two datetime values.

timestamp
2025-10-22 00:00:00
2025-10-22 00:05:00
2025-10-22 00:10:00
2025-10-22 00:15:00
2025-10-22 00:20:00
........
2025-10-22 23:55:00

I found the sequence() function but it returns a single record: array(timestamp). So I tried using the UNNEST() function but it will not accept nested SELECT statements as part of the sequence parameters.

select 
    *
from 
        unnest(sequence(CAST((select min(datetime) from tableA) as timestamp), CAST((select max(datetime) from tableA) as timestamp), INTERVAL '5' MINUTE)) as t(date_values)

I've referenced the following other questions to try to find a solution:

AWS:Repost Question

Stack Overflow Question

Both of the above solutions return an array of values, whereas I want each value to be it's own record so that I can join do joins with each value.

What would be the best way to accomplish what I've exampled above in the table?

asked 10 months ago183 views

1 Answer
0
Accepted Answer

To generate a sequence of timestamps as individual records in Athena, you need to use a combination of the sequence() function and UNNEST(). The issue with your current approach is that you're trying to use subqueries directly within the sequence() function parameters, which isn't supported.

Here's how you can accomplish this:

WITH date_range AS (
SELECT 
MIN(datetime) AS min_date,
MAX(datetime) AS max_date
FROM tableA
)
SELECT 
date_value
FROM 
date_range,
UNNEST(sequence(
CAST(min_date AS timestamp), 
CAST(max_date AS timestamp), 
INTERVAL '5' MINUTE
)) AS t(date_value)

This query:

  1. Creates a CTE (Common Table Expression) called date_range that gets the minimum and maximum datetime values from your table
  2. Uses the sequence() function to generate an array of timestamps at 5-minute intervals
  3. Uses UNNEST() to convert the array into individual rows
  4. Returns each timestamp as a separate record

The result will be a table with individual timestamp records at 5-minute intervals between your min and max datetime values, exactly as you showed in your example.

If you need to join these timestamps with other data, you can now use this as a subquery or CTE in a larger query and perform joins as needed.
Sources
Array functions - Amazon Timestream
Create arrays from subqueries - Amazon Athena

answered 10 months ago

EXPERT

reviewed 10 months ago

  • Thank you! I was on the right path, just had to adjust the syntax.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.