LAG() Window Function – with examples in PostgreSQL.

Having recently covered the LEAD() Window Function here on Digital Owl’s Prose, it only makes sense to follow-up with a post on its counterpart: LAG(). By all means, don’t lag behind. Read on and learn something with me…

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.

lone-window-green-wall-orange-roof
Photo by Cameron Kirby on Unsplash
OS and DB used:
  • Xubuntu Linux 18.04.2 LTS (Bionic Beaver)
  • PostgreSQL 11.2


Self-Promotion:

If you enjoy the content written here, by all means, share this blog and your favorite post(s) with others who may benefit from or like it as well. Since coffee is my favorite drink, you can even buy me one if you would like!


I’ll use a couple of tables from the PostgreSQL practice DVD Rental database for the example queries below.

Throughout this post, let’s assume we have this CTE that returns the below query results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
WITH valued_customers AS (
SELECT
        c.first_name AS first_name,
        c.last_name AS last_name,
        SUM(p.amount) AS total_spent
        FROM customer AS c
INNER JOIN payment AS p
ON c.customer_id = p.customer_id
GROUP by c.first_name, c.last_name
HAVING SUM(p.amount) > 150)

SELECT * FROM valued_customers;
 first_name | last_name | total_spent
------------+-----------+-------------
 Lena       | Jensen    |      154.70
 Tommy      | Collazo   |      183.63
 Ana        | Bradley   |      167.67
 Clara      | Shaw      |      189.60
 Brittany   | Riley     |      151.73
 Warren     | Sherrod   |      152.69
 Karl       | Seal      |      208.58
 Arnold     | Havens    |      161.68
 Mike       | Way       |      162.67
 Wesley     | Bull      |      158.65
 Gordon     | Allard    |      157.69
 Marcia     | Dean      |      166.61
 June       | Carroll   |      151.68
 Tim        | Cary      |      154.66
 Eleanor    | Hunt      |      211.55
 Marion     | Snyder    |      194.61
 Steve      | Mackenzie |      152.68
 Guy        | Brownlee  |      151.69
 Curtis     | Irby      |      167.62
 Louis      | Leone     |      156.66
 Rhonda     | Kennedy   |      191.62
(21 rows)

As you have likely guessed, LAG() operates similarly as LEAD() with the difference being; where LEAD() accesses current and subsequent row data, LAG() returns previous row and current row data.

Let’s gain crystal-clear clarity with a few examples. Feel free to visit this post I wrote on LAG() for an example of the syntax, as they are the same.

Like before, I’ll set NULL to something more visible during the psql session with \pset:

1
2
dvdrental=> \pset null '!#!'
Null display is "!#!".

Here, I pass in 2 for the offset parameter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
SELECT
first_name, last_name, total_spent,
LAG(total_spent, 2) OVER(ORDER BY total_spent) as lagging
FROM valued_customers;
 first_name | last_name | total_spent | lagging
------------+-----------+-------------+---------
 June       | Carroll   |      151.68 |     !#!
 Guy        | Brownlee  |      151.69 |     !#!
 Brittany   | Riley     |      151.73 |  151.68
 Steve      | Mackenzie |      152.68 |  151.69
 Warren     | Sherrod   |      152.69 |  151.73
 Tim        | Cary      |      154.66 |  152.68
 Lena       | Jensen    |      154.70 |  152.69
 Louis      | Leone     |      156.66 |  154.66
 Gordon     | Allard    |      157.69 |  154.70
 Wesley     | Bull      |      158.65 |  156.66
 Arnold     | Havens    |      161.68 |  157.69
 Mike       | Way       |      162.67 |  158.65
 Marcia     | Dean      |      166.61 |  161.68
 Curtis     | Irby      |      167.62 |  162.67
 Ana        | Bradley   |      167.67 |  166.61
 Tommy      | Collazo   |      183.63 |  167.62
 Clara      | Shaw      |      189.60 |  167.67
 Rhonda     | Kennedy   |      191.62 |  183.63
 Marion     | Snyder    |      194.61 |  189.60
 Karl       | Seal      |      208.58 |  191.62
 Eleanor    | Hunt      |      211.55 |  194.61
(21 rows)

Notice since LAG() does not have 2 previous rows to look back and access data from, NULL is displayed for the first 2 rows in the result set.

We’ll try an even larger number next with 5:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
SELECT
first_name, last_name, total_spent,
LAG(total_spent, 5) OVER(ORDER BY total_spent) as lagging
FROM valued_customers;
first_name | last_name | total_spent | lagging
------------+-----------+-------------+---------
 June       | Carroll   |      151.68 |     !#!
 Guy        | Brownlee  |      151.69 |     !#!
 Brittany   | Riley     |      151.73 |     !#!
 Steve      | Mackenzie |      152.68 |     !#!
 Warren     | Sherrod   |      152.69 |     !#!
 Tim        | Cary      |      154.66 |  151.68
 Lena       | Jensen    |      154.70 |  151.69
 Louis      | Leone     |      156.66 |  151.73
 Gordon     | Allard    |      157.69 |  152.68
 Wesley     | Bull      |      158.65 |  152.69
 Arnold     | Havens    |      161.68 |  154.66
 Mike       | Way       |      162.67 |  154.70
 Marcia     | Dean      |      166.61 |  156.66
 Curtis     | Irby      |      167.62 |  157.69
 Ana        | Bradley   |      167.67 |  158.65
 Tommy      | Collazo   |      183.63 |  161.68
 Clara      | Shaw      |      189.60 |  162.67
 Rhonda     | Kennedy   |      191.62 |  166.61
 Marion     | Snyder    |      194.61 |  167.62
 Karl       | Seal      |      208.58 |  167.67
 Eleanor    | Hunt      |      211.55 |  183.63
(21 rows)

In the screen shot below, make note how in the 6th row of the result set, LAG() accesses and displays the ‘total_spent’ amount for the 1st row (5 rows previous) where those 4 rows above display NULL.

sql-output-code-with-red-arrow
LAG() 5 rows…

Since this short post has mostly contained arbitrary examples for demonstration, I am anxious to know of any real-world use cases you have used LAG() for or any other ideas you have about it. So please, by all means, leave your comment below.

Like what you have read? See anything incorrect? Please comment below and thanks for reading!!!

Explore the official PostgreSQL 11 On-line Documentation for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, is performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Advertisements

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.