Using FIRST_VALUE and LAST_VALUE in PostgreSQL
📖 Scenario: You work for a retail company that tracks sales data. You want to find the first and last sale dates for each product to understand sales trends.
🎯 Goal: Create a PostgreSQL query that uses FIRST_VALUE and LAST_VALUE window functions to find the earliest and latest sale dates for each product.
📋 What You'll Learn
Create a table called
sales with columns product_id (integer), sale_date (date), and amount (numeric).Insert the exact sales data provided.
Define a window partition by
product_id ordered by sale_date ascending.Use
FIRST_VALUE(sale_date) to get the first sale date per product.Use
LAST_VALUE(sale_date) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) to get the last sale date per product.💡 Why This Matters
🌍 Real World
Finding first and last events or values per group is common in sales, finance, and event tracking systems.
💼 Career
Understanding window functions like FIRST_VALUE and LAST_VALUE is essential for data analysts and database developers to write advanced queries.
Progress0 / 4 steps