EN
PostgreSQL - Group rows by days
0 points
In this article, we would like to show you how in the group rows by days in PostgreSQL.

Note: at the end of this article you can find database preparation SQL queries.
xxxxxxxxxx
1
SELECT
2
DATE_TRUNC('day', "event_timestamp") AS "day",
3
COUNT(*)
4
FROM "events"
5
GROUP BY DATE_TRUNC('day', "event_timestamp")
6
ORDER BY DATE_TRUNC('day', "event_timestamp")
Result:

Shorter notation of the example above:
xxxxxxxxxx
1
SELECT
2
DATE_TRUNC('day', "event_timestamp") AS "day",
3
COUNT(*)
4
FROM "events"
5
GROUP BY 1
6
ORDER BY 1
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "events" (
2
"id" SERIAL NOT NULL,
3
"event_timestamp" TIMESTAMP NOT NULL,
4
PRIMARY KEY ("id")
5
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "events"
2
("event_timestamp")
3
VALUES
4
('2021-03-11 11:41:31'),
5
('2021-03-21 12:42:32'),
6
('2021-03-22 14:44:34'),
7
('2021-03-22 15:45:35'),
8
('2021-03-23 16:46:36'),
9
('2021-04-05 17:47:37'),
10
('2021-04-05 19:49:39'),
11
('2021-04-16 20:50:40'),
12
('2021-04-17 15:45:35'),
13
('2021-04-23 16:46:36'),
14
('2021-04-23 19:49:39'),
15
('2021-04-23 20:50:40');