Goal Find generated stored base table columns that expression does not refer to any column of the table. It could be that there will be a constant value in every row in case of this column. The support of generated columns was added to PostgreSQL 12.
Type Problem detection (Each row in the result could represent a flaw in the design)
Reliability Medium (Medium number of false-positive results)
License MIT License
Fixing Suggestion Change the expression of the generated column.
Data Source INFORMATION_SCHEMA only
SQL Query
WITH all_columns AS (SELECT table_schema, table_name, column_name
FROM INFORMATION_SCHEMA.columns
WHERE (table_schema, table_name) IN (SELECT table_schema, table_name
FROM INFORMATION_SCHEMA.tables WHERE table_type='BASE TABLE') 
AND table_schema NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL) 
AND is_generated='NEVER'),
generated_columns AS (SELECT table_schema, table_name, column_name, generation_expression
FROM INFORMATION_SCHEMA.columns
WHERE (table_schema, table_name) IN (SELECT table_schema, table_name
FROM INFORMATION_SCHEMA.tables WHERE table_type='BASE TABLE') 
AND table_schema NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL) 
AND is_generated='ALWAYS'),
referred_columns AS (
SELECT a.table_schema, a.table_name, a.column_name, g.generation_expression
FROM all_columns AS a INNER JOIN generated_columns AS g
ON a.table_schema=g.table_schema AND a.table_name=g.table_name
WHERE g.generation_expression LIKE '%' || a.column_name || '%')
SELECT table_schema, table_name, column_name, generation_expression
FROM generated_columns AS ge
WHERE NOT EXISTS (SELECT 1
FROM referred_columns AS r
WHERE r.table_schema=ge.table_schema
AND r.table_name=ge.table_name
AND r.generation_expression=ge.generation_expression)
ORDER BY table_schema, table_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
Comfortability of data managementQueries of this category provide information about the means that have been used to make the use or management of database more comfortable and thus, more efficient.
Generated columnsQueries of this category provide information about generated stored base table columns.
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).