I want to get the data from the last 28 days and only include complete days. So what I mean is, when I look at the data today at 10:00 AM, it only includes data from yesterday (the completed day) and 28 days before yesterday.
I am creating a live dashboard with figures like this. So I don't want the numbers to change until the day is finished.
Also, I am willing to understand the difference between CURRENT_DATE
and CURRENT_TIMESTAMP
For example, in my code, if I use CURRENT_TIMESTAMP
, will I get the data from today 10:00 AM back to 28 days ago 10:00 AM? if not, how can I get data in a way numbers change live according to every time I run the code (the average time that data change in the database is 10 minutes).
My simplified code:
select count(id) from customers
where created_at > CURRENT_DATE - interval '28 days'
Maybe I am using wrong code, can you please give me advice on how to get the date in both formats:
Assuming created_at
is of type timestamptz
.
- include only complete days(does not include today, until the day is finished)
Start with now()
and use date_trunc()
:
...
WHERE created_at >= date_trunc('day', now() - interval '28 days')
AND created_at < date_trunc('day', now());
Or work with CURRENT_DATE
...
...
WHERE created_at >= CURRENT_DATE - 28
AND created_at < CURRENT_DATE;
The result for both depends on the current timezone
setting. The effective date depends on your current time zone. The type timestamp with time zone
(timestamptz
) does not. But the expression date_trunc('day', now())
introduces the same dependency as the "day" is defined by your current time zone.
If that's not what you want, specify the time zone explicitly as third argument to the overloaded variant of date_trunc()
(Postgres 12+):
...
WHERE created_at >= date_trunc('day', now() - interval '28 days', 'Europe/Vienna')
AND created_at < date_trunc('day', now());
Basics:
You can subtract integer
values from a date
to subtract days:
now()
is a shorter equivalent of CURRENT_TIMESTAMP
. See:
count(*)
is equivalent to count(id)
while id
is defined NOT NULL
, but a bit faster.
- include hours, from today morning until 28 days back same time in the morning.
Simply:
WHERE created_at > now() - interval '28 days'
No dependency on the current time zone.