First Last Non Null Per Group
Get the first and last non null values per group using window functions with ignore nulls framing.
Code
SELECT DISTINCT
partition_key,
FIRST_VALUE(value) IGNORE NULLS OVER (
PARTITION BY partition_key
ORDER BY sort_key
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS first_non_null,
LAST_VALUE(value) IGNORE NULLS OVER (
PARTITION BY partition_key
ORDER BY sort_key
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_non_null
FROM observations
ORDER BY partition_key;What the code does
At its core this is a single SELECT statement against observations.
Breaking the statements into their working parts: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.
What to watch for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Applying it
Run the statement against the observations table.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- The references are `observations`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.