Goal Find columns in non-empty tables that do not contain any values. If there are no values in a columns, then it may mean that one hasn't tested constraints that have been declared to the column or implemented by using triggers. It could also mean that such columns are not needed at all.
Notes The query does not look up the actual data but relies on the result of statistics collection process (see the ANALYZE statement). The side effect of running the test is that the statistics of the entire database will be refreshed.
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 Drop the column or start to use it.
Data Source INFORMATION_SCHEMA+system catalog
SQL Query
ANALYZE;
SELECT ps.schemaname, ps.tablename, ps.attname 
FROM pg_catalog.pg_stats AS ps INNER JOIN pg_catalog.pg_stat_all_tables AS psat
ON ps.schemaname=psat.schemaname AND ps.tablename=psat.relname
WHERE  ps.schemaname NOT IN (SELECT schema_name FROM INFORMATION_SCHEMA.schemata WHERE schema_name<>'public' AND schema_owner='postgres' AND schema_name IS NOT NULL) AND n_distinct = 0 AND psat.n_live_tup>0 
AND psat.last_analyze IS NOT NULL
ORDER BY ps.schemaname, ps.tablename;

SQL statements that help generate fixes for the identified problem.

SQL Query to Generate FixDescription
SELECT format('ALTER TABLE %1$I.%2$I DROP COLUMN %3$I;', ps.schemaname, ps.tablename, ps.attname) AS statements
FROM pg_catalog.pg_stats AS ps INNER JOIN pg_catalog.pg_stat_all_tables AS psat
ON ps.schemaname=psat.schemaname AND ps.tablename=psat.relname
WHERE  ps.schemaname NOT IN (SELECT schema_name FROM INFORMATION_SCHEMA.schemata WHERE schema_name<>'public' AND schema_owner='postgres' AND schema_name IS NOT NULL) AND n_distinct = 0 AND psat.n_live_tup>0 
AND psat.last_analyze IS NOT NULL
ORDER BY ps.schemaname, ps.tablename;
Drop the column.
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
Data at the database logical levelQueries of this category provide information about data in base tables.
Missing dataQueries of this category provide information about missing data (NULLs) in a database.
Unused implementation elementsQueries of this catergory provide information about the database objects that are not used.