I can't claim it will break any speed records, but it will do what you ask. No dynamic SQL or user-defined functions necessary.
SELECT t.*
FROM your_table as t
-- If nulls are present, these will not be equal
WHERE to_jsonb(t) = jsonb_strip_nulls(to_jsonb(t))
If performance becomes a real concern such as having to run this query many times, you could create an expression index for it. However, I would recommend normalizing your database's data model if that's the case. You may just be papering over structural defects.
CREATE INDEX nulls_detected
ON your_table (to_jsonb(your_table) = jsonb_strip_nulls(to_jsonb(your_table)));
Further optimizations could probably be found using a bloom filter for your index.
Here's an example of this in action:
CREATE TABLE null_example (
id serial PRIMARY KEY,
col1 int,
col2 text,
col3 boolean
);
INSERT INTO null_example (col1, col2, col3) VALUES
(1, 'test1', true),
(NULL, 'test2', false),
(3, NULL, true),
(4, 'test4', NULL),
(5, 'test5', false);
Now if you run the following…
SELECT t.*
FROM null_example AS t
WHERE to_jsonb(t) = jsonb_strip_nulls(to_jsonb(t));
…you get the following output. Any rows that contain NULL column values have been omitted.
id | col1 | col2 | col3
---+------+-------+------
1 | 1 | test1 | t
5 | 5 | test5 | f
If you are trying to target columns for removal such as from an ALTER TABLE … DROP COLUMN
statement, the following query can help you along the way as well.
SELECT results.key, count(*), array_agg(t.id) AS affected_ids
FROM null_example AS t
CROSS JOIN LATERAL jsonb_each(to_jsonb(t)) AS results(key, value)
WHERE results.value = 'null'::jsonb
GROUP BY results.key
This returns:
key | count | affected_ids
-----+-------+--------------
col2 | 1 | {3}
col3 | 1 | {4}
col1 | 1 | {2}