Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

sql - Why does PostgreSQL not return null values when the condition is <> true

I was confused behind the reasoning of the following:

SELECT * FROM table WHERE avalue is null

Returns x number of rows where 'avalue' is null

SELECT * FROM table WHERE avalue <> true

Does not return rows where 'avalue' is null.

My reasoning (which appears to be incorrect) is that as null is a unique value (it isn't even equal to null) means that it should show in the result set as it isn't equal to true either.

I guess you could argue that by saying column <> value you imply that the column has a value therefore ignoring the null values altogether.

What is the reasoning behind this and is this the same in other common SQL DB's?

My reasoning (assumption) is telling me this is counter-intuitive and I wanted to learn why.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Every halfway decent RDBMS does it the same way, because it's correct.
I am quoting the Postgres manual here:

Ordinary comparison operators yield null (signifying "unknown"), not true or false, when either input is null. For example, 7 = NULL yields null, as does 7 <> NULL. When this behavior is not suitable, use the IS [ NOT ] DISTINCT FROM constructs:

expression IS DISTINCT FROM expression
expression IS NOT DISTINCT FROM expression

Note that these expressions perform a bit slower than simple expression <> expression comparison.

For boolean values there is also the simpler IS NOT [TRUE | FALSE].
To get what you expected in your second query, write:

SELECT * FROM table WHERE avalue IS NOT TRUE;

SQL Fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...