SQL-Engineering-Handbook

FIRST_VALUE(), LAST_VALUE(), and NTILE()

FIRST_VALUE, LAST_VALUE, and NTILE diagram

Overview

FIRST_VALUE() and LAST_VALUE() retrieve the value at the start and end of a window’s frame. NTILE(n) divides the rows in a window into n roughly equal-sized buckets and labels each row with its bucket number.

Learning Objectives

Prerequisites

Syntax

FIRST_VALUE(column) OVER (ORDER BY sort_column) AS first_value

LAST_VALUE(column) OVER (
    ORDER BY sort_column
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_value

NTILE(n) OVER (ORDER BY sort_column) AS bucket_number

Dataset Used

employes joined to departments

Examples

See 06_first_last_ntile.sql.

Real World Applications

Business Use Cases

Domain Scenario
Marketing Split customers into quartiles by spend (NTILE(4))
Banking First and last transaction per account statement
HR First and last hire in each department

Common Mistakes

Best Practices

Engineering Notes

FIRST_VALUE() works correctly with the default frame because “first” and “current position” align naturally as the window grows; LAST_VALUE() does not share that property, which is why it is the single most-cited source of window-function bugs in production code reviews.

Practice Questions

  1. Show the first employee using FIRST_VALUE().
  2. Show the last employee using LAST_VALUE() (with the correct frame clause).
  3. Divide employees into buckets using NTILE().

Difficulty

Intermediate

Estimated Time

25 minutes

Learning Outcomes

Next Topic

07_RUNNING_TOTALS


Lesson Navigation

← Previous: 05_LAG_LEADModule README → Next: 07_RUNNING_TOTALS