In this post we are going to cover DAYNAME, MONTHNAME, splitting a week into weekdays and weekends, and TIME_SLICE in Snowflake.
DAYNAME and MONTHNAME turn a date into text. TIME_SLICE does something different. It puts a date or a timestamp into a fixed-width bucket, so you can group a time series into even windows.
We will start with the two name functions and build it up step by step. On the way we will write a day-of-week report that comes out in alphabetical order, check a hand-written mapping instead of trusting it, and find out that TIME_SLICE's seven-day buckets are not weeks.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 74 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with DAYNAME and MONTHNAME
- Now let's write a day-of-week report
- What if we need the word Sunday?
- Now let's split the week into weekday and weekend
- Where did 0 and 6 come from? Let's check them
- Can we snap a date to its Monday without that parameter?
- Now let's try TIME_SLICE
- Let's watch it group
- Now let's try it on dates. Does it follow the calendar?
- One last thing: a bucketing that grouped nothing
Let's create some sample data
This is the third of five posts on dates, and it runs against the same ORDERS table as the rest of the course. The script below sets up the fixed anchor date that the generated grids on this page count forward from.
Copy it into a Snowflake worksheet and run it once.
-- ORDERS comes from the setup script this course uses throughout.
-- Run it once; every episode reuses the same tables.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
-- The generated grids on this page count forward from one fixed date instead
-- of CURRENT_DATE, so nothing here depends on the clock.
SELECT DATE '2024-06-30' AS ANCHOR;Here are the orders we will be working on.
SELECT ORDER_ID, CUSTOMER_ID, ORDER_DATE, AMOUNT, STATUS
FROM ORDERS ORDER BY ORDER_DATE LIMIT 10;| ORDER_ID | CUSTOMER_ID | ORDER_DATE | AMOUNT | STATUS |
|---|---|---|---|---|
| 1001 | 101 | 2023-01-12 | 4200.00 | SHIPPED |
| 1002 | 102 | 2023-01-28 | 890.50 | SHIPPED |
| 1003 | 101 | 2023-02-14 | 6150.00 | SHIPPED |
| 1004 | 103 | 2023-02-27 | 1500.00 | CANCELLED |
| 1005 | 104 | 2023-03-09 | 2310.75 | SHIPPED |
| 1006 | 101 | 2023-03-22 | 5020.00 | SHIPPED |
| 1007 | 105 | 2023-04-05 | 7890.00 | SHIPPED |
| 1008 | 102 | 2023-04-19 | 1120.00 | SHIPPED |
| 1009 | 103 | 2023-05-02 | 3340.25 | SHIPPED |
| 1010 | 106 | 2023-05-21 | 640.00 | PENDING |
We also want one full week to read the day numbering off, so let's generate seven consecutive days from the anchor with each day's name and number beside it.
SELECT D.THE_DATE,
DAYNAME(D.THE_DATE) AS DAY_NAME,
DATE_PART('dayofweek', D.THE_DATE) AS DOW
FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-06-30') AS THE_DATE
FROM TABLE(GENERATOR(ROWCOUNT => 7))) D
ORDER BY D.THE_DATE;| THE_DATE | DAY_NAME | DOW |
|---|---|---|
| 2024-06-30 | Sun | 0 |
| 2024-07-01 | Mon | 1 |
| 2024-07-02 | Tue | 2 |
| 2024-07-03 | Wed | 3 |
| 2024-07-04 | Thu | 4 |
| 2024-07-05 | Fri | 5 |
| 2024-07-06 | Sat | 6 |
Sun is 0 and Sat is 6. That is the 'dayofweek' numbering from Episode 73, and two separate things later on this page depend on it, so this grid is worth keeping in view.
Let's start with DAYNAME and MONTHNAME
Both of these take a date and give back text. The interesting part is how much text, and that is a thing to measure rather than assume.
So let's measure it.
SELECT DATE '2024-06-30' AS ANCHOR,
DAYNAME(DATE '2024-06-30') AS DAY_NAME,
LENGTH(DAYNAME(DATE '2024-06-30')) AS DAY_NAME_LENGTH,
MONTHNAME(DATE '2024-06-30') AS MONTH_NAME,
LENGTH(MONTHNAME(DATE '2024-06-30')) AS MONTH_NAME_LENGTH;| ANCHOR | DAY_NAME | DAY_NAME_LENGTH | MONTH_NAME | MONTH_NAME_LENGTH |
|---|---|---|---|---|
| 2024-06-30 | Sun | 3 | Jun | 3 |
We got Sun and Jun, and LENGTH says 3 for both of them.
These are abbreviations and that is all they do. There is no argument for a full name, no locale switch, and no sibling function that gives you the word Sunday.
Let's get all twelve month abbreviations out while we are here, so you have them.
SELECT M.THE_DATE,
MONTHNAME(M.THE_DATE) AS MONTH_NAME,
DATE_PART('month', M.THE_DATE) AS MONTH_NUMBER
FROM (SELECT DATEADD('month', SEQ4(), DATE '2024-01-15') AS THE_DATE
FROM TABLE(GENERATOR(ROWCOUNT => 12))) M
ORDER BY M.THE_DATE;| THE_DATE | MONTH_NAME | MONTH_NUMBER |
|---|---|---|
| 2024-01-15 | Jan | 1 |
| 2024-02-15 | Feb | 2 |
| 2024-03-15 | Mar | 3 |
| 2024-04-15 | Apr | 4 |
| 2024-05-15 | May | 5 |
| 2024-06-15 | Jun | 6 |
| 2024-07-15 | Jul | 7 |
| 2024-08-15 | Aug | 8 |
| 2024-09-15 | Sep | 9 |
| 2024-10-15 | Oct | 10 |
| 2024-11-15 | Nov | 11 |
| 2024-12-15 | Dec | 12 |
Twelve rows, three letters each, and in every case they are the first three letters of the English month name.
That matters more than it looks. It means the first three characters of a month name are a reliable thing to compare against MONTHNAME, and we are going to use exactly that property to check a hand-written mapping later on.
Now let's write a day-of-week report
Here is the report anybody would write. Orders per day of the week, grouped by the day name and ordered by it.
SELECT DAYNAME(ORDER_DATE) AS DAY_NAME, COUNT(*) AS ORDERS_
FROM ORDERS
GROUP BY DAYNAME(ORDER_DATE)
ORDER BY DAY_NAME;| DAY_NAME | ORDERS_ |
|---|---|
| Fri | 3 |
| Mon | 4 |
| Sat | 6 |
| Sun | 6 |
| Thu | 6 |
| Tue | 8 |
| Wed | 8 |
Fri, Mon, Sat, Sun, Thu, Tue, Wed. That is a week in alphabetical order. The query is correct, it errors on nothing, and nobody has ever read a week that way.
The reason is one sentence. DAYNAME returns text, and ORDER BY sorts text. There is no weekday-ness in that column for Snowflake to sort by.
So let's carry the number as well
We can group by the day number alongside the name and order by the number. The name stays in the output as a label and the number does the sorting.
SELECT DATE_PART('dayofweek', ORDER_DATE) AS DOW,
DAYNAME(ORDER_DATE) AS DAY_NAME,
COUNT(*) AS ORDERS_,
ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS
GROUP BY DATE_PART('dayofweek', ORDER_DATE), DAYNAME(ORDER_DATE)
ORDER BY DOW;| DOW | DAY_NAME | ORDERS_ | TOTAL |
|---|---|---|---|
| 0 | Sun | 6 | 28570.50 |
| 1 | Mon | 4 | 16350.00 |
| 2 | Tue | 8 | 45770.25 |
| 3 | Wed | 8 | 50390.00 |
| 4 | Thu | 6 | 31570.75 |
| 5 | Fri | 3 | 7545.00 |
| 6 | Sat | 6 | 25230.50 |
Same seven days and the same seven counts, in an order a person can read. There is a total in this one as well, which is just along for the ride.
Both versions group on something derived from the same date, so let's confirm that neither of them lost or invented a row.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT(DISTINCT DAYNAME(ORDER_DATE)) AS DISTINCT_NAMES,
COUNT(DISTINCT DATE_PART('dayofweek', ORDER_DATE)) AS DISTINCT_NUMBERS
FROM ORDERS;| ROWS_TOTAL | DISTINCT_NAMES | DISTINCT_NUMBERS |
|---|---|---|
| 41 | 7 | 7 |
41 orders, 7 distinct day names, 7 distinct day numbers. Both groupings cover exactly the same ground, so it was purely an ordering problem.
That is worth establishing, because the bug that looks just like this one in Episode 73 was not an ordering problem at all. There the two counts disagreed, and rows really had been merged.
The same trap shows up with month names, status codes, priority labels and anything else where the display value is a word and the order you want is not alphabetical. Group by the thing that sorts and keep the word as a label.
What if we need the word Sunday?
Since there is no full-name function, the mapping is ours to write. DECODE over the day number is the compact way to do it, with a final value for anything that does not match.
Let's run a whole week through it.
SELECT D.THE_DATE,
DAYNAME(D.THE_DATE) AS ABBREVIATED,
DECODE(DATE_PART('dayofweek', D.THE_DATE),
0, 'Sunday', 1, 'Monday', 2, 'Tuesday', 3, 'Wednesday',
4, 'Thursday', 5, 'Friday', 6, 'Saturday', 'UNEXPECTED') AS FULL_NAME
FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-06-30') AS THE_DATE
FROM TABLE(GENERATOR(ROWCOUNT => 7))) D
ORDER BY D.THE_DATE;| THE_DATE | ABBREVIATED | FULL_NAME |
|---|---|---|
| 2024-06-30 | Sun | Sunday |
| 2024-07-01 | Mon | Monday |
| 2024-07-02 | Tue | Tuesday |
| 2024-07-03 | Wed | Wednesday |
| 2024-07-04 | Thu | Thursday |
| 2024-07-05 | Fri | Friday |
| 2024-07-06 | Sat | Saturday |
Each full name sits beside the abbreviation it came from, and it all looks right.
But looks right is not a standard worth shipping a hand-written mapping on.
So let's check it, in one query
We will take four weeks of dates and ask two questions. Did anything fall through to the fallback value? And do the first three characters of each answer match what DAYNAME says on its own?
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(DECODE(DATE_PART('dayofweek', D.THE_DATE),
0, 'Sunday', 1, 'Monday', 2, 'Tuesday', 3, 'Wednesday',
4, 'Thursday', 5, 'Friday', 6, 'Saturday', 'UNEXPECTED')
= 'UNEXPECTED') AS FELL_THROUGH,
COUNT_IF(LEFT(DECODE(DATE_PART('dayofweek', D.THE_DATE),
0, 'Sunday', 1, 'Monday', 2, 'Tuesday', 3, 'Wednesday',
4, 'Thursday', 5, 'Friday', 6, 'Saturday', 'UNEXPECTED'), 3)
= DAYNAME(D.THE_DATE)) AS AGREES_WITH_DAYNAME
FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-06-30') AS THE_DATE
FROM TABLE(GENERATOR(ROWCOUNT => 28))) D;| ROWS_TOTAL | FELL_THROUGH | AGREES_WITH_DAYNAME |
|---|---|---|
| 28 | 0 | 28 |
28 days, 0 fell through, and 28 agree with DAYNAME.
The second column is the real check, because it compares our hand-written mapping against Snowflake's own answer rather than against itself. The fallback count on its own would have passed even if every single name were shifted by one day.
That fallback value is not decoration either. DECODE with no fallback returns NULL for an unmatched input, and a NULL in a label column is far harder to spot in a report than the word UNEXPECTED.
Now let's split the week into weekday and weekend
The usual way to do this is a CASE on the day number. Let's run it over the first ten orders, and leave the name and the number in the output so the answer can be checked by eye.
SELECT ORDER_ID, ORDER_DATE,
DAYNAME(ORDER_DATE) AS DAY_NAME,
DATE_PART('dayofweek', ORDER_DATE) AS DOW,
CASE WHEN DATE_PART('dayofweek', ORDER_DATE) IN (0, 6)
THEN 'Weekend' ELSE 'Weekday' END AS KIND
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 10;| ORDER_ID | ORDER_DATE | DAY_NAME | DOW | KIND |
|---|---|---|---|---|
| 1001 | 2023-01-12 | Thu | 4 | Weekday |
| 1002 | 2023-01-28 | Sat | 6 | Weekend |
| 1003 | 2023-02-14 | Tue | 2 | Weekday |
| 1004 | 2023-02-27 | Mon | 1 | Weekday |
| 1005 | 2023-03-09 | Thu | 4 | Weekday |
| 1006 | 2023-03-22 | Wed | 3 | Weekday |
| 1007 | 2023-04-05 | Wed | 3 | Weekday |
| 1008 | 2023-04-19 | Wed | 3 | Weekday |
| 1009 | 2023-05-02 | Tue | 2 | Weekday |
| 1010 | 2023-05-21 | Sun | 0 | Weekend |
Sat at 6 and Sun at 0 came back as Weekend, and everything else is a Weekday.
Keeping those two middle columns in a working query costs nothing and makes a wrong answer visible immediately.
Now let's roll it up, which is what the report actually wanted.
SELECT CASE WHEN DATE_PART('dayofweek', ORDER_DATE) IN (0, 6)
THEN 'Weekend' ELSE 'Weekday' END AS KIND,
COUNT(*) AS ORDERS_,
ROUND(SUM(AMOUNT), 2) AS TOTAL,
ROUND(AVG(AMOUNT), 2) AS AVERAGE
FROM ORDERS
GROUP BY 1
ORDER BY ORDERS_ DESC;| KIND | ORDERS_ | TOTAL | AVERAGE |
|---|---|---|---|
| Weekday | 29 | 151626.00 | 5415.21 |
| Weekend | 12 | 53801.00 | 4483.42 |
29 weekday orders and 12 weekend ones, with their totals and averages.
Those two counts add up to the 41 from the previous section. And the 12 is the Sat and Sun rows of the day-number grid added together, so the split is consistent with everything above it.
The two averages differ, and this post is not going to build a story on that. Twelve orders is not a sample that supports a claim about weekend buying behaviour. The grid is here to show the shape of the query, not to argue for a conclusion.
Where did 0 and 6 come from? Let's check them
Stop and look at that CASE again. It tests for 0 and 6, and those two values come from the 'dayofweek' numbering, which as Episode 73 showed comes from a session parameter.
So they are magic numbers whose meaning is configurable. Let's check them against something that does not use them.
DAYNAME does not read the day number, so it is an independent witness. We will ask both directions at once. Is anything marked Weekend whose name is not Sat or Sun, and is anything marked Weekday whose name is?
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(DATE_PART('dayofweek', ORDER_DATE) IN (0, 6)
AND DAYNAME(ORDER_DATE) NOT IN ('Sat', 'Sun')) AS WRONGLY_WEEKEND,
COUNT_IF(DATE_PART('dayofweek', ORDER_DATE) NOT IN (0, 6)
AND DAYNAME(ORDER_DATE) IN ('Sat', 'Sun')) AS WRONGLY_WEEKDAY
FROM ORDERS;| ROWS_TOTAL | WRONGLY_WEEKEND | WRONGLY_WEEKDAY |
|---|---|---|
| 41 | 0 | 0 |
0 and 0, across all 41 rows. The magic numbers agree with the names.
That is one extra query, it runs once, and it turns an assumption into a checked fact. Which is the habit worth taking away from this post.
This check passed on this session. It is not a proof that 0 and 6 are the weekend everywhere, because the numbering they come from moves with WEEK_START. If you want a weekend test that cannot move, write it against 'dayofweekiso', whose numbering is fixed by the ISO standard rather than by a setting. The captured grid for it is in Episode 73.
Can we snap a date to its Monday without that parameter?
Same argument as the last section, on a more useful problem. DATE_TRUNC('week', ...) gives us the start of the week, but which day that is depends on WEEK_START.
The ISO parts do not depend on it, so we can build the Monday ourselves. Take 'dayofweekiso', subtract one, and go back that many days.
Let's run that beside DATE_TRUNC and compare.
SELECT D.THE_DATE,
DAYNAME(D.THE_DATE) AS DAY_NAME,
DATE_TRUNC('week', D.THE_DATE) AS TRUNC_WEEK,
DATEADD('day', -MOD(DATE_PART('dayofweekiso', D.THE_DATE) - 1, 7), D.THE_DATE)
AS ISO_MONDAY
FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-06-30') AS THE_DATE
FROM TABLE(GENERATOR(ROWCOUNT => 7))) D
ORDER BY D.THE_DATE;| THE_DATE | DAY_NAME | TRUNC_WEEK | ISO_MONDAY |
|---|---|---|---|
| 2024-06-30 | Sun | 2024-06-24 | 2024-06-24 |
| 2024-07-01 | Mon | 2024-07-01 | 2024-07-01 |
| 2024-07-02 | Tue | 2024-07-01 | 2024-07-01 |
| 2024-07-03 | Wed | 2024-07-01 | 2024-07-01 |
| 2024-07-04 | Thu | 2024-07-01 | 2024-07-01 |
| 2024-07-05 | Fri | 2024-07-01 | 2024-07-01 |
| 2024-07-06 | Sat | 2024-07-01 | 2024-07-01 |
Identical on all seven days. The Sun row is the interesting one: both expressions sent it back to 2024-06-24 rather than forward, because ISO numbering puts Sunday at the end of its week. The other six rows all snapped to 2024-07-01.
Seven days is a small sample for a claim of equivalence, so let's widen it.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(DATE_TRUNC('week', D.THE_DATE)
= DATEADD('day', -MOD(DATE_PART('dayofweekiso', D.THE_DATE) - 1, 7),
D.THE_DATE)) AS AGREE
FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-01-01') AS THE_DATE
FROM TABLE(GENERATOR(ROWCOUNT => 60))) D;| ROWS_TOTAL | AGREE |
|---|---|
| 60 | 60 |
60 out of 60 agree. So if you want the Monday of a date's week and you do not want to depend on a session parameter, that is the expression, and this grid is the reason to trust it rather than the fact that it looks plausible.
The subtraction is what makes it work on a Monday. 'dayofweekiso' is 1 there, so the expression goes back zero days and gives us the date itself. That is unlike NEXT_DAY and PREVIOUS_DAY from Episode 73, which are strict and never return the date you gave them.
The MOD is a guard rather than the mechanism. 'dayofweekiso' only ever returns 1 through 7, so subtracting one gives a number from 0 to 6, and MOD by seven leaves every one of those alone.
Now let's try TIME_SLICE
TIME_SLICE is the last function on this page and it is the most immediately useful one. It takes a timestamp, a width and a unit, and gives back the start of the fixed-width window that timestamp falls in.
Let's put one timestamp through four different widths.
SELECT '2024-06-30 14:37:52'::TIMESTAMP_NTZ AS ANCHOR,
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 15, 'minute') AS EVERY_15_MIN,
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 30, 'minute') AS EVERY_30_MIN,
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 4, 'hour') AS EVERY_4_HOURS,
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 1, 'hour') AS EVERY_HOUR;| ANCHOR | EVERY_15_MIN | EVERY_30_MIN | EVERY_4_HOURS | EVERY_HOUR |
|---|---|---|---|---|
| 2024-06-30 14:37:52 | 2024-06-30 14:30:00 | 2024-06-30 14:30:00 | 2024-06-30 12:00:00 | 2024-06-30 14:00:00 |
Each answer rounded down to its own bucket start. That is what makes the function usable as a GROUP BY key, because every timestamp in a window produces the identical value.
There is a fourth argument
Let's ask for the start and the end of the same window, and measure the gap between them in the query.
SELECT '2024-06-30 14:37:52'::TIMESTAMP_NTZ AS ANCHOR,
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 15, 'minute', 'START') AS SLICE_START,
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 15, 'minute', 'END') AS SLICE_END,
DATEDIFF('minute',
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 15, 'minute', 'START'),
TIME_SLICE('2024-06-30 14:37:52'::TIMESTAMP_NTZ, 15, 'minute', 'END'))
AS SLICE_WIDTH_MINUTES;| ANCHOR | SLICE_START | SLICE_END | SLICE_WIDTH_MINUTES |
|---|---|---|---|
| 2024-06-30 14:37:52 | 2024-06-30 14:30:00 | 2024-06-30 14:45:00 | 15 |
'START' is the default and gave us the beginning of the window. 'END' gave us the beginning of the next one, and the last column measures the gap: 15 minutes, the width we asked for.
Because 'END' is the next window's start rather than the last instant of this one, a range test written with it wants >= start AND < end. Half-open, no gap, no overlap, and no need to subtract a second from anything.
Let's watch it group
The grids so far show one timestamp at a time, which does not show the point of the function.
So let's generate twelve readings five minutes apart across one hour and put each one's slice beside it.
SELECT T.TS,
TIME_SLICE(T.TS, 15, 'minute') AS SLICE_
FROM (SELECT DATEADD('minute', SEQ4() * 5,
'2024-06-30 14:00:00'::TIMESTAMP_NTZ) AS TS
FROM TABLE(GENERATOR(ROWCOUNT => 12))) T
ORDER BY T.TS;| TS | SLICE_ |
|---|---|
| 2024-06-30 14:00:00 | 2024-06-30 14:00:00 |
| 2024-06-30 14:05:00 | 2024-06-30 14:00:00 |
| 2024-06-30 14:10:00 | 2024-06-30 14:00:00 |
| 2024-06-30 14:15:00 | 2024-06-30 14:15:00 |
| 2024-06-30 14:20:00 | 2024-06-30 14:15:00 |
| 2024-06-30 14:25:00 | 2024-06-30 14:15:00 |
| 2024-06-30 14:30:00 | 2024-06-30 14:30:00 |
| 2024-06-30 14:35:00 | 2024-06-30 14:30:00 |
| 2024-06-30 14:40:00 | 2024-06-30 14:30:00 |
| 2024-06-30 14:45:00 | 2024-06-30 14:45:00 |
| 2024-06-30 14:50:00 | 2024-06-30 14:45:00 |
| 2024-06-30 14:55:00 | 2024-06-30 14:45:00 |
The SLICE_ column changes every third row, and the first row of each run of three is a timestamp that is its own slice start. That repetition is the whole mechanism: distinct inputs, identical bucket keys.
Now let's group by the slice and count.
SELECT TIME_SLICE(T.TS, 15, 'minute') AS SLICE_, COUNT(*) AS N
FROM (SELECT DATEADD('minute', SEQ4() * 5,
'2024-06-30 14:00:00'::TIMESTAMP_NTZ) AS TS
FROM TABLE(GENERATOR(ROWCOUNT => 12))) T
GROUP BY TIME_SLICE(T.TS, 15, 'minute')
ORDER BY SLICE_;| SLICE_ | N |
|---|---|
| 2024-06-30 14:00:00 | 3 |
| 2024-06-30 14:15:00 | 3 |
| 2024-06-30 14:30:00 | 3 |
| 2024-06-30 14:45:00 | 3 |
4 slices, 3 rows in each. Even buckets, with nothing skipped and nothing doubled up. That is the shape a time-series chart needs, and it is the reason to reach for TIME_SLICE rather than rounding a timestamp by hand.
Now let's try it on dates. Does it follow the calendar?
TIME_SLICE works on DATE columns too, with day and month widths. Let's ask for three widths at once.
SELECT ORDER_ID, ORDER_DATE,
TIME_SLICE(ORDER_DATE, 7, 'day') AS WEEK_BUCKET,
TIME_SLICE(ORDER_DATE, 10, 'day') AS TEN_DAY_BUCKET,
TIME_SLICE(ORDER_DATE, 2, 'month') AS TWO_MONTH_BUCKET
FROM ORDERS
ORDER BY ORDER_DATE
LIMIT 10;| ORDER_ID | ORDER_DATE | WEEK_BUCKET | TEN_DAY_BUCKET | TWO_MONTH_BUCKET |
|---|---|---|---|---|
| 1001 | 2023-01-12 | 2023-01-12 | 2023-01-03 | 2023-01-01 |
| 1002 | 2023-01-28 | 2023-01-26 | 2023-01-23 | 2023-01-01 |
| 1003 | 2023-02-14 | 2023-02-09 | 2023-02-12 | 2023-01-01 |
| 1004 | 2023-02-27 | 2023-02-23 | 2023-02-22 | 2023-01-01 |
| 1005 | 2023-03-09 | 2023-03-09 | 2023-03-04 | 2023-03-01 |
| 1006 | 2023-03-22 | 2023-03-16 | 2023-03-14 | 2023-03-01 |
| 1007 | 2023-04-05 | 2023-03-30 | 2023-04-03 | 2023-03-01 |
| 1008 | 2023-04-19 | 2023-04-13 | 2023-04-13 | 2023-03-01 |
| 1009 | 2023-05-02 | 2023-04-27 | 2023-04-23 | 2023-05-01 |
| 1010 | 2023-05-21 | 2023-05-18 | 2023-05-13 | 2023-05-01 |
The two-month buckets look like what you would expect. They land on the 1st of a month.
The seven-day and ten-day ones do not line up with anything in the calendar. Order 1007 is dated in April and sits in a seven-day bucket that starts in March.
The clearest evidence is in the composed query, because it is the one grid here carrying a day name and a seven-day bucket start side by side.
SELECT ORDER_ID, ORDER_DATE,
DAYNAME(ORDER_DATE) AS DAY_NAME,
MONTHNAME(ORDER_DATE) AS MONTH_NAME,
DATE_PART('dayofweek', ORDER_DATE) AS DOW,
CASE WHEN DATE_PART('dayofweek', ORDER_DATE) IN (0, 6)
THEN 'Weekend' ELSE 'Weekday' END AS KIND,
TIME_SLICE(ORDER_DATE, 7, 'day') AS WEEK_BUCKET
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 5;| ORDER_ID | ORDER_DATE | DAY_NAME | MONTH_NAME | DOW | KIND | WEEK_BUCKET |
|---|---|---|---|---|---|---|
| 1001 | 2023-01-12 | Thu | Jan | 4 | Weekday | 2023-01-12 |
| 1002 | 2023-01-28 | Sat | Jan | 6 | Weekend | 2023-01-26 |
| 1003 | 2023-02-14 | Tue | Feb | 2 | Weekday | 2023-02-09 |
| 1004 | 2023-02-27 | Mon | Feb | 1 | Weekday | 2023-02-23 |
| 1005 | 2023-03-09 | Thu | Mar | 4 | Weekday | 2023-03-09 |
Two rows have an order date that is also its own seven-day bucket start. Order 1001 on 2023-01-12 and order 1005 on 2023-03-09. The DAY_NAME column says both of those are a Thu.
So TIME_SLICE's seven-day buckets do not begin on a Monday. They are not weeks at all. They are fixed-width windows counted from a fixed origin, and whichever weekday that origin happens to land on is the weekday every bucket boundary lands on.
DATE_TRUNC | TIME_SLICE | |
|---|---|---|
| Boundaries follow | The calendar | A fixed origin and a width |
| Bucket widths available | Calendar parts: year, quarter, month, week, day | Any whole number of any unit |
| Are the buckets equal in size? | No, months differ and so do years | Yes, by construction |
| Reach for it when | The report is per month or per week | You want even buckets of n minutes, days or months |
TIME_SLICE is a ruler and DATE_TRUNC is a calendar. They are different tools and they are not substitutes for each other.
One last thing: a bucketing that grouped nothing
Let's finish by putting ten-day buckets over the whole table, grouped and counted.
SELECT TIME_SLICE(ORDER_DATE, 10, 'day') AS BUCKET_START,
COUNT(*) AS ORDERS_, ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS
GROUP BY TIME_SLICE(ORDER_DATE, 10, 'day')
ORDER BY BUCKET_START;| BUCKET_START | ORDERS_ | TOTAL |
|---|---|---|
| 2023-01-03 | 1 | 4200.00 |
| 2023-01-23 | 1 | 890.50 |
| 2023-02-12 | 1 | 6150.00 |
| 2023-02-22 | 1 | 1500.00 |
| 2023-03-04 | 1 | 2310.75 |
| 2023-03-14 | 1 | 5020.00 |
| 2023-04-03 | 1 | 7890.00 |
| 2023-04-13 | 1 | 1120.00 |
| 2023-04-23 | 1 | 3340.25 |
| 2023-05-13 | 1 | 640.00 |
| 2023-06-02 | 1 | 8100.00 |
| 2023-06-22 | 1 | 1975.50 |
| 2023-07-02 | 1 | 6420.00 |
| 2023-07-22 | 1 | 750.00 |
| 2023-08-11 | 1 | 9250.00 |
| 2023-08-21 | 1 | 2860.00 |
| 2023-09-10 | 1 | 5540.00 |
| 2023-09-30 | 1 | 1430.00 |
| 2023-10-20 | 1 | 7015.00 |
| 2023-10-30 | 1 | 10400.00 |
| 2023-11-19 | 1 | 980.00 |
| 2023-12-09 | 1 | 2250.00 |
| 2023-12-19 | 1 | 6730.00 |
| 2024-01-08 | 1 | 3910.00 |
| 2024-01-28 | 1 | 11200.00 |
| 2024-02-17 | 1 | 8340.00 |
| 2024-02-27 | 1 | 1690.00 |
| 2024-03-18 | 1 | 1240.00 |
| 2024-03-28 | 1 | 7460.00 |
| 2024-04-17 | 1 | 5180.00 |
| 2024-05-07 | 1 | 4025.00 |
| 2024-05-27 | 1 | 12850.00 |
| 2024-06-06 | 1 | 6900.00 |
| 2024-06-26 | 1 | 4760.00 |
| 2024-07-16 | 1 | 8820.00 |
| 2024-07-26 | 1 | 2540.00 |
| 2024-08-25 | 1 | 13100.00 |
| 2024-09-04 | 1 | 5930.00 |
| 2024-09-24 | 1 | 1080.00 |
| 2024-10-14 | 1 | 9640.00 |
| 2024-11-03 | 1 | NULL |
41 rows, and the ORDERS_ column reads 1 on every single one of them. The last row has a NULL total, which is the order with no amount from Episode 73 arriving in a bucket of its own.
Let's confirm that as a count rather than reading 41 rows.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT(TIME_SLICE(ORDER_DATE, 10, 'day')) AS BUCKETED,
COUNT(DISTINCT TIME_SLICE(ORDER_DATE, 10, 'day')) AS DISTINCT_BUCKETS,
COUNT_IF(ORDER_DATE < TIME_SLICE(ORDER_DATE, 10, 'day')) AS BEFORE_ITS_OWN_BUCKET
FROM ORDERS;| ROWS_TOTAL | BUCKETED | DISTINCT_BUCKETS | BEFORE_ITS_OWN_BUCKET |
|---|---|---|---|
| 41 | 41 | 41 | 0 |
41 rows, 41 of them bucketed, 41 distinct buckets, and 0 rows falling before their own bucket start. The bucketing is correct and it aggregated nothing, because no two of these orders land in the same ten-day bucket.
That is a fact about this data, not about TIME_SLICE. These 41 orders are spread thinly enough that each one gets a bucket to itself. The grid is left on the page as it came back rather than swapped for data that groups more agreeably, and it is worth recognising the shape: one row per bucket in a grouped report usually means the bucket is finer than the data, not that the query is broken.
Key points
DAYNAMEandMONTHNAMEalways return three characters, measured withLENGTHon this page rather than assumed. There is no full-name function and no locale argument.- Grouping and ordering by
DAYNAMEsorts a week alphabetically:Fri,Mon,Sat,Sun,Thu,Tue,Wed. The query is correct and the report is unreadable. - The fix is to group by the day number as well and order by that, keeping the name as a label. Here the two groupings covered identical ground: 41 orders, 7 names, 7 numbers.
- Build a full day name with
DECODEover the day number, and give it a visible fallback value rather than letting an unmatched input returnNULL. - Check a hand-written mapping against something that did not write it. Comparing the first three characters against
DAYNAMEcaught what a fallback count alone never would: 28 days, 0 fell through, 28 agreed. - The weekday and weekend
CASEtests0and6, which come from a session parameter. Cross-checking them againstDAYNAMEcost one query and returned 0 and 0 across all 41 rows. - To get the Monday of a date's week without depending on
WEEK_START, go backMOD(DATE_PART('dayofweekiso', d) - 1, 7)days. Verified againstDATE_TRUNC('week', ...)on 60 consecutive days, 60 of 60 agreeing. TIME_SLICE(ts, width, unit)rounds down to a fixed-width window start, so every timestamp in a window shares one key. The fourth argument'END'returns the next window's start, which makes a half-open range test natural.TIME_SLICEis a ruler andDATE_TRUNCis a calendar. Its seven-day buckets do not start on a Monday. Two bucket starts in the grid here fall on aThu.- Ten-day buckets over these orders produced 41 buckets for 41 orders. The bucketing is right. The data is simply spread too thinly to group, which is a fact about the table and not about the function.
Episode 75 — formatting dates and reading them back. TO_CHAR and TO_DATE, the format model, and what happens when the text you hand it is not the date you thought it was.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The ORDERS data is invented demo data created by that script. Every calculation is anchored to DATE '2024-06-30' rather than the clock, and every weekday named in the text above is read from a DAYNAME column in one of the grids rather than worked out here. No performance or benchmark claims are made anywhere in this series, and no conclusion is drawn from the weekday and weekend averages. Function behaviour follows the Snowflake date & time functions documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.