SELECT knowledge FROM sql_resources WHERE category='bigquery-standard-sql' AND slug='date-trunc'
DATE_TRUNC
See also DATETIME_TRUNC, TIMESTAMP_TRUNC, TIME_TRUNC
Definition
The DATE_TRUNC
function in BigQuery will truncate the date to the given date_part
.
Where date_part
can be any of the following:
DATE_TRUNC(date_expression, date_part)
WEEK()
: Truncatesdate_expression
to the preceding week boundary, where weeks begin onWEEKDAY
. Valid values forWEEKDAY
areSUNDAY
,MONDAY
,TUESDAY
,WEDNESDAY
,THURSDAY
,FRIDAY
, andSATURDAY
.ISOWEEK
: Truncatesdate_expression
to the preceding ISO 8601 week boundary.ISOWEEK
s begin on Monday. The firstISOWEEK
of each ISO year contains the first Thursday of the corresponding Gregorian calendar year. Anydate_expression
earlier than this will truncate to the preceding Monday.ISOYEAR
: Truncatesdate_expression
to the preceding ISO 8601 week-numbering year boundary. The ISO year boundary is the Monday of the first week whose Thursday belongs to the corresponding Gregorian calendar year.
Returns: DATE
month | week | year |
---|---|---|
2021-01-01 | 2020-12-27 | 2021-01-01 |
Practical Info
- Always returns a
DATE
, so even if you are truncating to theYEAR
, you'll received back the first day of that year. For that reason, it's often use in conjunction withFORMAT_DATE
if you want to just use the yearYYYY
. - Be careful when dealing with multiple
TRUNC
s - as seen in the example above, a date in 2021 can be counted in 2020 if the first day of the week was there. So if you counted byYEAR
vsYEAR(WEEK)
you would get different results.
Common Questions
How do I aggregate my data by month?
DATE_TRUNC
is very handy for aggregating your data by a particular date_part
, like MONTH
. See the example below to see how you can aggregate by MONTH
:
Loading code...
total | month |
---|---|
10 | 2021-02-01 |
27 | 2021-01-01 |
Make sure you've included your DATE_TRUNC
column in your GROUP BY
!
Troubleshooting Common Errors
Argument 1 of DATE_TRUNC has incorrect type: expected date found timestamp.
Loading code...
You'll need to make sure you're using the right function for your data type. To use DATE_TRUNC
, you must be working with a DATE
, and not a DATETIME
, TIMESTAMP
, or TIME
.
You can use CAST
to change your other date types to DATE
, or use one of the equivalent functions for other date types like DATETIME_TRUNC
.
Related Pages
- DATETIME_TRUNC
- Dates and Times in Standard SQL