SAMPLE BY
SAMPLE BY aggregates time-series data into time buckets. It groups rows by time intervals and applies aggregate functions.Basic SAMPLE BY
Time Units
Supported time units:s- secondsm- minutesh- hoursd- daysM- monthsy- years
SAMPLE BY with Multiple Aggregates
ALIGN TO CALENDAR
Align time buckets to calendar boundaries:ALIGN TO FIRST OBSERVATION
Align buckets to the first timestamp in the data:Time Zone Support
Specify time zone for calendar alignment:WITH OFFSET
Shift time buckets by an offset:FILL Strategy
Handle missing data in time buckets:FILL(NONE)
Default behavior - skip empty buckets:FILL(NULL)
Include empty buckets with NULL values:FILL(LINEAR)
Interpolate values for empty buckets:FILL(value)
Fill empty buckets with a constant:LATEST ON
LATEST ON retrieves the most recent row for each partition. It’s optimized for getting the latest value per group.Basic LATEST ON
LATEST ON with Multiple Partitions
LATEST ON with WHERE
LATEST ON in Subquery
Time Functions
timestamp_floor
Round timestamp down to time unit:timestamp_ceil
Round timestamp up to time unit:date_trunc
Truncate timestamp to specified precision:dateadd
Add time interval to timestamp:s, m, h, d, M, y
datediff
Calculate difference between timestamps:Extract Date Parts
now()
Get current timestamp:systimestamp()
Get system timestamp (same as now()):Time-Series Query Patterns
Hourly OHLC (Open, High, Low, Close)
Rolling Window Aggregation
Time-Weighted Average
Gap Detection
Find time gaps larger than threshold:Latest Value Per Symbol with Age
Performance Tips
- Designated timestamp column: Use
TIMESTAMP(column)in table definition for optimized time queries - Partition by time: Partition tables by DAY, MONTH, or YEAR for efficient time-range queries
- Filter on timestamp first: Apply timestamp filters before other conditions
- Use SYMBOL for grouping keys: SYMBOL columns are optimized for GROUP BY and PARTITION BY
- LATEST ON optimization: LATEST ON is more efficient than
ROW_NUMBER() OVER (... ORDER BY timestamp DESC) = 1
Next Steps
- Aggregations - Learn about aggregate functions
- Window Functions - Use analytical window functions
- JOIN Operations - Explore time-series joins