Say we have two tables:
Company
+---+-----+
|id | name|
+---+-----+
|1 | bar |
|2 | foo |
+---+-----+
Branch
+----+----+-------+
|cid | id | profit|
+----+----+-------+
|1 | 10 | 100 |
|1 | 11 | 200 |
|2 | 20 | 50 |
+----+----+-------+
--cid in Branch is the foreign key to company id
The query is to find out unique companies with at least one branch having profit > 100 say.
One way is:
SELECT DISTINCT c.id, c.name
FROM Company c, Branch b
WHERE c.id == b.cid AND b.profit > 100;
The particular scenario is that very few companies have branches (basically the entries in Branch table is far fewer than those in Company. Given this information is the above query the best possible? Or is there any alternative?
A more efficient method may be to use an EXISTS clause: