Sitemap
Towards Data Engineering

Explore top articles on data engineering, cloud architecture, agentic AI, and MLOps. Join our thriving Medium community of data professionals to discover curated insights, share your expertise, and build the future of AI and data-driven ecosystems.

SQL: LAG and LEAD Functions

3 min readApr 25, 2025

--

We will examine the LAG and LEAD functions to effectively conclude our series on Window Functions.

Press enter or click to view image in full size

READ FOR FREE

TABLE OF CONTENTS

· INTRODUCTION
· LAG AND LEAD
· FUNÇÃO LAG
· LEAD
· CONCLUSION

INTRODUCTION

These analytical functions within SQL act as offsets for query results.

These functions evaluate the current line, displaying the previous value (LAG) and the next value (LEAD).

They are based on the ORDER BY clause and use the column specified by the partition to return the desired value.

It accepts three parameters as arguments:

  1. The column we want for comparison to return the value.
  2. The number of rows returned will be specified, with one row being the default return value.
  3. When no value is specified, the default return value is NULL.

LAG FUNCTION.

In the first example, the PRE_VAL column displays the value from the previous row, starting at the second line (column RNUMBER).

--

--

Douglas S. de Souza
Douglas S. de Souza

Written by Douglas S. de Souza

Data Engineer | Data Content Creator | GCP | DBT | Big Query | Airflow

Towards Data Engineering
Towards Data Engineering

Published in Towards Data Engineering

Explore top articles on data engineering, cloud architecture, agentic AI, and MLOps. Join our thriving Medium community of data professionals to discover curated insights, share your expertise, and build the future of AI and data-driven ecosystems.