Archive for May 30th, 2009
Aggregate AND
Comments enabled. I *really* need your comment
From Stack Overflow:
I have a table with a foreign key and a boolean value (and a bunch of other columns that aren't relevant here), as such:
CREATE TABLE myTable ( someKey integer, someBool boolean ); INSERT INTO myTable VALUES (1, 't'), (1, 't'), (2, 'f'), (2, 't');Each
someKeycould have 0 or more entries.For any given
someKey, I need to know if
- All the entries are true, or
- Any of the entries are false
Basically, it's an
AND.
This solution is often used to represent polls that should be unanimous for the decision to be made (i. e. anyone can put a veto on the decision).
PostgreSQL offers a special aggregate BOOL_AND to do this.
However, an aggregate may be less efficient here.
The return value of an AND function is constrained by finding certain values:
- Whenever a
FALSEis found, the return value cannot beTRUEanymore. It's eitherFALSEorNULL. - Whenever a
NULLis found, the return value isNULL
Aggregates in PostgreSQL, however, won't take this into account.
What we need here is a method to stop and return whenever first NULL or FALSE value is found.
Let's create a sample table and see how can it may be done:
Read the rest of this entry »
Subscribe in a reader