Goal This query identifies all base table columns that enforce a maximum value length through the use of a CHECK constraint. It specifically searches for constraint definitions that contain length-calculating functions (such as length(), char_length(), or similar patterns) to provide a comprehensive list of all columns where data length is explicitly managed by a business rule at the database level.
Type General (Overview of some aspect of the database.)
License MIT License
Data Source system catalog only
SQL Query
WITH column_checks AS (SELECT
    ns.nspname AS table_schema,
    cls.relname AS table_name,
    a.attname AS column_name,
    COALESCE(basetype.typname, t.typname) AS data_type,
    pg_get_constraintdef(c.oid) AS check_clause,
	'TABLE CHECK' AS check_type
FROM
    pg_constraint c
INNER JOIN
    pg_class cls ON c.conrelid = cls.oid
INNER JOIN
    pg_namespace ns ON cls.relnamespace = ns.oid
INNER JOIN
    pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
INNER JOIN
    pg_type t ON a.atttypid = t.oid
LEFT JOIN
    pg_type basetype ON t.typtype = 'd' AND t.typbasetype = basetype.oid
WHERE
    c.contype = 'c'
    AND c.conrelid != 0
    AND cardinality(c.conkey) = 1

UNION ALL

SELECT
    ns.nspname AS table_schema,
    cls.relname AS table_name,
    a.attname AS column_name,
    basetype.typname AS data_type,
    pg_get_constraintdef(c.oid) AS check_clause,
	'DOMAIN CHECK' AS check_type
FROM
    pg_attribute a
INNER JOIN
    pg_class cls ON a.attrelid = cls.oid
INNER JOIN
    pg_namespace ns ON cls.relnamespace = ns.oid
INNER JOIN
    pg_type t ON a.atttypid = t.oid
INNER JOIN
    pg_constraint c ON c.contypid = t.oid
INNER JOIN
    pg_type basetype ON t.typbasetype = basetype.oid
WHERE
    cls.relkind IN ('r', 'p', 'f')
    AND a.attnum > 0
    AND NOT a.attisdropped
    AND t.typtype = 'd'
    AND c.contype = 'c')
SELECT table_schema, table_name, column_name, data_type, check_clause, check_type
FROM column_checks
WHERE check_clause~'(length.*<(=){0,1}.*(?|\{,[[:digit:]]+\})'
AND data_type~*'(char|text)'
ORDER BY table_schema, table_name, column_name;

Categories

This query is classified under the following categories:

NameDescription
CHECK constraintsQueries of this category provide information about CHECK constraints.
Field sizeQueries of this category provide information about the maximum size of values that can be recorded in column fields
Validity and completenessQueries of this category provide information about whether database design represents the world (domain) correctly (validity) and whether database design captures all the information about the world (domain) that is correct and relevant (completeness).