Hi,

I noticed an inconsistency in the behavior of sequence-related
functions for a freshly created sequence.
CREATE SEQUENCE s1;

postgres=# select last_value from pg_sequences;
 last_value
------------

(1 row)

postgres=# select pg_sequence_last_value('s1');
 pg_sequence_last_value
------------------------

(1 row)

postgres=# select las_value from pg_get_sequence_data('s1');
 last_value
------------
          1
(1 row)

As you can see:

pg_sequences and pg_sequence_last_value return NULL for last_value,
which aligns with the expectation that the sequence hasn't been used
yet. However, pg_get_sequence_data returns the start value (1) even
though is_called is false. This seems inconsistent. I felt
pg_get_sequence_data should also return NULL for last_value in this
case to match the others.
Attached patch has a fix for the same. Thoughts?

Regards,
Vignesh
From d80a07a7a1ada926af31de180abc00240dd61ad7 Mon Sep 17 00:00:00 2001
From: Vignesh C <[email protected]>
Date: Wed, 20 Aug 2025 16:10:17 +0530
Subject: [PATCH v1] Fix pg_get_sequence_data showing incorrect last_value

Fix pg_get_sequence_data showing incorrect last_value for a newly
created sequence.
---
 src/backend/commands/sequence.c | 6 +++++-
 src/bin/pg_dump/pg_dump.c       | 2 +-
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index a3c8cff97b0..896f862c0d9 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -1836,7 +1836,11 @@ pg_get_sequence_data(PG_FUNCTION_ARGS)
 
 		seq = read_seq_tuple(seqrel, &buf, &seqtuple);
 
-		values[0] = Int64GetDatum(seq->last_value);
+		if (seq->is_called)
+			values[0] = Int64GetDatum(seq->last_value);
+		else
+			isnull[0] = true;
+
 		values[1] = BoolGetDatum(seq->is_called);
 
 		UnlockReleaseBuffer(buf);
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index fc7a6639163..4defae1a59f 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -19175,8 +19175,8 @@ dumpSequenceData(Archive *fout, const TableDataInfo *tdinfo)
 		entry = bsearch(&key, sequences, nsequences,
 						sizeof(SequenceItem), SequenceItemCmp);
 
-		last = entry->last_value;
 		called = entry->is_called;
+		last = called ? entry->last_value : entry->startv;
 	}
 
 	resetPQExpBuffer(query);
-- 
2.43.0

Reply via email to