SQL Interview Questions · Question 17

Write a query to find each user's previous login date?

Interview preparation resource from Gate Smashers.

Interview-ready answer

SELECT user_id, login_date, LAG(login_date) OVER (PARTITION BY user_id ORDER BY login_date) AS previous_login FROM User_Logins;

User_Logins (sample data)
user_idlogin_datesession_minutes
12024-07-0135
12024-07-0242
12024-07-0328
22024-07-0120
22024-07-0325
32024-07-0245
SQL querysql
SELECT
  user_id,
  login_date,
  LAG(login_date) OVER (
    PARTITION BY user_id
    ORDER BY login_date
  ) AS previous_login
FROM User_Logins;
Understand it clearly

Query

Use the LAG window function to access the previous login_date per user. The query returns each row with an extra column previous_login containing the prior login_date for that user (or NULL for their first login).

  • SQL: LAG(login_date) OVER (PARTITION BY user_id ORDER BY login_date) AS previous_login

How it works

The window specification PARTITION BY user_id restarts the history for each user. ORDER BY login_date establishes the chronological sequence within that user's rows so LAG returns the immediately preceding login_date.

  • Partition: PARTITION BY user_id — separate history per user
  • Order: ORDER BY login_date — chronological order for LAG to reference
  • First row: The first login for a user has no previous row, so previous_login is NULL

Notes & edge cases

If multiple logins can share the same login_date, include a more granular ordering column (for example a timestamp or a unique event ID) in the ORDER BY to make the previous row deterministic.

  • Ties: Add timestamp or event_id to ORDER BY when login_date is not unique

Sample data reference

See the sample User_Logins rows below. Run the query against that table to get each row's previous_login.