Menu

Find login streaks in SQL with the gaps-and-islands trick (PostgreSQL and SQLite)
📰

Find login streaks in SQL with the gaps-and-islands trick (PostgreSQL and SQLite)

DEV Community: sql·DailyDrills·1 day ago
#MXmTEXnq
#devtosql#devto#dev#days#user_id
Long article (1838 words) — no AI summary yet.
Reading 0:00
15s threshold

"How many days in a row did each user log in?" sounds like it needs a loop. It doesn't. There's a short, well-known SQL pattern for it called gaps and islands : each run of consecutive days is an island, and the missing days between them are the gaps.

This post builds the query step by step on a tiny table, then shows the mistakes that quietly give you wrong streaks. Every query and result below was run on PostgreSQL, and the SQLite version at the end was run on SQLite 3.46.

The data

One row per login, so a user can have several rows on the same day:

CREATE TABLE logins ( user_id INTEGER , login_at TIMESTAMP ) ;

INSERT INTO logins ( user_id , login_at ) VALUES ( 1 , '2026-03-01 09:10:00' ) , ( 1 , '2026-03-01 21:40:00' ) , ( 1 , '2026-03-02 08:05:00' ) , ( 1 , '2026-03-03 07:55:00' ) , ( 1 , '2026-03-05 12:00:00' ) , ( 1 , '2026-03-06 23:30:00' ) , ( 1 , '2026-03-09 10:00:00' ) , ( 2 , '2026-03-02 18:00:00' ) , ( 2 , '2026-03-03 18:20:00' ) , ( 2 , '2026-03-04 19:00:00' ) , ( 2 , '2026-03-05 08:45:00' )…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.