0

I am baffled at to why the Postgresql position function gives different results for what seems to be a straightforward test.

Here is query #1:

SELECT count(*)
FROM 
    dnasample D, ibg_studies ST, subjects S
WHERE 
    D.studyindex=ST.studyindex
    AND ST.studyabrv='CONGER'
    AND D.subjectidkey=S.id
    AND D.projectindex IS NULL
    AND POSITION('Previous subjectid:' in D.comment) IS NULL

which returns a result of 246.

Then here is query #2:

SELECT count(*)
FROM 
    dnasample D, ibg_studies ST, subjects S
WHERE 
    D.studyindex=ST.studyindex
    AND ST.studyabrv='CONGER'
    AND D.subjectidkey=S.id
    AND D.projectindex IS NULL
    AND POSITION('Previous subjectid:' in D.comment)=0 

I do not see why these return such different results?

I've tried reading the Postgres documentation to clarify the difference between zero and the null string, but not much luck there yet...

Thanks in advance, --Rick

2 Answers 2

5

The position(needle in haystack) function will return:

  • Zero if needle is not NULL and not in haystack and haystack is not NULL.
  • A positive value if needle is in haystack with one being the beginning of haystack.
  • NULL if needle or haystack are NULL.

For example:

=> select position('a'  in 'a' ) as a,
          position('a'  in 'b' ) as b,
          position('a'  in null) as n1,
          position(null in 'a' ) as n2,
          position(null in null) as n3;
 a | b | n1 | n2 | n3 
---+---+----+----+----
 1 | 0 |    |    |   

That empty spots under n1 through n3 are NULLs.

So this condition:

POSITION('Previous subjectid:' in D.comment) IS NULL

is equivalent to:

D.comment IS NULL

whereas this:

POSITION('Previous subjectid:' in D.comment)=0

will be true if and only if D.comment IS NOT NULL and D.comment does not contain 'Previous subjectid:'.

So the two conditions are quite different.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks; I understand the difference now; great answer.
This question has been answered...no more are needed!
1

NULL is actually a no value. 0 is a pool of bit data.

This is the difference.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.