How can I write an SQL query that returns a record only if ALL of the associated records in a joined table satisfy some condition.
For example, if A has many B, I want to SELECT * FROM A WHERE all related B’s for a given A have B.some_val > value
I know this is probably a pretty basic question, so thanks for any help. Also, if it makes a difference, I’m using postgres.
Sam
Assuming no need for correlation, use:
If you do need correlation:
Explanation
The
EXISTSevaluates on a boolean, based on the first match – this makes it faster than say using IN, and — unlike using a JOIN — will not duplicate rows. The SELECT portion doesn’t matter – you can change it toEXISTS SELECT 1/0 ...and the query will still work though there’s an obvious division by zero error.The subquery within the
EXISTSuses the aggregate function MIN to get the smallest B.some_val – if that value is larger than the a.val value, the a.val is smaller than all of the b values. The only need for aWHEREclause is for correlation – aggregate functions can only be used in theHAVINGclause.