6. Nested Select Queries Consider the following tables of the Fisherman database: Fisherman FishCatch Table: Now, I wish to find the names of the fishermen who caught a bass (any type). The SQL query would be: select name from fisherman where fishermanid = any(selectfishermanID from FishCatch where fish like ‘%Bass%’) As you can see, any is used to compare a particular record’s field to that of multiple records.
7. Nested Select Queries The previous query can be rewritten using in as follows: Using ANY: select name from fisherman where fishermanid= any(selectfishermanID from FishCatch where fish like ‘%Bass%’) Using IN: select name from fisherman where fishermanidin(selectfishermanID from FishCatch where fish like ‘%Bass%’) NOTE: When using in remember NOT TO PUT THE ‘=‘ (Equal to ) operator
8. Usefulness of having ‘Having’ We have seen that there exists a restriction that the aggregate functions cannot be used in the right side of where clause. This syntactical restriction may lead to several inconveniences while programming. To understand this, see the following problem: Find the Fisherman who has caught 2 fishes: We might think of this solution: Select FishermanID from fishTable where count(fish) =2 But this doesn’t work as aggregate functions are not allowed on the right-side of where clause. So, how do we solve the problem? ‘Having’ is our answer.
9. Having Find the Fisherman who has caught 2 fishes: Solving with having: Select fishermanID from fishtable group by fishermanidhaving count(fish)=2