Saturday, July 18, 2009

Learn Nested Subqueries and Set Comparison use in SQL

- SQL provides a mechanism for the nesting of sub queries.

- A sub query is a select-from-where
expression that is nested within another query.

- A common use of sub queries is to perform tests for set membership, set comparisons,
and set cardinality.

Example Query For Nested Sub queries

- Find all customers who have both an account and a loan at the bank.
select distinct customer_name
from borrower
where customer_name in (select customer_name from depositor)

- Find all customers who have a loan at the bank but do not have an account at the bank
select distinct customer-name
from borrower
where customer_name not in (select customer_name from depositor)

Set Comparison

- Find all branches that have greater assets than some branch
located in kandy.

select distinct T.branch_name
from branch as T, branch as S
where T.assets > S.assets and S.branch_city = ‘kandy’

- Same query using > some clause

select branch_name
from branch
where assets > some(select assets
from branch
where branch_city = ‘kandy’)

No comments:

Post a Comment