Goal Find domain check constraint names that are used more than once (within the same schema or in different schemas). Different things should have different names. However, here different constraints have the same name. Also make sure that this is not a sign of duplication of domains.
Type Problem detection (Each row in the result could represent a flaw in the design)
Reliability High (Few or no false-positive results)
License MIT License
Fixing Suggestion Give different constraints different names.
Data Source INFORMATION_SCHEMA only
SQL Query
SELECT constraint_name, count(*) AS number_of_occurrences, string_agg(domain_schema || '.' || domain_name, ';
' ORDER BY domain_schema, domain_name) AS domains FROM INFORMATION_SCHEMA.domain_constraints WHERE domain_schema NOT IN (SELECT schema_name FROM INFORMATION_SCHEMA.schemata WHERE schema_name<>'public' AND schema_owner='postgres' AND schema_name IS NOT NULL) GROUP BY constraint_name HAVING Count(*)>1 ORDER BY Count(*) DESC, constraint_name;

SQL statements that help generate fixes for the identified problem.

SQL Query to Generate FixDescription
WITH domain_constraints AS (SELECT constraint_name, domain_schema, domain_name
FROM INFORMATION_SCHEMA.domain_constraints
WHERE domain_schema NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL)),
duplicate_names AS (SELECT constraint_name
FROM domain_constraints
GROUP BY constraint_name
HAVING Count(*)>1)
SELECT format('ALTER DOMAIN %1$I.%2$I RENAME CONSTRAINT %3$I TO %3$s%2$s;', domain_schema, domain_name, constraint_name) AS statements
FROM domain_constraints
WHERE constraint_name IN (SELECT constraint_name
FROM duplicate_names)
ORDER BY domain_schema, domain_name;
Rename the constraint by adding domain name to the end of the constraint name.
Collections

This query belongs to the following collections:

NameDescription
Find problems automaticallyQueries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .
Categories

This query is classified under the following categories:

NameDescription
CHECK constraintsQueries of this category provide information about CHECK constraints.
DomainsQueries of this category provide information about reusable specifications of column properties.
Duplication of implementation elementsQueries of this catergory provide information about the duplication of the database objects.
NamingQueries of this category provide information about the style of naming.