SlideShare a Scribd company logo
1 of 8
Use Lead and Lag in SQL to
find previous or next rows
LEAD and LAG are built in analytical functions which can make
it easy to find the next or previous row of data
In this example we will use a date table as its easy to follow and
the results are plain and simple to understand
Here is an example
This returns the next date and the
previous date for each date in the
dataset
We will break down the components
of this code
Breaking down the key pieces
LEAD([FullDateUK], 1, 0) over (ORDER BY [datekey]) as nextday
LEAD looks for the next row
[FullDateUK] is the field we want to return
, 1 is the number of rows to look forward
, 0 is the default if no data is available
over (ORDER BY [datekey]) defines the order to sort the data
LAG is very similar, except that it looks for the previous row
Other examples
select [FullDateUK], nextweek, prevweek from
(
SELECT [datekey], [FullDateUK]
, LEAD([FullDateUK], 7,0) over (ORDER BY [datekey]) as nextweek
, LAG([FullDateUK], 7,0) over (ORDER BY [datekey]) as prevweek
FROM [SelectDistinctTips].[dbo].[DimDate]
) D
where [datekey] > 20191225
order by [datekey]
By changing the parameter to a 7 we can return the date a week
earlier
Use Cases
You wouldn’t use this technique to find dates as there are date functions to do that, but it does demonstrate nicely how
it works
Typical use cases for this
Finding the prior week or month sales for a sales dataset, Forecasting closing stock by carrying forward the previous
days closing stock
It can be used wherever you need to find either the previous row and or next row of a dataset, like you might do in
Excel
Hope you found this useful
For more Tips, Tricks and
Timesavers, visit our website
Tips and Timesavers | Select Distinct Limited
Credit: simon.harrison@selectdistinct.co.uk

More Related Content

Similar to Sql tips lead and lag

Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
djkucera
 
dbms-unit-_part-1.pptxeqweqweqweqweqweqweqweq
dbms-unit-_part-1.pptxeqweqweqweqweqweqweqweqdbms-unit-_part-1.pptxeqweqweqweqweqweqweqweq
dbms-unit-_part-1.pptxeqweqweqweqweqweqweqweq
wrushabhsirsat
 
Predictive performance analysis using sql pattern matching
Predictive performance analysis using sql pattern matchingPredictive performance analysis using sql pattern matching
Predictive performance analysis using sql pattern matching
Horia Berca
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
Vinay Thota
 

Similar to Sql tips lead and lag (20)

TSQL Functions (SQL Server)
TSQL Functions (SQL Server)TSQL Functions (SQL Server)
TSQL Functions (SQL Server)
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
SQL Tips PIVOT Function.pptx
SQL Tips PIVOT Function.pptxSQL Tips PIVOT Function.pptx
SQL Tips PIVOT Function.pptx
 
Top 5 SQL Tips and Timesaver 2023, our most popular posts
Top 5 SQL Tips and Timesaver 2023, our most popular postsTop 5 SQL Tips and Timesaver 2023, our most popular posts
Top 5 SQL Tips and Timesaver 2023, our most popular posts
 
Module02
Module02Module02
Module02
 
Chris Seebacher Portfolio
Chris Seebacher PortfolioChris Seebacher Portfolio
Chris Seebacher Portfolio
 
How to PIVOT in SQL
How to PIVOT in SQLHow to PIVOT in SQL
How to PIVOT in SQL
 
Data ware house design
Data ware house designData ware house design
Data ware house design
 
Data ware house design
Data ware house designData ware house design
Data ware house design
 
Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony DavisUncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony Davis
 
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
 
Sql Server 2000
Sql Server 2000Sql Server 2000
Sql Server 2000
 
Em12c performance tuning outside the box
Em12c performance tuning outside the boxEm12c performance tuning outside the box
Em12c performance tuning outside the box
 
SQL Tips UNPIVOT Function.pptx
SQL Tips UNPIVOT Function.pptxSQL Tips UNPIVOT Function.pptx
SQL Tips UNPIVOT Function.pptx
 
dbms-unit-_part-1.pptxeqweqweqweqweqweqweqweq
dbms-unit-_part-1.pptxeqweqweqweqweqweqweqweqdbms-unit-_part-1.pptxeqweqweqweqweqweqweqweq
dbms-unit-_part-1.pptxeqweqweqweqweqweqweqweq
 
Predictive performance analysis using sql pattern matching
Predictive performance analysis using sql pattern matchingPredictive performance analysis using sql pattern matching
Predictive performance analysis using sql pattern matching
 
SAS/Tableau integration
SAS/Tableau integrationSAS/Tableau integration
SAS/Tableau integration
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
 

More from Select Distinct Limited

Power BI Tips Top N Measures.pptx
Power BI Tips Top N Measures.pptxPower BI Tips Top N Measures.pptx
Power BI Tips Top N Measures.pptx
Select Distinct Limited
 

More from Select Distinct Limited (20)

Year on Year Comparison in Power BI.pptx
Year on Year Comparison in Power BI.pptxYear on Year Comparison in Power BI.pptx
Year on Year Comparison in Power BI.pptx
 
Sync Slicers in Power BI a step by step guide
Sync Slicers in Power BI a step by step guideSync Slicers in Power BI a step by step guide
Sync Slicers in Power BI a step by step guide
 
Using Google Search Console Data in Power BI.pptx
Using Google Search Console Data in Power BI.pptxUsing Google Search Console Data in Power BI.pptx
Using Google Search Console Data in Power BI.pptx
 
Data Lake v Data Warehouse. What is the difference?
Data Lake v Data Warehouse. What is the difference?Data Lake v Data Warehouse. What is the difference?
Data Lake v Data Warehouse. What is the difference?
 
How to Create Drop Down Lists in Excel, step by step
How to Create Drop Down Lists in Excel, step by stepHow to Create Drop Down Lists in Excel, step by step
How to Create Drop Down Lists in Excel, step by step
 
Top 5 Power BI tips 2023 most popular blog posts
Top 5 Power BI tips 2023 most popular blog postsTop 5 Power BI tips 2023 most popular blog posts
Top 5 Power BI tips 2023 most popular blog posts
 
CTEs in SQL.pptx
CTEs in SQL.pptxCTEs in SQL.pptx
CTEs in SQL.pptx
 
Calculated Columns and Measures in Power BI.pptx
Calculated Columns and Measures in Power BI.pptxCalculated Columns and Measures in Power BI.pptx
Calculated Columns and Measures in Power BI.pptx
 
Divide by Zero Errors
Divide by Zero ErrorsDivide by Zero Errors
Divide by Zero Errors
 
When to transform data for Power BI.pptx
When to transform data for Power BI.pptxWhen to transform data for Power BI.pptx
When to transform data for Power BI.pptx
 
Power BI KPIs
Power BI KPIsPower BI KPIs
Power BI KPIs
 
Direction of travel on a map in Power BI.pptx
Direction of travel on a map in Power BI.pptxDirection of travel on a map in Power BI.pptx
Direction of travel on a map in Power BI.pptx
 
UNION in DAX
UNION in DAXUNION in DAX
UNION in DAX
 
APPEND data in Power Query
APPEND data in Power QueryAPPEND data in Power Query
APPEND data in Power Query
 
Power BI Connect to Google BigQuery.pptx
Power BI Connect to Google BigQuery.pptxPower BI Connect to Google BigQuery.pptx
Power BI Connect to Google BigQuery.pptx
 
Advanced Top N Measures in Power BI
Advanced Top N Measures in Power BIAdvanced Top N Measures in Power BI
Advanced Top N Measures in Power BI
 
Custom Formats in Power BI
Custom Formats in Power BICustom Formats in Power BI
Custom Formats in Power BI
 
Power BI Tips Top N Measures.pptx
Power BI Tips Top N Measures.pptxPower BI Tips Top N Measures.pptx
Power BI Tips Top N Measures.pptx
 
Power BI Drill Through
Power BI Drill ThroughPower BI Drill Through
Power BI Drill Through
 
How to use a slicer to toggle measures in Power BI
How to use a slicer to toggle measures in Power BIHow to use a slicer to toggle measures in Power BI
How to use a slicer to toggle measures in Power BI
 

Recently uploaded

“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
Muhammad Subhan
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 

Recently uploaded (20)

Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 

Sql tips lead and lag

  • 1. Use Lead and Lag in SQL to find previous or next rows
  • 2. LEAD and LAG are built in analytical functions which can make it easy to find the next or previous row of data In this example we will use a date table as its easy to follow and the results are plain and simple to understand
  • 3. Here is an example This returns the next date and the previous date for each date in the dataset We will break down the components of this code
  • 4. Breaking down the key pieces LEAD([FullDateUK], 1, 0) over (ORDER BY [datekey]) as nextday LEAD looks for the next row [FullDateUK] is the field we want to return , 1 is the number of rows to look forward , 0 is the default if no data is available over (ORDER BY [datekey]) defines the order to sort the data LAG is very similar, except that it looks for the previous row
  • 5. Other examples select [FullDateUK], nextweek, prevweek from ( SELECT [datekey], [FullDateUK] , LEAD([FullDateUK], 7,0) over (ORDER BY [datekey]) as nextweek , LAG([FullDateUK], 7,0) over (ORDER BY [datekey]) as prevweek FROM [SelectDistinctTips].[dbo].[DimDate] ) D where [datekey] > 20191225 order by [datekey] By changing the parameter to a 7 we can return the date a week earlier
  • 6. Use Cases You wouldn’t use this technique to find dates as there are date functions to do that, but it does demonstrate nicely how it works Typical use cases for this Finding the prior week or month sales for a sales dataset, Forecasting closing stock by carrying forward the previous days closing stock It can be used wherever you need to find either the previous row and or next row of a dataset, like you might do in Excel
  • 7. Hope you found this useful
  • 8. For more Tips, Tricks and Timesavers, visit our website Tips and Timesavers | Select Distinct Limited Credit: simon.harrison@selectdistinct.co.uk