Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Query for Latest User

EasySQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is SQL Query for Latest User. Start with the requirements and the four tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Infineon Technologies Americas needs an operational query that identifies the employee whose login was recorded most recently. The production employee_login_events table contains more than 100 million rows, so the query must be deterministic and suitable for an indexed PostgreSQL workload.

Write a PostgreSQL query that returns exactly one row for the most recently logged-in active employee, along with department and site information.

Requirements

  1. Consider only active employees and login events with a non-null login_at.
  2. Return exactly one row, even when multiple employees have the same latest timestamp.
  3. Break timestamp ties deterministically using the greatest event_id.
  4. Include the employee ID, employee name, login timestamp, department name, and site name.
  5. Use a window function and structure the query so an index on (login_at DESC, event_id DESC) can support the large event table.

Schema

employees
ColumnTypeDescription
employee_idPKBIGINTUnique employee identifier
employee_nameVARCHAR(120)Employee full name
department_idINTAssigned department
site_idINTAssigned Infineon site
is_activeBOOLEANWhether the employee is active
employee_login_events
ColumnTypeDescription
event_idPKBIGINTUnique login event identifier
employee_idBIGINTEmployee who logged in
login_atTIMESTAMPTZRecorded login timestamp
departments
ColumnTypeDescription
department_idPKINTDepartment identifier
department_nameVARCHAR(100)Department name
sites
ColumnTypeDescription
site_idPKINTSite identifier
site_nameVARCHAR(120)Infineon site name
Tablesemployeesemployee_login_eventsdepartmentssites
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results