0% found this document useful (0 votes)
16 views22 pages

Queries Using Group by

Uploaded by

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

Queries Using Group by

Uploaded by

tumpilliswapna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

III B.

Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB


WEEK-5
(Queries using Group By, Order By, and Having Clauses)

Week - 5(a)
(Queries using Group By)

Proble m State ment:


Demonstration of GROUP BY Keyword in SQL.

Solution:
1. Know the purpose of GROUP BY Keyword in SQL.
2. Use the GROUP BY Keyword to divide rows in a table into s maller groups

GROUP BY Clause:

A group by keyword groups a set of rows together into separate blocks(Smaller


groups) to get information for each block in a single SQL Query.
A GROUP BY Keyword has the following syntax:

SELECT COL1, AGGREAGATE OPEARTOR


FROM <TABLENAME>
GROUP BY <COL1>

Q) Find the total amount of money spent for each department in employees table
based on salary.

SQL > select department_id,sum(salary) from employees


group by department_id;

DEPARTMENT_ID SUM(S ALARY)


10 4500
20 19000
50 17500
60 19200
80 37100
90 58000
110 20300

RAGHU ENGINEERING COLLEGE 48


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

Q) Find the total number of employees present in each department.

SQL > select department_id,count(employee_id) "TOTAL emp IN


DEPARTMENT "from employees
group by department_id;

DEPARTMENT_ID TOTAL emp IN DEPARTMENT


10 1
20 2
50 5
60 3
80 4
90 3
110 2

7 rows selected.

RAGHU ENGINEERING COLLEGE 49


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 5(b)
(Queries using HAVING)

Proble m State ment:


Exhibitio n of HAVING Keyword in SQL.

Solution:
1. Learn HAVING Keyword in SQL.
2. Use the HAVING clause to restrict groups
3. When you use the HAVING clause, the Oracle server restricts groups as follows:
i. Rows are grouped.
ii. The group function is applied.
iii. Groups matching the HAVING clause are displayed.

HAVING Clause:

Having Clause is used in SQL to filter a group of rows especially to filter with
aggregate operators.

Q) Find the department_id whose average salary is less than 6500

SQL > select department_id,avg(salary) from employees


group by department_id
having avg(salary)<6500;

DEPARTMENT_ID AVG(S ALARY)


10 4500
50 3500
60 6400

RAGHU ENGINEERING COLLEGE 50


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 5(c)
(Queries using ORDER BY)
Proble m State ment:
Demonstration of ORDER BY Keyword in SQL.
Solution:
1. Know the purpose of ORDER BY Keyword in SQL.
2. Use the ORDER BY Keyword to SORT rows in a table according to a particular
column or attribute

ORDER BY Keyword :

The ORDER BY clause can be used to sort the rows. Use the ORDER BY clause to
display the rows in a specific order(Ascending order, descending order).
- ASC orders the rows in ascending order (this is the default order)
- DESC orders the rows in descending order
The ORDER BY clause comes last in the SELECT statement
Syntax
SELECT expr
FROM table
WHERE condition(s)
ORDER BY {column/ expr } [ASC|DESC];
EXAMPLE FOR ORDER BY Keyword

Q) Find the employee-id along with his first name and last name with highest
salary displayed first in descending order.
SQL > SELECT EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC

RAGHU ENGINEERING COLLEGE 51


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Q) Find the total number of employees in each department with highest number of
employees displayed first in descending order.

SQL > SELECT DEPARTMENT_ID,COUNT(EMPLOYEE_ID)


FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
ORDER BY COUNT(EMPLOYEE_ID) DESC

Q) Find the department_id whose average salary is less than 6500 with highest
average salary displayed first in descending order.

SQL > select department_id,avg(salary) from employees


group by department_id
having avg(salary)<6500
order by avg(salary) desc;

DEPARTMENT_ID AVG(S ALARY)


60 6400
10 4500
50 3500

RAGHU ENGINEERING COLLEGE 52


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
WEEK-6
(Queries on Controlling Data: Commit, Rollback, and Save point)

Week - 6(a)
(Queries using Commit)
Proble m State ment:
Usage of TCL(Transaction Control Language) Commands -COMMIT Keyword in SQL.
Solution:
1. Learn TCL(Transaction Control Language) Commands in SQL.
2. Know the purpose of COMMIT Keyword in a database.
TCL (Transaction Control Language) Keywords:

 Commit
 Rollback
 Savepoint

Commit:
Commit keyword saves the data permanently in the database. If commit state ment is not issued
after Insert keyword ,then the inserted rows or DML Statements re mains the in the database till
the user logs-in the database, Once the user logs out his session then the data inserted will be
erased off from the database.

SQL > CREATE TABLE PRODUCTS


(PRODUCT_ID NUMBER(10),
PRODUCT_NAME VARCHAR2(30),
MANUFACTURER VARCHAR2(30)
);
SQL > INSERT INTO PRODUCTS VALUES (10,'T.V','SONY');
1 row(s) inserted.
SQL > INSERT INTO PRODUCTS VALUES (20,'FRIDGE','WHIRLPOOL');
1 row(s) inserted.
SQL > INSERT INTO PRODUCTS VALUES (30,'WASHING-MACHINE','IFB');
1 row(s) inserted.
SQL > COMMIT
Commit Completed.
SQL > SELECT * FROM PRODUCTS;

RAGHU ENGINEERING COLLEGE 53


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 6(b)
(Queries using ROLLBACK)
Proble m State ment:
Usage of TCL(Transaction Control Language) Commands -ROLLBACK Keyword in SQL.
Solution:
1. Learn TCL(Transaction Control Language) Commands in SQL.
2. Know the purpose of ROLLBACK Keyword in a database.
Rollback:
Rollback undoes the data (Undo the changes made by DML) that has been
saved till the last commit statement.
Rollback takes (or restores) the database state to its previous committed state.
SQL > COMMIT
Commit Completed.
SQL> INSERT INTO PRODUCTS VALUES(40,'P.C','LENOVO');
SQL > SELECT * FROM PRODUCTS;

SQL > ROLLBACK


Rollback Completed.
SQL > SELECT * FROM PRODUCTS;

RAGHU ENGINEERING COLLEGE 54


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 6(c)
(Queries using SAVEPOINT)

Proble m State ment:


Usage of TCL(Transaction Control Language) Commands -SAVEPOINT Keyword in SQL.

Solution:
1. Learn TCL(Transaction Control Language) Commands in SQL.
2. Know the purpose of SAVEPOINT Keyword in a database.

Savepoint:

Savepoint rollbacks the database state to a Specific Point (Savepoint) that has

been already defined with Savepoint. We can define any number of save

points in a database.

SQL> INSERT INTO PRODUCTS VALUES(40,'P.C','LENOVO');

SQL> SAVEPOINT S1;

SQL > SELECT * FROM PRODUCTS;

SQL> INSERT INTO PRODUCTS VALUES(50,'MICROMAVE-

OVEN','SAMSUNG');

SQL> SAVEPOINT S2;

RAGHU ENGINEERING COLLEGE 55


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
SQL > SELECT * FROM PRODUCTS;

SQL> ROLLBACK TO S1;

SQL > SELECT * FROM PRODUCTS;

RAGHU ENGINEERING COLLEGE 56


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

WEEK -7
(Queries on Joins and Sub-Queries)
Week - 7(a)
(sub queries)

Proble m State ment:


Implement Sub queries in SQL.

Solution:

1. Learn how to write sub queries.


2.Place the inner query within the parenthesis.
3.The outer query takes the result of the inner query and uses it to display result.

Consider the following student table


SQL > select * from students order by percent desc;

ROLL_NO STUD_NAME MARKS1 MARKS2 MARKS3 MARKS4 MARKS5 TOTAL PERCENT AGE
105 Vishnu 99 98 99 100 94 490 98 22
104 Swathi 96 98 97 94 91 476 95.2 22
107 Karuna 96 98 89 90 94 467 93.4 21
103 Raju 92 94 96 92 89 463 92.6 21
102 Krishna 89 81 91 93 78 419 83.8 21
101 Kiran 77 68 78 91 87 401 80.2 19
100 ravi 73 84 56 69 90 372 74.4 19
106 Reshma 76 81 59 70 74 360 72 20

8 rows selected.
Sub Queries Examples

Q) Select the roll number and name of the student who secured fourth rank

in the class.

SQL > select roll_no,stud_name from students whe re percent in

(select max(percent) from students whe re percent <

(select max(percent) from students whe re percent <

(select max(percent) from students whe re percent <

(select max(percent) from students) ) ) );

RAGHU ENGINEERING COLLEGE 57


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

Q) Find all the employee details who earn highest salary.


SQL > select * from e mployees where salary in

(select max(salary) from e mployees);

EMPLOY FIRST_ LAST_ EM PHONE_N HIRE_ JOB_ SAL COMMISSI MANAG DEPARTM
EE_I D NAME NAME AIL UMBER DATE ID ARY ON_P CT ER_ID ENT_ID
SKI 515.123.45 17- AD_P 2400
100 Steven King 90
NG 67 JUN-87 RES 0

Q) Find all the employee details who salary is above Abel’s salary.
SQL > select * from e mployees where salary >

(select salary from e mployees where last_name='Abel');

EMPLO FIRST_ LAST_ PHONE_N HIRE_ JOB_ SAL COMMISSI MANAG DEPARTM
EMAIL
YEE_ID NAME NAME UMBER DATE ID ARY ON_P CT ER_ID ENT_ID
17-
515.123.45 AD_P 2400
100 Steven King SKING JUN- 90
67 RES 0
87
21-
Kochha NKOC 515.123.45 AD_V 1700
101 Neena SEP- 100 90
r HHA R 68 P 0
89
13-
De LDE HA 515.123.45 AD_V 1700
102 Lex JAN- 100 90
Haan AN 69 P 0
93
17-
Greenb NGRE 515.124.45 FI_M 1200
108 Nancy AUG- 101 100
erg ENBE 69 GR 0
94
01-
JRUSS 011.44.134 SA_M 1400
145 John Russell OCT- .4 100 80
EL 4.429268 AN 0
96

RAGHU ENGINEERING COLLEGE 58


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
05-
Partner KPART 011.44.134 SA_M 1350
146 Karen JAN- .3 100 80
s NER 4.467268 AN 0
97
10-
Errazuri AERR 011.44.134 SA_M 1200
147 Alberto MAR- .3 100 80
z AZUR 4.429278 AN 0
97
11-
011.44.134 SA_R 1150
168 Lisa Ozer LOZER MAR- .25 148 80
3.929268 EP 0
97
17-
Hartstei MHAR 515.123.55 MK_ 1300
201 Michael FEB- 100 20
n TS TE 55 MAN 0
96
07-
SHIGG 515.123.80 AC_ 1200
205 Shelley Higgins JUN- 101 110
INS 80 MGR 0
94

10 rows selected.

Q) Display the employee details of second highest salary.


SQL > select * from e mployees where salary in

(select max(salary) from e mployees where salary not

in (select max(salary) from employees) );

EMPLOY FIRST_ LAST_ PHONE_N HIRE_ JOB SAL COMMISSI MANAG DEPARTM
EMAIL
EE_I D NAME NAME UMBER DATE _ID ARY ON_P CT ER_ID ENT_ID
21-
Kochha NKOC 515.123.45 AD_ 1700
101 Neena SEP- 100 90
r HHA R 68 VP 0
89
De LDE HA 515.123.45 13- AD_ 1700
102 Lex 100 90
Haan AN 69 JAN-93 VP 0

RAGHU ENGINEERING COLLEGE 59


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 7(b)
(Queries on Joins -- Cross Join)

Proble m State ment:


Implement different types of joins in SQL.

Solution:

1. Learn What is a Join ?


2.Know the types of joins.
3.Implement Cross join in SQL by conside ring 2 different tables.

• Join Definition:
A join is an SQL operation which will combine or join two or more tables to retrieve data or
information from more than one table.

Different types of joins

• Cross join (Cartesian product)


• Equi joins &non-equi joins
• Outer join

Cartesian product (or) Cross Join(X)

A Cartesian product also known as cross join is an SQL operation that combines 2 relations
(tables) which produces a new relation by taking all the rows values from one table (first table)
and joins with every member (all rows) of another relation(table second).

SQL > CREATE TABLE PROJECTS


(PROJ_NO NUMBER(20) CONSTRAINT PROJECTS_PROJ_NO_PKEY PRIMARY KEY,
PROJ_FUND NUMBER(15)
);

SQL > CREATE TABLE DEPT


(DEPT_ID NUMBER(10) CONSTRAINT DEPT_DID_PKEY PRIMARY KEY,
DEPT_NAME VARCHAR2(20),
PROJ_NO NUMBER(15)
);

SQL > insert into PROJECTS values(1,10000)

RAGHU ENGINEERING COLLEGE 60


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

1 row created.

SQL > insert into PROJECTS values(2,15000)

1 row created.

SQL > insert into PROJECTS values(4,25000)


1 row created.

SQL > select * from Projects

SQL > insert into DEPT values(10,'PHYSICS',1)


1 row created.

SQL > insert into DEPT values(20,'CHEMISTRY',2)


1 row created.

SQL > insert into DEPT2 values(30,'MATHS',3)


1 row created.

SQL > SELECT * from Dept

A Cross join is defined in SQL by specifying the table names participating in the cross join after

RAGHU ENGINEERING COLLEGE 61


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
the FROM keyword in SELECT Statement.

SQL > SELECT * FROM PROJECTS,DEPT

RAGHU ENGINEERING COLLEGE 62


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 7(c)
(Queries on Joins -- Equi Join)

Proble m State ment:


Implement Equi-join in SQL.

Solution:

1. Know What is a Equi-Join ?


2.Implement Equi join in SQL by considering 2 different tables.

Equi Join

An Equi join combines 2 tables with equality ope rator(=).

When we have to join 2 tables with equality operator , the common values of attributes for the
corresponding tables are taken into conside ration and if they are matched then they are included
in the join operation

SQL > select * from Projects

SQL > SELECT * from Dept

RAGHU ENGINEERING COLLEGE 63


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
EQUI-JOIN Example

SQL > SELECT D.DEPT_ID,D.DEPT_NAME,D.PROJ_NO,P.PROJ_FUND


FROM PROJECTS P,DEPT D
WHERE P.PROJ_NO=D.PROJ_NO

RAGHU ENGINEERING COLLEGE 64


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB
Week - 7(d)
(Queries on Joins -- OUTER Joins)

Proble m State ment:


Implement different types of Outer joins in SQL.

Solution:

1. Learn What is an Oute r Join ?


2.Know the types of outer joins.
3.Implement outer joins in SQL by considering 2 different tables.

Outer Joins

• Consider two relations R & S ,Equi join or inner join is performed when tuples from R have
matching tuples in S or vice versa.

• A join is said to be an outer join, if we want to keep all the rows eithe r in R or in S or in both
R and S regardless of whether or not they have matching tuples in both relations.

• When we pe rform outer join if there are no matching rows values in outer table or other table,
they are replaced as null values.

Outer joins are classified into 3 types.


• Left outer join
• Right oute r join
• Full outer join

LEFT OUTER-JOIN Example

• Left–Outer join takes all the tuples or rows present in the left relation or table and joins with
tuples present in right table, if there is no matching tuple in right relation then adds or
places null values for all columns in right table.

RAGHU ENGINEERING COLLEGE 65


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

SQL > select * from Projects

SQL > SELECT * from Dept

SQL > SELECT d.dept_id,d.dept_name,d.proj_no,p.proj_no,p.proj_fund


from dept d LEFT OUTER JOIN projects p
ON d.proj_no=p.proj_no;

RIGHT OUTER-JOIN Example


• Right–Outer join takes all the tuples or rows present in the right relation (or table) and
joins with tuples present in left table, if there is no matching tuple s of right relation with
left relation while joining, then adds or places null values for all columns in left table
for unmatched values.

RAGHU ENGINEERING COLLEGE 66


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

SQL > select * from Projects

SQL > SELECT * from Dept

SQL > SELECT d.dept_id,d.dept_name,d.proj_no,p.proj_no,p.proj_fund


from dept d RIGHT OUTER JOIN projects p
ON d.proj_no=p.proj_no;

RAGHU ENGINEERING COLLEGE 67


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

FULL OUTER-JOIN Example


• Full–Outer join takes all the tuples or rows from both left table and right tables, if the re are
any unmatched values or rows then adds or places null values for all columns in both left
table and right table.

• Full outer join = left oute r join


+
right outer join

SQL > select * from Projects

SQL > SELECT * from Dept

SQL > SELECT d.dept_id,d.dept_name,d.proj_no,p.proj_no,p.proj_fund


from dept d FULL OUTER JOIN projects p
WHERE d.proj_no =p.proj_no

RAGHU ENGINEERING COLLEGE 68


III B.Tech CS E I Sem DATA B AS E MANGEMENT S YSTEMS LAB

RAGHU ENGINEERING COLLEGE 69

You might also like