0% found this document useful (0 votes)
22 views10 pages

Sub Queries

Concepts of sub queries in database

Uploaded by

hello world
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Sub Queries

Concepts of sub queries in database

Uploaded by

hello world
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Subqueries

Guidelines fro subqueries


Query to display max value

select max(price) from books;

select max (salary) from emp;


Query to display the name with max
value

select bookid from books


where price =(select max(price) from books);

Or
select ename from emp
where salary =(select max(salary) from emp);
query to display second highest
price

select price from books


where price <>(select max(price) from books);
note: this will display all the prices excluding the higest
but we want 2nd highest, so we will write it as
select max(price) from books
where price <>(select max(price) from books);
display bookid with the 2nd highest
price

select bookid from books


where price= (select max(price) from books
where price <>(select max(price) from books));
by using IN , IN uses a list to
compare

select bookid from books


where price IN (select max(price) from books
where price <>(select max(price) from books));
Quey to display all the dept names
Along with all emp working in that

Empi enam dep


d e t
1 Hina cs
2 Saad Hr
3 Rehan Cs
4 Maria Hr
5 Rahat It
 Here we eill use group by clause
 The depts will be grouped according to their numbers as CS has 2
emps, IT 1and Hr 2.
So the simple query will be
SELECT dept from emp GROUP BY dept;
Note: the attribute withthe GROUP BY clause is used with SELECT clause
SELECT dept, count(*) from emp GROUP BY dept;
We can also write the aggregate function as count (dept)
Query to display all dept names
emp<2

SELECT dept from emp GROUP BY dept


HAVING count (*)<2;
Now for name of emp from that dept having less then 2 no.

Select ename from emp where dept IN (SELECT dept from emp GROUP BY
dept
HAVING count (*)<2);

You might also like