Is "WHERE foo" and "WHERE foo IS TRUE" equivalent in PostgreSQL?

Viewed 145

I get the same counts from these:

SELECT COUNT(*) FROM "users" WHERE admin
SELECT COUNT(*) FROM "users" WHERE admin IS TRUE

Are they equivalent or are there subtle or not-so-subtle differences?

Is one preferred, perhaps for cross-engine compatibility?

2 Answers

There is a subtle difference in the handling of NULL values as mentioned in the documentation:

SELECT null::boolean -- null
SELECT null::boolean IS TRUE -- boolean false
SELECT null::boolean IS NOT TRUE -- boolean true

In short, the IS syntax always returns a boolean value, rather than propagating NULLs. This wouldn't make a difference in a WHERE clause, because a NULL condition excludes rows, but is an important difference to know.

Other than that, the main advantage is being explicit: in a complex SQL query, it might not be obvious that a particular column is a boolean, so adding the IS TRUE makes the intent clearer.

Users coming from systems with no boolean type might also instinctively use WHERE admin = TRUE (which would propagate NULLs in a context where that made a difference). The code wouldn't actually be portable to such systems, because they wouldn't recognise the "true" keyword.

They are absolutely equivalent.

There is no technical reason to prefer one or the other. I personally prefer the first, which is shorter, while I find that most other people prefer WHERE admin = TRUE.

Related