MRS Subqueries
MRS Subqueries
MRS Subqueries
SQL SUBQUERIES:
Single Row:
Sub query which returns single row output. Single row comparison
operators i.e. >,= are used with WHERE conditions.
Multiple Row:
The subquery returns more than one row. Multiple row comparison
operators like IN, ANY, ALL are used in the comparisons.
SINGLE ROW SUBQUERY EXAMPLES:
4
3
2
1
Question:
List the names of the students who have failed in the
subject ‘COMP1011’.
SINGLE QUERIES:
To identify the students who have failed in subject COMP1011
Select stu_id
From marks
Where sub_id = ‘COMP1011’
And grade < 40;
Select stu_name
From student
Where stu_id = 9292145;
NESTED QUERY (SUBQUERY):
Select stu_name
From Student
Where stu_id in ( select stu_id
From marks
Where sub_id =
‘COMP1011’
And grade < 40);
= equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
<> not equal to
IN
NOT IN
ANY
ALL
MULTIPLE ROW SUBQUERIES:
Orders(ord_no,ord_amt,advance_amt,ord_date,cust_code,agen
t_code,ord_description)
ANY: You can use the ANY operator to compare a value with any
value in a list. You must place an =, <>, >, <, <= or >= operator
before ANY in your query.
Q: Enlist if any of the agent who belongs to the country 'UK'
SELECT agent_code,agent_name,working_area,commission
FROM agents WHERE agent_code = ANY( SELECT agent_code
FROM customer WHERE cust_country='UK');
MULTIPLE ROW SUBQUERIES:
ALL:Compares a value to every value in a list or returned by a
query. Must be preceded by =, !=, >, <, <=, >=. Evaluates to TRUE
if the query returns no rows.
select ename from emp where sal > all ( select sal
from emp where job = 'SALESMAN');
GROUP BY AND HAVING CLAUSE:
GROUP BY:Groups rows based on distinct values which exists for
specified column.
Q: Retrieve the product numbers and total quantity ordered for each
product from the sales_order_details table.
Sales_order_details(p_no,qty,qty_dis,description)
select ord_num, agent_code, ord_date, ord_amount
from orders where(agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders GROUP BY agent_code);
VIEWS IN SQL
• A view is a virtual table contains rows and columns, just like a
real table. The fields in a view are fields from one or more real
tables in the database.
Syntax:
CREATE VIEW view_name AS SELECT column_name(s) FROM
table_name WHERE condition
For Example:
Create View product_vw AS select description from product
where city = ‘Mumbai’ Order by city
To Delete VIEW:
Drop View <View Name>