softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL Analytical Functions – LEAD(), LAG(), FIRST_VALUE(), LAST_VALUE()

🔹 Why Analytical Functions Matter

Analytical or window functions add insights across rows without collapsing the dataset. They power comparisons, time-series analysis, dashboards, and QA validation where the original row structure must stay intact.

⚙️ 1️⃣ Analytical Function Primer

Analytical functions operate over a window defined by OVER (PARTITION BY ... ORDER BY ...). They return a value per row instead of aggregating multiple rows into one result.

⚙️ 2️⃣ Example Dataset – Regional Sales

IDRegionMonthSales
1EastJan1000
2EastFeb1500
3EastMar1200
4WestJan2000
5WestFeb2500
6WestMar1800

⚙️ 3️⃣ LAG() – Compare to Previous Row

SELECT 
  Region,
  Month,
  Sales,
  LAG(Sales, 1) OVER (PARTITION BY Region ORDER BY Month) AS PrevMonthSales,
  Sales - LAG(Sales, 1) OVER (PARTITION BY Region ORDER BY Month) AS SalesChange
FROM Sales;
Boundary rows return NULL. Use COALESCE if you need a default value.

⚙️ 4️⃣ LEAD() – Peek at the Next Row

SELECT 
  Region,
  Month,
  Sales,
  LEAD(Sales, 1) OVER (PARTITION BY Region ORDER BY Month) AS NextMonthSales
FROM Sales;

⚙️ 5️⃣ FIRST_VALUE() – First Value per Partition

SELECT 
  Region,
  Month,
  Sales,
  FIRST_VALUE(Sales) OVER (PARTITION BY Region ORDER BY Month) AS FirstMonthSales
FROM Sales;

⚙️ 6️⃣ LAST_VALUE() – Last Value per Partition

SELECT 
  Region,
  Month,
  Sales,
  LAST_VALUE(Sales) OVER (
      PARTITION BY Region
      ORDER BY Month
      ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  ) AS LastMonthSales
FROM Sales;
Without ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, LAST_VALUE only considers the current window frame.

⚙️ 7️⃣ Combine Multiple Functions

SELECT 
  Region,
  Month,
  Sales,
  LAG(Sales)  OVER (PARTITION BY Region ORDER BY Month) AS Prev,
  LEAD(Sales) OVER (PARTITION BY Region ORDER BY Month) AS Next,
  FIRST_VALUE(Sales) OVER (PARTITION BY Region ORDER BY Month) AS First,
  LAST_VALUE(Sales)  OVER (
      PARTITION BY Region ORDER BY Month
      ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  ) AS Last
FROM Sales;

🧩 Real-World Scenarios

Sales Tracking

Compare month-over-month growth with LAG and LEAD.

Trend Analysis

Highlight first and last values to spotlight opening and closing metrics.

QA Dashboards

Validate API responses that include previous/next period totals.

Financial KPIs

Monitor salary revisions or balance changes without losing row detail.

⚖️ Best Practices

💡 Interview Tip

“Analytical functions scan each partition once. They are ideal when you need previous/next comparisons without collapsing rows like GROUP BY does.”
← Back to Articles | 🏠 Back to Homepage