Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding columns that are NOT NULL in PostgreSQL

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?

like image 808
Allan David Munja Avatar asked Mar 17 '11 21:03

Allan David Munja


People also ask

Where column is not null PostgreSQL?

Here is an example of how to use the PostgreSQL IS NOT NULL condition in a SELECT statement: SELECT * FROM employees WHERE first_name IS NOT NULL; This PostgreSQL IS NOT NULL example will return all records from the employees table where the first_name does not contain a null value.

IS NOT NULL Postgre?

The not-null constraint in PostgreSQL ensures that a column can not contain any null value. This is a column constraint. No name can be defined to create a not-null constraint. This constraint is placed immediately after the data-type of a column.

How do I check for NULL in PostgreSQL?

SELECT * FROM employees WHERE first_number IS NULL; This PostgreSQL IS NULL example will return all records from the employees table where the first_name contains a NULL value.


1 Answers

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; 
like image 182
Mike Sherrill 'Cat Recall' Avatar answered Sep 19 '22 14:09

Mike Sherrill 'Cat Recall'