Sub Queries
Sub Queries
o - A SELECT clause
o - A FROM clause
o - A WHERE clause
A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
You can use the comparison operators, such as >, <, or =. The comparison operator
can also be a multiple-row operator, such as IN, ANY, or ALL.
A subquery is also called an inner query or inner select, while the statement
containing a subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an inner
query can be passed to the outer query.
The subquery (inner query) executes once before the main query (outer query)
executes.
Now we want to write a query to identify all students who get better marks than that of the
student who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better marks
than the result of the first query.
SELECT *
FROM `marks`
WHERE studentid = 'V002';
Query result:
You can combine the above two queries by placing one query inside the other. The subquery
(also called the 'inner query') is the query inside the parentheses. See the following code and
query result :
If a subquery (inner query) returns a null value to the outer query, the outer query will
not return any rows when using certain comparison operators in a WHERE clause.
Case study 2
Correlated sub queries are used for row-by row processing. Each sub query is executed once
for every row of the outer query. Normal subqueries inner queries executed first, and outer
query executed. But in correlated sub queries outer query is always depends inner query so
outer query executed first, inner query executed for each row in outer query.
Case3
Inserting values from other table using select
QL> select * from customer;
New table created
CID NAME SQL> create table cus(id varchar2(5),cname
--- ---------- varchar2(10));
c01 Riya
c02 Jiya Table created.
c03 Diya
c04 Taral SQL> insert into cus(id,cname) select cid,name
c05 Saral from customer;
5 rows created.
ID CNAME
----- ----------
c01 Riya
c02 Jiya
c03 Diya
c04 Taral
c05 Saral
2 rows updated.
SQL> delete from account where ano To delete account of customer Saral from
in(select ano from account_holder where cid account table.
in (select cid from customer where
name='Saral'));
1 row deleted.