Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

What are SQL window functions, and how would you get the latest row or top value per group?

Answer

A window function calculates across related rows while retaining each row, using an OVER clause with optional PARTITION BY, ORDER BY and frame rules. A common pattern assigns ROW_NUMBER() OVER (PARTITION BY group_key ORDER BY timestamp DESC) and keeps row number one to select the latest row per group. Tests should include ties, duplicate timestamps, NULL ordering, deterministic secondary ordering, empty groups and frame boundaries for running or rolling calculations.

Strong answer includes

  • distinguishes windows from collapsing aggregation
  • uses partitioning and deterministic ordering
  • tests ties, null ordering and frame boundaries

Practical example

Latest row per customer with ROW_NUMBER
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Window functions calculate across related rows without collapsing them. PARTITION BY restarts the ranking for each customer, and the stable secondary ordering makes ties deterministic.

Expected result: Exactly one newest order per customer with orders.

#sql#window-functions#row-number#analytics

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recoveryUnderstand star schema and its importance for Power BIMicrosoft · Facts, dimensions, grain, relationships and semantic-model quality