Menu
Coddy logo textTech

LEAD & LAG functions

Lesson 6 of 13 in Coddy's SQL for advanced course.

The Lead and Lag functions allow us to the value of the current row by n steps back of n steps ahead

For example, if we want to calculate the ratio of a company for the current row and one months ago we extract the value two months ago:

idrevenuemonth
15325
24926
33937
47238
SELECT id, revenue, LAG(month, 1) OVER (ORDER BY MONTH) as prev_month_revenue
FROM table1 ORDER BY id

This will create the following table:

idrevenueprev_month_revenue
1532 
2492532
3393492
4723723

This way we can calculate the prev_month_revenue/revenue ratio.

If we instead used the LEAD function would take the next month of each row:

idrevenuenext_month_revenue
1532492
2492393
3393723
4723 
challenge icon

Challenge

Easy

Air conditioners can get very expensive. Over time, they have become more efficient and stronger, but the significance of these improvements is not seen day by day. We need to zoom out to see the improvements over time.

To do this, Calculate the average efficiency and strength of air conditioners for each id and month. Then fetch the ratio between efficiency and strength for the current month and two months before it. Finally, Calculate the ratio between the current month's ratio and the ratio of the two months before it. Return the results where the ratio is greater than 1.5. Name this column ratio_two_months.

Try it yourself

All lessons in SQL for advanced