Start learning free

LESSON 43 OF 66 · SQL: INTERVIEW QUESTIONS

Three in a Row in Python

Practice

A classic interview question: which users logged in three times in a row? "In a row" means neighboring rows, not three logins in total. A login is the middle of three when the row just before it and the row just after it belong to the same user.

LAG(column) OVER (ORDER BY id) reads a column from the row before, in id order, and LEAD reads it from the row after. A row with no neighbor on that side gets NULL. For example, this puts each login's time next to the time of the login before it:

SELECT id, logged_in,
    LAG(logged_in) OVER (ORDER BY id) AS previous_login
FROM logins

WHERE runs before window functions, so it can't compare with LAG directly. Work out the neighbors in a named query first, then filter it like a table. For this lesson the shop gets a logins table:

id | user_id | logged_in
 1 | 1 | 2026-06-01 08:02
 2 | 1 | 2026-06-01 08:15
 3 | 2 | 2026-06-01 08:31
 4 | 3 | 2026-06-01 09:04
 5 | 3 | 2026-06-01 09:20
 6 | 3 | 2026-06-01 09:47
 7 | 3 | 2026-06-01 10:12
 8 | 2 | 2026-06-01 10:30
 9 | 5 | 2026-06-01 11:05
10 | 2 | 2026-06-01 11:41
11 | 1 | 2026-06-01 12:09
12 | 5 | 2026-06-01 12:26
13 | 5 | 2026-06-01 13:02
14 | 5 | 2026-06-01 13:38

Users 1 and 2 log in three times each, but never three in a row. The query must print:

user_id
3
5
(2 rows)

Your task: in query, build a named query neighbors that gives each login its user_id, prev_user and next_user, in id order. Then list, once each, the users whose row has the same user on both sides.


Assignment
Follow the Coding Tutorial to build the neighbors query and the main query that filters it, one clause per step.


Hint
User 3 logs in four times in a row, so two of those rows are middles: DISTINCT lists the user once. A NULL neighbor is never equal to anything, so the first and last rows can't match.


STEP 1 OF 7
    Ctrl + Enter to check

    Sqlq Consecutive Numbers in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free