2

Is there a simpler way to implement

select (case when ((a is null) or (b is null)) then null else (case when
(a = b) then true else false end) end) from ...

in PostgreSQL, or other major RDBMS for that matter?

1
  • select a = b will return exactly the same thing or a is not distinct from b Commented Jul 20, 2019 at 17:13

2 Answers 2

5

I think the simplest is:

select (a = b)

although this is not exactly your logic, because this returns NULL if either a or b are NULL. It might be good enough.

If you want it to return false if either a or b are NULL but not both, then:

select (a = b) and nullif(coalesce(a, b) is null, true)

EDIT:

Because you ask about other databases, one way of expressing the logic would be:

(case when a = b then 1 when a <> b then 0 end) as flag

This returns NULL if either is NULL.

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

5 Comments

thanks. my logic is wrong. I want null if either is null (will changed the question).
@user66081 . . . That is the first option; it seemed like a reasonable interpretation.
For some reason I though it wouldn't work without trying. Do you know if this has a high chance of working on other major RDBMS?
@user66081 . . . If the database supports a boolean type then it should work. Otherwise, you'll need more explicit logic.
select a is not distinct from b to get a null safe a = b
2

You can write

SELECT CASE
       WHEN (a IS NULL) OR (b IS NULL) THEN NULL
       WHEN (a = b) THEN 'true'
       ELSE 'false'
       END

2 Comments

Did you copy the code from the OP's question and posted it as an answer?
No I was wrote answer when I was in bus so my network was weak and I send answer later and when I send it I see another answer

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.