Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Last 20 Rows Retrieval

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

Your question is SQL Last 20 Rows Retrieval. Start with the requirements and the three 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

Ascendion's delivery analytics team needs a report showing the most recent activity records across its project portfolio. Write a PostgreSQL query that returns the latest 20 activity rows, preserving activities even when employee or project details are unavailable.

Requirements

  1. Use a CTE to identify the latest 20 rows from activity_events.
  2. Sort by occurred_at descending, using event_id descending as a deterministic tie-breaker.
  3. Use LEFT JOIN to include activity rows with missing employee or project references.
  4. Return the event ID, timestamp, event type, employee name, and project name in newest-first order.

The sample contains fewer than 20 activity rows, so the query should return every available row while still using LIMIT 20.

Schema

activity_events
ColumnTypeDescription
event_idPKINTEGERUnique activity identifier
occurred_atTIMESTAMPTime the activity occurred
event_typeVARCHAR(40)Activity classification
employee_idINTEGEROptional reference to the employee responsible
project_idINTEGEROptional reference to the related project
employees
ColumnTypeDescription
employee_idPKINTEGEREmployee identifier
employee_nameVARCHAR(120)Employee display name
departmentVARCHAR(80)Employee department
projects
ColumnTypeDescription
project_idPKINTEGERProject identifier
project_nameVARCHAR(150)Project display name
client_nameVARCHAR(120)Client organization
Tablesactivity_eventsemployeesprojects
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results