Skip to content
Advertisement

How can i get a count(*) of all the columns in a table? Using PostgreSql

I have bunch of tables where several of them have hundreds of columns. I need to get a count of non-null values for each column and I’ve been doing it manually. I would like to figure out a way to get all the counts for all the columns in a table. I looked up stackoverflow and google, but unable to find the answer.

I tried this but it’s just returning a value of 1 for each column. I know it’s just counting the number of column and not the values in each column. Any suggestions?

Advertisement

Answer

COUNT(column_name) always gives you the count of NON NULL values.

Create a generic function like this which can take schema name and table name as arguments.

Here I am constructing select statements joined together by UNION ALLs each returning the value of the column_name and it’s count for all columns when executed dynamically.

Execution

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement