简体   繁体   中英

Boolean type in Postgres does not work as expected

I'm using Ubuntu 16.04 and psql (PostgreSQL) 9.4.14.

I just encountered a really weird case. The sum of three states of boolean is not equal to the whole count.

在此处输入图片说明

This is deleted field attribute default as false.

I tried:

The whole count:

SELECT count(*) from table; the count -> 9000

The un-deleted count:

SELECT count(*) from table where deleted; the count -> 400;

Same as:

SELECT count(*) from table where deleted = true; the count -> 400;

The deleted count:

SELECT count(*) from table where not deleted; the count -> 0; 

Same as:

SELECT count(*) from table where deleted <> true; the count -> 0;

And the null case is:

SELECT count(*) from table where deleted = null; the count -> 0;

I checked the official doc .

PostgreSQL provides the standard SQL type boolean. The boolean type can have several states: "true", "false", and a third state, "unknown", which is represented by the SQL null value.

But as you can see, that final sum from the three states cannot be 9000 .

So surprisingly annoyed.

Please share some advice for this, thank you!

You need to use IS NULL to compare a column against NULL :

select count(*) from info_security_group where deleted is null;

My guess is that this will return a count of 8600.

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