Nested Query
Nested Query
Nested Query
For Example: To select the first name of all the students, the query would be like:
Output:
Name
-------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra
mysql> show columns from student1;
+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| sid | int(11) | YES | | NULL | |
| name | char(20) | YES | | NULL | |
| subject | char(10) | YES | | NULL | |
+---------+----------+------+-----+---------+-------+
3 rows in set (0.01 sec)
but, if you do not know their names, then to get their id's you need to write the query in this
manner,
Subquery Output:
id first_name
-------- -------------
100 Rahul
102 Stephen
In the above sql statement, first the inner query is processed first and then the outer query
is processed.
Find names of sailors whove reserved boat #103:
SELECT S.sname
FROM Sailors S
WHERE S.sid IN (SELECT R.sid
FROM Reserves R
WHERE R.bid=103)
A very powerful feature of SQL: a WHERE clause can itself
contain an SQL query! (Actually, so can FROM and HAVING
clauses.)
To find sailors whove not reserved #103, use NOT IN.
To understand semantics of nested queries, think of a nested loops
evaluation: For each Sailors tuple, check the qualification by
computing the subquery.
SELECT S.sname FROM Sailors S
WHERE S.sid IN (SELECT R.sid FROM Reserves R
WHERE R.bid IN( select B.bid FROM Boats B
WHERE B. color=red))
A query is called correlated subquery when both the
inner query and the outer query are interdependent. For
every row processed by the inner query, the outer query
is processed as well. The inner query depends on the
outer query before it can be processed.
In nested query inner query is independent of outer
query
SELECT *
FROM Sailors S
WHERE S.rating > ANY (SELECT S2.rating
FROM Sailors S2
WHERE S2.sname=Horatio)
Nested Subquery
1) You can nest as many queries you want but it is recommended not to nest
more than 16 subqueries in oracle
Non-Corelated Subquery
2) If a subquery is not dependent on the outer query it is called a non-
correlated subquery
Subquery Errors
3) Minimize subquery errors: Use drag and drop, copy and paste to avoid
running subqueries with spelling and database types. Watch your multiple
field SELECT comma use, extra or to few getting SQL error message
"Incorrect syntax".