// dates & times reference

SQL DATE_BIN function

Floors a timestamp into fixed-width bins counted from an origin you choose, so buckets never reset at calendar boundaries.

類別
Dates & times
Returns
timestamp
In this category
88 of 121

語法

DATE_BIN(stride, source, origin)

引擎支援

引擎Support備註
SQL Server Different name or syntax DATE_BUCKET(MINUTE, 15, d [, origin]) on SQL Server 2022+
PostgreSQL 是 Supported under this name.
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

範例

PostgreSQL

SELECT date_bin('15 minutes', ts, TIMESTAMPTZ '2026-01-01 00:05:00+00') AS bucket, COUNT(*) FROM events GROUP BY 1;

PostgreSQL

SELECT date_bin('15 minutes', TIMESTAMP '2026-08-01 10:07', TIMESTAMP '2001-01-01');  -- 2026-08-01 10:00:00

小知識

  • date_trunc('hour', d) resets on the clock hour; date_bin('15 minutes', d) can align to :05, :20, :35, :50 by passing an origin; that is its whole point.
  • The stride cannot contain months or years; those vary in length and cannot form a fixed grid.
  • PostgreSQL requires the origin argument; date_bin('5 minutes', now()) fails with 'function does not exist'. TIMESTAMP '2001-01-01' is the usual choice, and because that was a Monday, '7 days' bins then start on Mondays.

Questions about DATE_BIN

DATE_BIN vs date_trunc?

date_trunc snaps to calendar boundaries (day, month); date_bin snaps to a fixed repeating grid counted from an origin. For 'every 90 minutes', only date_bin works.

What is the SQL Server equivalent?

DATE_BUCKET on SQL Server 2022+: DATE_BUCKET(MINUTE, 15, d, origin). Before 2022, rebuild the grid by hand: DATEADD(MINUTE, (DATEDIFF(MINUTE, '2026-01-01', d) / 15) * 15, '2026-01-01').

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.