Practical No:-4 Aim: - Set Operators, Nested Queries, Joins, Sequences Set operators:-UNION Operation: UNION Is Used To Combine The Results of Two or
Practical No:-4 Aim: - Set Operators, Nested Queries, Joins, Sequences Set operators:-UNION Operation: UNION Is Used To Combine The Results of Two or
1 abhi
ada
2
m
The Second table,
I NAM
D E
2 adam
Chest
3
er
SELECT * FROM First INTERSECT SELECT * FROM Second;
Output:
I NAM
D E
ada
2
m
1 abhi
Nested Queries:-
In nested queries, a query is written inside a query. The
result of inner query is used in execution of outer query.
We will use STUDENT, COURSE, S_ID C_ID
STUDENT_COURSE tables for understanding nested
queries. S1 C1
S1 C3
S2 C1
STUDENT
S3 C2
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S4 C2
S1 RAM DELHI 9455123451 18
S4 C3
S2 RAMESH GURGAON 9652431543 18
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
STUDENT_COURSE
There are mainly two types of nested queries:
Independent Nested Queries: In independent nested queries,
query execution starts from innermost query to outermost queries.
The execution of inner query is independent of outer query, but the
result of inner query is used in execution of outer query. Various
operators like IN, NOT IN, ANY, ALL etc are used in writing
independent nested queries.
CREATE TABLE basket_a (id INT PRIMARY KEY, fruit VARCHAR (10
0) NOT NUL);
INSERT INTO basket_a (id, fruit)VALUES(1, 'Apple'),
INSERT INTO basket_a (id, fruit)VALUES (2, 'Orange'),
INSERT INTO basket_a (id, fruit)VALUES(3, 'Banana'),
INSERT INTO basket_a (id, fruit)VALUES (4, 'Cucumber');
CREATE TABLE basket_b (id INT PRIMARY KEY,fruit VARCHAR (100
) NOT NUL);
INSERT INTO basket_b (id, fruit)VALUES(1, 'Orange'),
INSERT INTO basket_b (id, fruit)VALUES(2, 'Apple'),
INSERT INTO basket_b (id, fruit)VALUES(3, 'Watermelon'),
INSERT INTO basket_b (id, fruit)VALUES(4, 'Pear');
Output:
id_a fruit_a id_b fruit_b
1 apple 2 apple
2 orange 1 orange
LEFT JOIN: returns all rows from the left table, even if there are no
matches in the right table.
SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b
FROM basket_a a LEFT JOIN basket_b b ON a.fruit = b.fruit;
Output:
id_ id_ fruit_
fruit_a
a b b
1 apple 2 apple
id_ id_ fruit_
fruit_a
a b b
orang
2 orange 1
e
cucumbe
4 null null
r
RIGHT JOIN: returns all rows from the right table, even if there are no
matches in the left table.
SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM b
asket_a a RIGHT JOIN basket_b b ON a.fruit = b.fruit;
Output:
id_ fruit_ id_
fruit_b
a a b
orang
2 1 orange
e
1 apple 2 apple
watermelo
null null 3
n
For Example :
CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;
Above query will create a sequence named sequence_1.Sequence will
start from 1 and will be incremented by 1 having maximum value 100.
Sequence will repeat itself from start value after exceeding 100.