Start learning free

LESSON 101 OF 107 · DATA ENGINEERING: INTERVIEW QUESTIONS

First and Last Event per User in Python

Practice

The interviewer asks: "For each user, show the first page they viewed and the last one, side by side in one row." Data engineers need this all the time: the page a visit started on and the page it ended on, a customer's first and latest order, a sensor's first and last reading. A hidden setup writes page_views.csv before your code runs; the starting code loads it into the table page_views and already counts each user's views:

user_id,page,viewed_at
7,/home,2026-05-04 09:00:00
12,/product/teapot,2026-05-04 09:03:00
7,/search,2026-05-04 09:04:00
12,/home,2026-05-04 09:06:00
7,/product/mug,2026-05-04 09:07:00
7,/cart,2026-05-04 09:09:00
12,/search,2026-05-04 09:12:00
7,/checkout,2026-05-04 09:15:00
58,/home,2026-05-04 11:30:00
41,/search,2026-05-04 23:50:00
41,/cart,2026-05-05 00:10:00

The trap: most people write MIN(page) and MAX(page). Those compare the page names as text and forget which row each came from: for user 7 they give /cart and /search, but user 7 started on /home and left from /checkout. The other common answer, ROW_NUMBER() once each way and a join, is right but long.

arg_min(x, y) finds the row with the smallest y in the group and returns that row's x; arg_max(x, y) does the same with the biggest y. They work in a GROUP BY, just like MIN and MAX, and some other engines call them min_by and max_by. An example on other values:

SELECT arg_max(city, temp) AS warmest, arg_min(city, temp) AS coldest
FROM (VALUES ('Oslo', 9), ('Lisbon', 24), ('Vienna', 17)) AS t(city, temp)
-- warmest: Lisbon, coldest: Oslo

For the time itself MIN and MAX are right: the latest viewed_at minus the earliest gives an interval, the time from the first view to the last, even across midnight. The check prints:

user_id | first_page | last_page | time_on_site | views
7 | /home | /checkout | 0:15:00 | 5
12 | /product/teapot | /search | 0:09:00 | 3
41 | /search | /cart | 0:20:00 | 2
58 | /home | /home | 0:00:00 | 1
(4 rows)

Your task: below the SELECT line, add first_page with arg_min, last_page with arg_max, and time_on_site, the latest view's time minus the earliest.


Assignment
Follow the Coding Tutorial to add each user's first page, last page and time on site to the query.


Hint
The first argument is what you get back; the second decides which row. Both functions pick the row by viewed_at. Each new line ends with a comma and a space, because COUNT(*) AS views comes after them.


STEP 1 OF 3
    Ctrl + Enter to check

    De Iq First Last Event 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