Sobes.tech
Middle+

Tell me about window functions — which ones have you used and how does the LEAD function work? How to avoid NULL in the LEAD result?

sobes.tech AI

Answer from AI

Window functions in SQL allow you to perform calculations across a set of table rows that are related to the current row, without grouping the results.

The LEAD function returns the value from the next row within the window. For example, if you have a table with dates and values, LEAD allows you to get the value of the next date for each row.

Example of using LEAD:

SELECT
  date,
  value,
  LEAD(value) OVER (ORDER BY date) AS next_value
FROM sales;

If there is no next row, LEAD returns NULL. To avoid NULL, you can specify a third parameter — a default value:

LEAD(value, 1, 0) OVER (ORDER BY date) AS next_value

Here, if there is no next row, instead of NULL, 0 will be used.

I used window functions for time series analysis, calculating cumulative sums, and comparing current and next values without aggregation.