Query goal: | Find the number of direct and all (direct+indirect) child tables of a base table based on the table inheritance. |
Notes about the query: | 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. |
Query type: | Sofware measure (Numeric values (software measures) about the database) |
Query license: | MIT License |
Data source: | system catalog only |
SQL query: | Click on query to copy it
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; |
Collection name | Collection 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 |
Category name | Category description |
---|---|
Table inheritance | Queries of this category provide information about the inheritance between base tables. |
Reference |
---|
https://www.postgresql.org/docs/current/tutorial-inheritance.html |