简体   繁体   中英

searching not null condition in multiple columns with query postgresql

I want to count how many document that does not have date in field1, field2, field3, and field4. I have created the query as below but it does not really look good.

select 
   count(doc)
where true
   and field1 is not null
   and field2 is not null
   and field3 is not null
   and field4 is not null

How can I apply one filter for multiple columns?

Thanks in advance.

There is nothing at all wrong with your current query, and it is probably what I would be using here. However, you could use a COALESCE trick here:

SELECT COUNT(*)
FROM yourTable
WHERE COALESCE(field1, field2, field3, field4) IS NOT NULL;

This works because for any record having at least one of the four fields assigned to a non NULL date would fail the IS NOT NULL check. Only records for which all four fields are NULL would match.

Note that this counts records having at least one non NULL field. If instead you want to count records where all four fields are NULL , then use:

SELECT COUNT(*)
FROM yourTable
WHERE COALESCE(field1, field2, field3, field4) IS NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM