Created
October 24, 2024 13:35
-
-
Save wdhowe/f68ab515f9e5ea137862600de7fe3ca6 to your computer and use it in GitHub Desktop.
Postgresql: List All Sequences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- List all sequences and their current values, excluding system schemas | |
SELECT | |
n.nspname as schema, | |
s.relname as sequence_name, | |
t.relname as table_name, | |
a.attname as column_name, | |
pg_sequence_last_value(s.oid) as last_value | |
FROM pg_class s | |
JOIN pg_namespace n ON n.oid = s.relnamespace | |
JOIN pg_depend d ON d.objid = s.oid | |
AND d.deptype = 'a' | |
JOIN pg_class t ON t.oid = d.refobjid | |
JOIN pg_attribute a ON a.attrelid = t.oid | |
AND a.attnum = d.refobjsubid | |
WHERE s.relkind = 'S' | |
AND n.nspname NOT IN ('pg_catalog', 'information_schema') | |
ORDER BY schema, sequence_name; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION list_seqs() | |
RETURNS TABLE ( | |
schema_name text, | |
sequence_name text, | |
table_name text, | |
column_name text, | |
last_value bigint | |
) | |
LANGUAGE SQL | |
STABLE | |
AS $$ | |
SELECT | |
n.nspname as schema_name, | |
s.relname as sequence_name, | |
t.relname as table_name, | |
a.attname as column_name, | |
pg_sequence_last_value(s.oid) as last_value | |
FROM pg_class s | |
JOIN pg_namespace n ON n.oid = s.relnamespace | |
JOIN pg_depend d ON d.objid = s.oid | |
AND d.deptype = 'a' | |
JOIN pg_class t ON t.oid = d.refobjid | |
JOIN pg_attribute a ON a.attrelid = t.oid | |
AND a.attnum = d.refobjsubid | |
WHERE s.relkind = 'S' | |
AND n.nspname NOT IN ('pg_catalog', 'information_schema') | |
ORDER BY schema_name, sequence_name; | |
$$; | |
-- To use the function, simply call: | |
-- SELECT * FROM list_seqs(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment