This query identifies junction tables (implementing a binary relationship via two foreign keys) whose names are simple concatenations of the parent table names, often with minor variations (e.g., Courses_Lecturer). This naming convention is a design smell as it describes the physical implementation rather than the conceptual relationship being modeled. The recommended best practice is to rename such tables to reflect the domain concept they represent. For instance, the relationship between Course and Lecturer should be named after the activity it represents, such as Teaching or Course_Assignment.
Type
Problem detection (Each row in the result could represent a flaw in the design)
with two_fk as (select c.relnamespace as target_schema_oid, c.oid as target_table_oid
from pg_constraint o inner join pg_class c on c.oid = o.conrelid
where o.contype = 'f'
group by target_schema_oid, target_table_oid
having count(*)=2),
fk as (select
(select nspname from pg_namespace where oid=f.relnamespace) as foreign_schema,
f.relname as foreign_table,
(select nspname from pg_namespace where oid=c.relnamespace) as target_schema,
c.relname as target_table
from pg_constraint o inner join pg_class f on f.oid = o.confrelid
inner join pg_class c on c.oid = o.conrelid
where o.contype = 'f' and
(c.relnamespace, c.oid) in (select target_schema_oid, target_table_oid from two_fk)),
fk_with_names as (select fk1.foreign_schema as foreign_schema1, fk1.foreign_table as foreign_table1,
fk2.foreign_schema as foreign_schema2, fk2.foreign_table as foreign_table2,
fk1.target_schema, fk1.target_table
from fk as fk1, fk as fk2
where fk1.target_schema=fk2.target_schema and fk1.target_table=fk2.target_table and fk1.foreign_table>fk2.foreign_table)
select foreign_schema1, foreign_table1, foreign_schema2, foreign_table2, target_schema, target_table as suspected_table_name
from fk_with_names
where target_table ~* ('^' || foreign_table1 || '.*[_]*' || foreign_table2 || '.*$')
or target_table ~* ('^' || foreign_table2 || '.*[_]*' || foreign_table1 || '.*$')
order by target_schema, target_table;
Categories
This query is classified under the following categories:
Name
Description
Naming
Queries of this category provide information about the style of naming.
Relationships between tables
Queries of this category provide information about how database tables are connected to each other and whether such connections have been explicitly defined and whether it has been done correctly.