Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server DATE_BUCKET: A How-To Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

SQL Server's DATE_BUCKET function (introduced in SQL Server 2022 and Azure SQL) groups any date or time value into fixed-size buckets, such as every 5 minutes, every 2 days, or every 3 months, starting from an origin you choose. It returns a single datetime value representing the start of the bucket that contains the input, which makes it ideal for time-series aggregation, downsampling, and reporting without complex date math. You need SQL Server 2022 or later (or Azure SQL Database/Managed Instance) and a basic understanding of T-SQL date types.

What You'll Need

  • SQL Server 2022 or later, or Azure SQL Database / Azure SQL Managed Instance. The function is not available in SQL Server 2019 or earlier.
  • A database where you can run queries (any user with SELECT permission on the target table).
  • A date, datetime, datetime2, or smalldatetime column or variable to bucket.
  • Optional: a numbers or calendar table if you need to generate empty buckets for gaps.

Step-by-Step

  1. Confirm your version supports DATE_BUCKET. Run SELECT @@VERSION; and check that it reports SQL Server 2022 (major version 16) or higher, or that you are connected to Azure SQL. If you see version 15 or lower, the function will raise “'DATE_BUCKET' is not a recognized built-in function name.”
  2. Understand the syntax. The full form is DATE_BUCKET ( datepart, number, date [, origin ] ). datepart is the unit (e.g., MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR), number is the bucket width (a positive integer), date is the value to bucket, and the optional origin sets the anchor point. If you omit origin, the default is 1900-01-01 00:00:00.000.
  3. Bucket a single value. Try SELECT DATE_BUCKET(MINUTE, 5, '2024-03-15T10:07:32'); This returns 2024-03-15 10:05:00 — the start of the 5-minute bucket containing 10:07:32. The result type matches the input date type.
  4. Choose an origin deliberately. The origin defines where buckets begin. For example, DATE_BUCKET(DAY, 7, '2024-03-15', '2024-01-01'); creates 7-day buckets anchored to January 1, 2024, so the bucket containing March 15 starts on March 11 (the Monday nearest the anchor, depending on the anchor's weekday). Pick an origin that matches your reporting cycle (fiscal year start, first day of the month, etc.).
  5. Aggregate a table by bucket. Use DATE_BUCKET in the GROUP BY and SELECT list. For a table SensorReadings(ReadingTime datetime2, Value float):
    SELECT
      DATE_BUCKET(MINUTE, 15, ReadingTime) AS BucketStart,
      AVG(Value) AS AvgValue,
      COUNT(*) AS Readings
    FROM SensorReadings
    GROUP BY DATE_BUCKET(MINUTE, 15, ReadingTime)
    ORDER BY BucketStart;
    This collapses each 15-minute window into one row. Because the expression is identical in SELECT and GROUP BY, SQL Server can use it directly.
  6. Filter before grouping. Add a WHERE clause on the raw column (not the bucket) to limit the scan, e.g., WHERE ReadingTime >= '2024-03-01' AND ReadingTime < '2024-04-01'. Filtering on the bucket expression can prevent index usage.
  7. Handle gaps if needed. DATE_BUCKET only returns buckets that contain rows. To show empty buckets, generate a series of bucket starts with a numbers table or a recursive CTE and LEFT JOIN your aggregated query to it.
  8. Use it in a computed column or view. You can wrap the expression in a view for reuse. Note that DATE_BUCKET is deterministic, so it can be used in indexed views only if the underlying expression is also deterministic and precise — test before relying on it.

Common Mistakes

  • Using it on SQL Server 2019 or older. The function does not exist there; you must rewrite with DATEADD/DATEDIFF math or upgrade.
  • Passing a negative or zero number. The bucket width must be a positive integer; zero or negative values raise an error.
  • Forgetting the origin. The default origin of 1900-01-01 means weekly buckets start on a Monday only if that anchor aligns; if your business week starts Sunday, set an explicit origin.
  • Mixing date types. The return type follows the input date argument. Passing a date with a MINUTE datepart truncates time to midnight, which may surprise you.
  • Filtering on the bucket expression. WHERE DATE_BUCKET(...) = ... is non-sargable; filter on the raw column instead.
  • Assuming it fills gaps. It does not generate rows for empty buckets.

Tips

  • Use DATE_BUCKET instead of nested DATEADD/DATEDIFF for readability; it is also generally faster because the optimizer understands it.
  • For monthly or quarterly reporting, set origin to the first day of your fiscal year to align buckets correctly.
  • Combine with FORMAT or CONVERT in the SELECT list for display, but keep the raw bucket value for sorting and joining.
  • Test bucket boundaries with sample values around midnight, month-end, and leap days to confirm the origin behaves as expected.
  • If you need to support older versions, create a scalar function that mimics DATE_BUCKET using DATEDIFF and DATEADD, then swap it out after upgrading.

Troubleshooting

  • “'DATE_BUCKET' is not a recognized built-in function name.” You are on an older version or compatibility level. Check SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME(); — the database must be at compatibility level 160 or higher for SQL Server 2022 features. Raise it with ALTER DATABASE ... SET COMPATIBILITY_LEVEL = 160; after testing.
  • Unexpected bucket starts. Print the origin and a few sample inputs. Remember that buckets are counted forward from the origin, not backward from “now.” Adjust the origin.
  • Wrong data type returned. Cast the input explicitly, e.g., CAST(ReadingTime AS datetime2), to control precision.
  • Performance regression. Check the execution plan; if the bucket expression appears in a predicate, rewrite the WHERE clause to use the raw column. Ensure statistics are up to date.
  • Errors with smalldatetime. smalldatetime has minute precision; bucketing to seconds will not produce distinct buckets. Use datetime2 for finer granularity.

Frequently Asked Questions

Which SQL Server versions include DATE_BUCKET?

SQL Server 2022 and later, plus Azure SQL Database and Azure SQL Managed Instance. It is not in SQL Server 2019 or earlier.

Can I use DATE_BUCKET with a column in GROUP BY?

Yes. Put the same DATE_BUCKET expression in both SELECT and GROUP BY; the optimizer handles it efficiently.

What happens if I omit the origin argument?

The default origin is 1900-01-01 00:00:00.000. Buckets are counted from that point, which may not match your reporting calendar.

Does DATE_BUCKET return NULL for NULL input?

Yes, it returns NULL when the date argument is NULL.

Can I bucket by weeks starting on Sunday?

Yes, pass an origin that falls on a Sunday, e.g., '2024-01-07', and use WEEK as the datepart.

Is DATE_BUCKET available in SQL Server 2019 compatibility mode?

No. The database compatibility level must be 160 or higher, and the engine must be SQL Server 2022 or newer.