Created
February 14, 2024 23:36
-
-
Save cluesque/17e1519914a1c6195bd49d299235acd3 to your computer and use it in GitHub Desktop.
Postgres: Report how close each table primary key is to its limit
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
WITH column_info AS ( | |
SELECT t.relname AS table_name, c.attname AS column_name, c.atttypid, c.attlen AS length, y.typname AS type | |
, pg_get_expr(adbin, adrelid) AS default | |
, (regexp_matches(pg_get_expr(adbin, adrelid), 'nextval..(.*).::regclass'))[1] AS sequencename | |
FROM pg_class t | |
LEFT OUTER JOIN pg_attribute c ON c.attrelid = t.oid | |
LEFT OUTER JOIN pg_type y ON y.oid = c.atttypid | |
LEFT OUTER JOIN pg_attrdef d ON t.oid = d.adrelid AND d.adnum = c.attnum | |
WHERE pg_get_expr(adbin, adrelid) LIKE '%nextval%' | |
), | |
max_values(length, max_value) AS (VALUES (4, 2147483647), (8, 9223372036854775807)), | |
sequence_info AS ( | |
SELECT table_name, column_name | |
, (s.last_value * 100 / m.max_value) percent_of_limit | |
FROM column_info ci | |
JOIN pg_sequences s ON s.sequencename = ci.sequencename | |
JOIN max_values m ON m.length = ci.length | |
WHERE s.last_value IS NOT NULL | |
) | |
SELECT (table_name || '.' || column_name) AS name, | |
percent_of_limit || '%' AS percent | |
FROM sequence_info | |
ORDER BY percent_of_limit DESC | |
LIMIT 10; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment