Finding columns that are NOT NULL in PostgreSQL

余生颓废 提交于 2019-12-21 06:46:18

问题


I had an assignment for each table to count nullable columns. Easy:

 SELECT table_name, count(*) FROM INFORMATION_SCHEMA.COLUMNS
 WHERE is_nullable='NO'
 GROUP BY table_name;


Now I have to modify this to count "columns that have property "NOT NULL"". Will the following code do this or will it just check weather column name is not null?

CREATE TEMP TABLE A AS 
SELECT DISTINCT column_name, table_name AS name FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name IS NOT NULL
GROUP BY table_name, column_name;

SELECT name, count(*) FROM A
GROUP BY name;

If no... Any advices?


回答1:


No.

This query

SELECT DISTINCT column_name, table_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name IS NOT NULL

will return all the rows that have a value in the column "column_name".

All rows in that table will always have a value in the column "column_name".

Do you just need to know how many columns are nullable and how many are non-nullable?

SELECT is_nullable, COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY is_nullable;

Count by table name? I think you can use this.

SELECT table_name, is_nullable, count(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY table_name, is_nullable
ORDER BY table_name, is_nullable;



回答2:


To get a count of all NOT NULL columns in any table, use:

SELECT count(*)
  FROM information_schema.columns
 WHERE table_schema = 'table_schema_here'
   AND table_name   = 'table_name_here'
   AND is_nullable = 'YES';

I hope this will help someone.



来源:https://stackoverflow.com/questions/5345380/finding-columns-that-are-not-null-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!