Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all rows with a NULL value in any column using PostgreSQL

Tags:

sql

postgresql

There are many slightly similar questions, but none solve precisely this problem. "Find All Rows With Null Value(s) in Any Column" is the closest one I could find and offers an answer for SQL Server, but I'm looking for a way to do this in PostgreSQL.

How can I select only the rows that have NULL values in any column?

I can get all the column names easily enough:

select column_name from information_schema.columns where table_name = 'A'; 

but it's unclear how to check multiple column names for NULL values. Obviously this won't work:

select* from A where (   select column_name from information_schema.columns where table_name = 'A'; ) IS NULL; 

And searching has not turned up anything useful.

like image 979
iconoclast Avatar asked Jun 24 '15 19:06

iconoclast


People also ask

How do I get NULL records in PostgreSQL?

Example - With INSERT StatementINSERT INTO contacts (first_name, last_name) SELECT first_name, last_name FROM employees WHERE employee_number IS NULL; This PostgreSQL IS NULL example will insert records into the contacts table where the employee_number contains a NULL value.

How do you find NULL records in a table?

Use the IS NULL operator in a condition with WHERE to find records with NULL in a column. Of course, you can also use any expression instead of a name of a column and check if it returns NULL. Nothing more than the name of a column and the IS NULL operator is needed (in our example, middle_name IS NULL ).

Can we use NVL in PostgreSQL?

PostgreSQL does not support nvl functions, but it supports coalesce functions. The usage is the same with that in Oracle. You can utilize coalesce to convert nvl and coalesce functions of Oracle. The arguments have to be of the same type, or can be automatically converted to the same type.


1 Answers

You can use NOT(<table> IS NOT NULL).

From the documentation :

If the expression is row-valued, then IS NULL is true when the row expression itself is null or when all the row's fields are null, while IS NOT NULL is true when the row expression itself is non-null and all the row's fields are non-null.

So :

SELECT * FROM t; ┌────────┬────────┐ │   f1   │   f2   │ ├────────┼────────┤ │ (null) │      1 │ │      2 │ (null) │ │ (null) │ (null) │ │      3 │      4 │ └────────┴────────┘ (4 rows)  SELECT * FROM t WHERE NOT (t IS NOT NULL); ┌────────┬────────┐ │   f1   │   f2   │ ├────────┼────────┤ │ (null) │      1 │ │      2 │ (null) │ │ (null) │ (null) │ └────────┴────────┘ (3 rows) 
like image 159
Marth Avatar answered Sep 22 '22 09:09

Marth