Find the number of direct and all (direct+indirect) child tables of a base table based on the table inheritance.
Notes
The query finds transitive closure of tables. In other words it finds all possible paths between tables where it is possible to reach from one table to another based on parent-child relationships that have been established by using table inheritance.
Type
Sofware measure (Numeric values (software measures) about the database)
WITH RECURSIVE transitive_closure AS (
WITH foo AS (SELECT inhrelid AS child, inhparent AS parent
FROM pg_inherits)
SELECT child, parent, 1 AS distance, child || '.' || parent || '.' AS path_string
FROM foo WHERE parent IS NOT NULL
UNION ALL
SELECT tc.child, e.parent, tc.distance + 1, tc.path_string || e.parent || '.' AS path_string
FROM foo AS e INNER JOIN transitive_closure AS tc ON e.child = tc.parent
WHERE tc.path_string NOT LIKE '%' || e.parent || '.%')
SELECT np.nspname AS table_schema, c.relname AS table_name, Count(DISTINCT tc.child) AS number_of_all_children,
(SELECT Count(*) AS cnt FROM pg_inherits WHERE pg_inherits.inhparent=c.oid) AS number_of_direct_children
FROM transitive_closure AS tc INNER JOIN pg_class AS c ON tc.parent=c.oid
INNER JOIN pg_namespace AS np ON c.relnamespace=np.oid
INNER JOIN pg_authid AS a ON np.nspowner=a.oid
WHERE (np.nspname='public' OR rolname<>'postgres')
GROUP BY c.oid, np.nspname, c.relname
ORDER BY Count(*) DESC, table_schema, table_name;
Collections
This query belongs to the following collections:
Name
Description
Find problems by overview
Queries that results point to different aspects of database that might have problems. A human reviewer has to decide based on the results as to whether there are problems or not .
Find quick numeric overview of the database
Queries that return numeric values showing mostly the number of different types of database objects in the database
Categories
This query is classified under the following categories:
Name
Description
Table inheritance
Queries of this category provide information about the inheritance between base tables.