Snowflake SQL Tutorial 74 - DAYNAME, MONTHNAME, Weekday vs Weekend, TIME_SLICE - Dates 3

Snowflake SQL · Episode 74

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

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.

Sample data
-- 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.

Query
SELECT ORDER_ID, CUSTOMER_ID, ORDER_DATE, AMOUNT, STATUS
FROM ORDERS ORDER BY ORDER_DATE LIMIT 10;
Result10 rows · 5 columns
ORDER_IDCUSTOMER_IDORDER_DATEAMOUNTSTATUS
10011012023-01-124200.00SHIPPED
10021022023-01-28890.50SHIPPED
10031012023-02-146150.00SHIPPED
10041032023-02-271500.00CANCELLED
10051042023-03-092310.75SHIPPED
10061012023-03-225020.00SHIPPED
10071052023-04-057890.00SHIPPED
10081022023-04-191120.00SHIPPED
10091032023-05-023340.25SHIPPED
10101062023-05-21640.00PENDING

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.

Query
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;
Result7 rows · 3 columns
THE_DATEDAY_NAMEDOW
2024-06-30Sun0
2024-07-01Mon1
2024-07-02Tue2
2024-07-03Wed3
2024-07-04Thu4
2024-07-05Fri5
2024-07-06Sat6

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.

Query
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;
Result1 row · 5 columns
ANCHORDAY_NAMEDAY_NAME_LENGTHMONTH_NAMEMONTH_NAME_LENGTH
2024-06-30Sun3Jun3

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.

Query
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;
Result12 rows · 3 columns
THE_DATEMONTH_NAMEMONTH_NUMBER
2024-01-15Jan1
2024-02-15Feb2
2024-03-15Mar3
2024-04-15Apr4
2024-05-15May5
2024-06-15Jun6
2024-07-15Jul7
2024-08-15Aug8
2024-09-15Sep9
2024-10-15Oct10
2024-11-15Nov11
2024-12-15Dec12

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.

Query
SELECT DAYNAME(ORDER_DATE) AS DAY_NAME, COUNT(*) AS ORDERS_
FROM ORDERS
GROUP BY DAYNAME(ORDER_DATE)
ORDER BY DAY_NAME;
Result7 rows · 2 columns
DAY_NAMEORDERS_
Fri3
Mon4
Sat6
Sun6
Thu6
Tue8
Wed8

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.

Query
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;
Result7 rows · 4 columns
DOWDAY_NAMEORDERS_TOTAL
0Sun628570.50
1Mon416350.00
2Tue845770.25
3Wed850390.00
4Thu631570.75
5Fri37545.00
6Sat625230.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.

Query
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;
Result1 row · 3 columns
ROWS_TOTALDISTINCT_NAMESDISTINCT_NUMBERS
4177

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.

Not just weekdays

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.

Query
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;
Result7 rows · 3 columns
THE_DATEABBREVIATEDFULL_NAME
2024-06-30SunSunday
2024-07-01MonMonday
2024-07-02TueTuesday
2024-07-03WedWednesday
2024-07-04ThuThursday
2024-07-05FriFriday
2024-07-06SatSaturday

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?

Query
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;
Result1 row · 3 columns
ROWS_TOTALFELL_THROUGHAGREES_WITH_DAYNAME
28028

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.

Why the fallback is a word

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.

Query
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;
Result10 rows · 5 columns
ORDER_IDORDER_DATEDAY_NAMEDOWKIND
10012023-01-12Thu4Weekday
10022023-01-28Sat6Weekend
10032023-02-14Tue2Weekday
10042023-02-27Mon1Weekday
10052023-03-09Thu4Weekday
10062023-03-22Wed3Weekday
10072023-04-05Wed3Weekday
10082023-04-19Wed3Weekday
10092023-05-02Tue2Weekday
10102023-05-21Sun0Weekend

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.

Query
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;
Result2 rows · 4 columns
KINDORDERS_TOTALAVERAGE
Weekday29151626.005415.21
Weekend1253801.004483.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.

On the averages

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?

Query
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;
Result1 row · 3 columns
ROWS_TOTALWRONGLY_WEEKENDWRONGLY_WEEKDAY
4100

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.

What the check does and does not prove

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.

Query
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;
Result7 rows · 4 columns
THE_DATEDAY_NAMETRUNC_WEEKISO_MONDAY
2024-06-30Sun2024-06-242024-06-24
2024-07-01Mon2024-07-012024-07-01
2024-07-02Tue2024-07-012024-07-01
2024-07-03Wed2024-07-012024-07-01
2024-07-04Thu2024-07-012024-07-01
2024-07-05Fri2024-07-012024-07-01
2024-07-06Sat2024-07-012024-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.

Query
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;
Result1 row · 2 columns
ROWS_TOTALAGREE
6060

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.

On-or-before, not strictly before

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.

Query
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;
Result1 row · 5 columns
ANCHOREVERY_15_MINEVERY_30_MINEVERY_4_HOURSEVERY_HOUR
2024-06-30 14:37:522024-06-30 14:30:002024-06-30 14:30:002024-06-30 12:00:002024-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.

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;
Result1 row · 4 columns
ANCHORSLICE_STARTSLICE_ENDSLICE_WIDTH_MINUTES
2024-06-30 14:37:522024-06-30 14:30:002024-06-30 14:45:0015

'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.

Which is exactly what you want for a range check

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.

Query
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;
Result12 rows · 2 columns
TSSLICE_
2024-06-30 14:00:002024-06-30 14:00:00
2024-06-30 14:05:002024-06-30 14:00:00
2024-06-30 14:10:002024-06-30 14:00:00
2024-06-30 14:15:002024-06-30 14:15:00
2024-06-30 14:20:002024-06-30 14:15:00
2024-06-30 14:25:002024-06-30 14:15:00
2024-06-30 14:30:002024-06-30 14:30:00
2024-06-30 14:35:002024-06-30 14:30:00
2024-06-30 14:40:002024-06-30 14:30:00
2024-06-30 14:45:002024-06-30 14:45:00
2024-06-30 14:50:002024-06-30 14:45:00
2024-06-30 14:55:002024-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.

Query
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_;
Result4 rows · 2 columns
SLICE_N
2024-06-30 14:00:003
2024-06-30 14:15:003
2024-06-30 14:30:003
2024-06-30 14:45:003

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.

Query
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;
Result10 rows · 5 columns
ORDER_IDORDER_DATEWEEK_BUCKETTEN_DAY_BUCKETTWO_MONTH_BUCKET
10012023-01-122023-01-122023-01-032023-01-01
10022023-01-282023-01-262023-01-232023-01-01
10032023-02-142023-02-092023-02-122023-01-01
10042023-02-272023-02-232023-02-222023-01-01
10052023-03-092023-03-092023-03-042023-03-01
10062023-03-222023-03-162023-03-142023-03-01
10072023-04-052023-03-302023-04-032023-03-01
10082023-04-192023-04-132023-04-132023-03-01
10092023-05-022023-04-272023-04-232023-05-01
10102023-05-212023-05-182023-05-132023-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.

Query
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;
Result5 rows · 7 columns · scroll →
ORDER_IDORDER_DATEDAY_NAMEMONTH_NAMEDOWKINDWEEK_BUCKET
10012023-01-12ThuJan4Weekday2023-01-12
10022023-01-28SatJan6Weekend2023-01-26
10032023-02-14TueFeb2Weekday2023-02-09
10042023-02-27MonFeb1Weekday2023-02-23
10052023-03-09ThuMar4Weekday2023-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_TRUNCTIME_SLICE
Boundaries followThe calendarA fixed origin and a width
Bucket widths availableCalendar parts: year, quarter, month, week, dayAny whole number of any unit
Are the buckets equal in size?No, months differ and so do yearsYes, by construction
Reach for it whenThe report is per month or per weekYou 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.

Query
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;
Result41 rows · 3 columns
BUCKET_STARTORDERS_TOTAL
2023-01-0314200.00
2023-01-231890.50
2023-02-1216150.00
2023-02-2211500.00
2023-03-0412310.75
2023-03-1415020.00
2023-04-0317890.00
2023-04-1311120.00
2023-04-2313340.25
2023-05-131640.00
2023-06-0218100.00
2023-06-2211975.50
2023-07-0216420.00
2023-07-221750.00
2023-08-1119250.00
2023-08-2112860.00
2023-09-1015540.00
2023-09-3011430.00
2023-10-2017015.00
2023-10-30110400.00
2023-11-191980.00
2023-12-0912250.00
2023-12-1916730.00
2024-01-0813910.00
2024-01-28111200.00
2024-02-1718340.00
2024-02-2711690.00
2024-03-1811240.00
2024-03-2817460.00
2024-04-1715180.00
2024-05-0714025.00
2024-05-27112850.00
2024-06-0616900.00
2024-06-2614760.00
2024-07-1618820.00
2024-07-2612540.00
2024-08-25113100.00
2024-09-0415930.00
2024-09-2411080.00
2024-10-1419640.00
2024-11-031NULL

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.

Query
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;
Result1 row · 4 columns
ROWS_TOTALBUCKETEDDISTINCT_BUCKETSBEFORE_ITS_OWN_BUCKET
4141410

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.

Read the result, not the intention

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

  • DAYNAME and MONTHNAME always return three characters, measured with LENGTH on this page rather than assumed. There is no full-name function and no locale argument.
  • Grouping and ordering by DAYNAME sorts 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 DECODE over the day number, and give it a visible fallback value rather than letting an unmatched input return NULL.
  • Check a hand-written mapping against something that did not write it. Comparing the first three characters against DAYNAME caught what a fallback count alone never would: 28 days, 0 fell through, 28 agreed.
  • The weekday and weekend CASE tests 0 and 6, which come from a session parameter. Cross-checking them against DAYNAME cost 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 back MOD(DATE_PART('dayofweekiso', d) - 1, 7) days. Verified against DATE_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_SLICE is a ruler and DATE_TRUNC is a calendar. Its seven-day buckets do not start on a Monday. Two bucket starts in the grid here fall on a Thu.
  • 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.
Next in this series

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.