From the course: PostgreSQL: Advanced Queries

Unlock the full course today

Join today to access over 24,400 courses taught by industry experts.

Move rows within a result with LEAD and LAG

Move rows within a result with LEAD and LAG - PostgreSQL Tutorial

From the course: PostgreSQL: Advanced Queries

Move rows within a result with LEAD and LAG

- [Instructor] There are two functions that will take a column of values from a table and then shift them up or down in the results. These functions are useful when you want to compare or reference values stored in adjacent rows. We can take a look at an example of how this works by pulling order records from the sales.orders table. These results will be sorted chronologically by customer, so that we can see the sequence of orders placed by each customer over time. Let's take a look at the first customer, BV446. They placed an order on March 19th, a second order on the same day, and a third order on the 26th. Now for each of these rows it would be convenient to be able to see when they placed their previous order and when they placed their next order. This would help us calculate how much time has elapsed between purchases. In order to calculate the time span between orders for each customer, we need to have the subsequent…

Contents