0% found this document useful (0 votes)
2 views

DBMS_Unit-2 relational algebra

Relational algebra is a procedural query language that allows users to specify both what data to retrieve and how to retrieve it using operators like selection, projection, rename, union, set difference, and Cartesian product. It also includes additional operators such as joins, intersection, and division. The document provides examples and syntax for each operation, illustrating their application in querying relational databases.

Uploaded by

saiprajwal7244
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DBMS_Unit-2 relational algebra

Relational algebra is a procedural query language that allows users to specify both what data to retrieve and how to retrieve it using operators like selection, projection, rename, union, set difference, and Cartesian product. It also includes additional operators such as joins, intersection, and division. The document provides examples and syntax for each operation, illustrating their application in querying relational databases.

Uploaded by

saiprajwal7244
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

Relational Algebra

• Relational algebra is a procedural query


language.

• In Procedural Query Language, users tells what


data to be retrieved from database and how to
retrieve it.
Ex: Relational Algebra

• Where as in Non-procedural query


language, users tells what data to be retrieved
from database but doesn’t tell how to retrieve
it.
Ex: SQL
• It uses operators to perform queries. An operator
can be either unary or binary.
• The basic/fundamental operations of relational
algebra are as follows −
 Selection
 Projection
 Rename
 Union
 Set difference
 Cartesian product
1) SELECTION (σ)
• SELECT operator is denoted by sigma(σ). It is used to find
tuples(or rows) in a relation(or table) which satisfy the given
condition.

Syntax − σ<condition>(relation_name)
Where condition is prepositional logic formula which uses
operators like V, ꓥ, !, =, ≠, ≥, < , >, ≤
• Consider a relation
Employee
Eno Ename Dno
1 Raj 10
2 Ravi 20
3 Ram 10

• Ex: List the employee information of employee ID “1”.


σEno = 1 (Employee) Eno Ename Dno
1 Raj 10

• Ex: List the employee information of employee ID “1” and “3”.


σ Eno = 1 V Eno = 3(Employee) Eno Ename Dno
1 Raj 10
3 Ram 10
2) PROJECTION (∏)
• Projection operation is a relational algebra operator which takes only
one relation as an input (so it is a unary operator) and output the
attributes/columns/fields listed in the form of a relation.
Syntax: ∏<list_of_attributes> (relation_name)
• Consider a relation
Employee
Eno Ename Dno
1 Raj 10
2 Ravi 20
3 Ram 10

• List employee ids and employee name from employee relation.


∏Eno, Ename (Employee)
Eno Ename
1 Raj
2 Ravi
3 Ram
• We can combine both SELECTION and PROJECTION operation
together.
• Ex1: Find the name of employee whose employee ID is 1.
∏Ename (σ Eno = 1 (Employee)) Ename
Raj

• Ex2: List the names of employees of employee ID “1” and “3”.

∏Ename (σ Eno = 1 V Eno = 3(Employee))


Ename
Raj
Ram
3) RENAME ( )
• It is represented as . It is used to rename the output relation.

• Syntax: 1) S(R) or (B1,B2, …. Bn) (R) or S(B1, B2, …Bn) (R)

• Ex: Rename the relation employee as emp.

emp(Employee)
4) Union (U)
• This is one of the Set Operators.
• Union operator is denoted by symbol and it is used to select all
the rows (tuples) from two tables (relations).
Syntax: A U B

• For a union operation to be valid, the following conditions must


hold −
 A and B must have the same number of attributes.
 Attribute domains must be compatible.
• After Union operation all duplicate tuples are automatically
eliminated.
• Result contains first table attributes names.
• Consider two relations for doing these relational algebra operations
Course Student
Cid Name Sid Sid sname Age
C101 Aditya S901 S901 Aditya 19
C104 Aditya S901 S911 Steve 18
C106 Steve S911 S921 Paul 19
C109 Paul S921 S931 Lucy 17
C115 Lucy S931 S941 Carl 16
S951 Rick 18

Ex: ∏Name (Course) ∏sname (Student) Name


Aditya
Steve
Paul
Lucy
Carl
Rick
5) Set Difference (-)
• The result of A - B, is a relation which includes all tuples that are in A
but not in B.
Syntax: A − B
• Consider two relations for doing these relational algebra operations
Course Student
Cid Name Sid Sid sname Age
C101 Aditya S901 S901 Aditya 19
C104 Aditya S901 S911 Steve 18
C106 Steve S911 S921 Paul 19
C109 Paul S921 S931 Lucy 17
C115 Lucy S931 S941 Carl 16
S951 Rick 18

Ex: ∏sname (Student) ∏Name (Course)


Name
Carl
Rick
6) Cartesian product (X)
• For R × S, the Cartesian product operation defines a
relation that is the concatenation of every tuple of
relation R with every tuple of relation S.
Syntax: R Χ S
• Consider two relations R1 and R2:
R1 R2
A B X Y
Aa 100 Xx 99
Bb 200 Yy 11

Ex: R1 X R2
A B X Y
Aa 100 Xx 99
Aa 100 Yy 11
Bb 200 Xx 99
Bb 300 Yy 11
Additional Operators/ Derived Operators
There are mainly three types of extended/additional
operators in Relational Algebra:
• Join
• Intersection
• Divide
JOINS
• Two types
1) Inner Join
a) Natural Join
b) Theta Join
c) Equi Join
2) Outer Join
a) Left Outer Join
b) Right Outer Join
c) Full Outer Join
1a) Natural Join
• Natural join does not utilize any of the comparison operators.

• Notation: R1 R2

• Meaning: R1 R2 = A(C(R1  R2))

• Where:
– The selection C checks equality of all common attributes
– The projection eliminates the duplicate common attributes

• If there is no common attribute in both the relations, it behaves


like a cartesian product or cross product (X).
Natural Join Example

Employee
Name SSN
John 999999999
Tony 777777777

Dependents
SSN Dname
999999999 Emily
777777777 Joe

Employee Dependents =
Name, SSN, Dname(SSN=SSN(Employee x Dependents))

Name SSN Dname


John 999999999 Emily
Tony 777777777 Joe
Natural Join Questions

• Given the schemas R(A, B, C, D), S(A, C, E),


what is the schema of R S ?

• Given R(A, B, C), S(D, E), what is R S ?

• Given R(A, B), S(A, B), what is R S ?


1b) Theta Join
• Theta Join allows you to merge two tables based on the
condition represented by theta (θ).
• A join that involves a predicate
R1  R2 =   (R1  R2)

• Here  can be any condition.(Except =, it uses <,<=,>,>= and


!= relational operators in the condition)
• Note: When a theta join uses only = operator in condition,
it becomes an equi join.
• Consider two relations for doing these relational algebra operations
R1 R2
Cid Name Sid Sid sname Age
C101 Aditya 901 901 Aditya 19
C104 Aditya 901 911 Steve 18
C106 Steve 911 921 Paul 19
C109 Paul 921 931 Lucy 17
C115 Lucy 931 941 Carl 16
951 Rick 18
Ex:
Cid Name Sid Sid sname Age
C106 Steve 911 901 Aditya 19
C109 Paul 921 901 Aditya 19
C109 Paul 921 911 Steve 18
C115 Lucy 931 901 Aditya 19
C115 Lucy 931 911 Steve 18
C115 Lucy 931 921 Paul 19
1c) Equi-join
• When Theta join uses only equal to comparison operator (=), it
is said to be equijoin.

• Syntax:
R1 A=B R2

• Meaning:
R1 A=B R2 =  A=B (R1  R2)
• Consider two relations for doing these relational algebra operations
R1 R2
Cid Name Sid Sid sname Age
C101 Aditya 901 901 Aditya 19
C104 Aditya 901 911 Steve 18
C106 Steve 911 921 Paul 19
C109 Paul 921 931 Lucy 17
C115 Lucy 931 941 Carl 16
951 Rick 18
Ex:
Cid Name Sid Sid sname Age
C101 Aditya 901 901 Aditya 19
C104 Aditya 901 901 Aditya 19
C106 Steve 911 911 Steve 18
C109 Paul 921 921 Paul 19
C115 Lucy 931 931 Lucy 17
2. Outer Joins
• The result of a join (or inner join) consists of tuples formed by
combining matching tuples in the two operands or relations, an outer
join contains those tuples and additionally some tuples formed by
extending an unmatched tuple in one of the operands or relations by
"fill" values for each of the attributes of the other operand.
• An extension of the join operation(Outer Join) that avoids loss of
information
• Three outer join operators are defined:
a) Left outer join ( )
b) Right outer join ( )
c) Full outer join ( )
Left outer join (also known as left join): returns
all the rows from the table on the left even if no
matching rows have been found in the table on the
right. When no matching record found in the table
on the right, NULL is returned.
Right outer join (also known as right join):
returns all the rows from the table on the right even if no
matching rows have been found in the table on the left.
Where no matches have been found in the table on the
left, NULL is returned.
Full outer join (also known as full join):
It returns all tuples from both relations are
included in the result, irrespective of the matching
condition.
Intersection
• Intersection defines a relation consisting of a set of all
tuple that are in both A and B.
• It is a derived operator
A  B = A – (A – B)
• Consider two relations for doing these relational algebra operations
Course Student
Cid Name Sid Sid sname Age
C101 Aditya S901 S901 Aditya 19
C104 Aditya S901 S911 Steve 18
C106 Steve S911 S921 Paul 19
C109 Paul S921 S931 Lucy 17
C115 Lucy S931 S941 Carl 16
S951 Rick 18

Ex: ∏Name (Course) Ո ∏sname (Student) Name


Aditya
Steve
Paul
Lucy
Division
Division operator A÷B can be applied if and only if:

Attributes of B is proper subset of Attributes of A.


• The relation returned by division operator will have attributes =
(All attributes of A – All Attributes of B)
• The relation returned by division operator will return those
tuples from relation A which are associated to every B’s tuple.
Queries
• Consider relations
instructor ( ID, name, dept_name, salary ) and
teaches ( ID, course id, sec id, semester, year )

Q1) Find the instructor where the instructor is in the “Physics”


department.

Q2) To find all instructors with salary greater than $90,000.

Q3) To find the instructors in Physics with a salary greater than


$90,000.
Q4) To Find the id, salary, name of all instructors.

Q5) Find the name of all instructors in the Physics department.

Q6) To Find the set of all courses taught in the Fall 2009 semester,
the Spring 2010 semester, or both.

Q7) To find all the courses taught in the Fall 2009 semester but not
in Spring 2010 semester.
Answers
A1) σdept_name = "Physics"(instructor)
A2) σsalary > 90000(instructor)
A3) σdept_name = "Physics" ∧ salary > 90000(instructor)
A4) ∏ ID, name, salary (instructor)
A5) ∏ name (σ dept_name =“Physics”(instructor))
A6) ∏ course_id (σ semester =“Fall” year = 2009 (section))
∏ course_id (σ semester =“Spring” year = 2010 (section))
A7) ∏ course_id (σ semester =“Fall” year = 2009 (section)) -
∏ course_id (σ semester =“Spring” year = 2010 (section))
Relational Data Model
Data types
• CHAR(SIZE):
 It is used to store fixed length character strings.
 For fixed length strings, a shorter string is padded with blank
characters to the right. For example, if the value ‘COMPUTERS’ is for
an attribute of type CHAR (10), it is padded with one blank character
to become ‘COMPUTERS ’ if needed.
 CHAR takes a maximum size of 2000 bytes.

C O M P U T E R S
• VARCHAR2(SIZE):
 It is used to store variable length character strings.
 When we use VARCHAR2 Padded blank spaces are ignored and
only the total numbers of characters or memory needed for the string
are used(Example for the string COMPUTERS Only 9 characters are
needed).
 VARCHAR2 takes a maximum size of 4000 bytes.

C O M P U T E R S
• NUMBER
 NUMBER data types are used to store numbers of various sizes like
INTEGER and floating-point (real) numbers of various precision (FLOAT
or REAL).
 A floating point value can be specified with Number data type in
the following way.
NUMBER (Precision, Scale).
Where precision is the total number of places or digits occupied by
the floating point value and scale is the number of digits after the
decimal point.
• Date:
 It is used to store dates and time information.
• BLOB:
 It is used to store images, audio files and video files
• CLOB:
 It is used to store text files
• BFILE:
 It is used to store binary files and executable files etc.,
Data Definition Language(DDL)
• Data definition language (DDL) describes the portion of SQL
that creates, alters, and deletes database objects.
• The main commands of this category are as follows:
i) CREATE
ii) ALTER
iii) DROP
i) CREATE
• It is used to create any Oracle database objects like Table, View, Trigger,
Index, User etc.
• Syntax:
SQL> CREATE TABLE <table_name>
(
<column_name1> DATATYPE(WIDTH),
<column_name2> DATATYPE(WIDTH),

<column_nameN> DATATYPE(WIDTH)
);
Example:
• Table name: Student
• Attributes: sid, sname, gender, branch

CREATE TABLE Student


(
sid number(4),
sname varchar(10),
gender char(1),
branch varchar(5)
);
ii) ALTER
• This command is used to change the specification of the column i.e., data
type, width or constraints.
• Syntax:
ALTER TABLE <table name> KEYWORD
(
<col_name1> DATA_TYPE(WIDTH),
<col_name2> DATA_TYPE(WIDTH),
-----
<col_nameN> DATA_TYPE(WIDTH)
);
Keywords used in ALTER command are:
1)MODIFY
2)ADD
3)ENABLE/DISABLE/DROP
4)RENAME
1) MODIFY
• This keyword is used to change the specification of existing column.
• Syntax:
ALTER TABLE <table name> MODIFY
(
<col_name1> DATA_TYPE(WIDTH),
<col_name2> DATA_TYPE(WIDTH),
-----
<col_nameN> DATA_TYPE(WIDTH)
);
• To increase/decrease the size of the column.
Ex:
ALTER TABLE emp MODIFY (ename varchar2(20));
Note: It is not possible to reduce the size of the column less than the data
size value.

• Change the data type of a column.


Ex:
ALTER TABLE emp MODIFY (ename char(20));
2) ADD
• This keyword is used to add new columns to the existing table.
• We can add new constraints to the columns of table.
• Syntax:
ALTER TABLE <table name> ADD
(
<col_name1> DATA_TYPE(WIDTH),
<col_name2> DATA_TYPE(WIDTH),
-----
<col_nameN> DATA_TYPE(WIDTH)
);
• Add a new column to a table.
Ex:
ALTER TABLE emp ADD(remarks VARCHAR2(50);
• Add multiple columns to a table.
Ex:
ALTER TABLE emp ADD
(
presentAddr VARCHAR2(50),
permanentAddr VARCHAR2(50)
);
Note: To add a new column along with constraint the table must be empty.
3) ENABLE/DISABLE/DROP
• These keywords are used to change the constraint specification (or) to
change the status of constraint.
• Syntax:
ALTER TABLE <table_name>
DISABLE/ENABLE/DROP
CONSTRAINT <constraint_name>;
• DISABLE is used to make the constraint inactive.
• ENABLE  is used to make the constraint active.
• DROP  is used to remove the constraint permanently.
4) RENAME
• Change/rename the name of column.
Ex:
ALTER TABLE emp
RENAME COLUMN sal TO salary;
Changing the name of a table
• Syntax:
RENAME <old_name> TO <new_name>;
• Ex:
RENAME emp TO employee;
(OR)
ALTER TABLE emp RENAME TO employee;
iii) DROP
• It is used o drop the database object(Table, Trigger, Index…) of
ORACLE database permanently.
• Syntax:
DROP TABLE <table_name>;
• Ex:
DROP TABLE emp;
Specifying Constraints in SQL
• Constraint: Constraint is a rule or restriction.
• Quality of the data is data integrity.
a) NOT NULL b) UNIQUE
c) PRIMARY KEY d) DEFAULT
e) CHECK f) FOREIGN KEY
a) NOT NULL
• NULL is an undefined or unknown value or inapplicable value that can be
assigned to an attribute(column) of a table in a database.
• It is not equal to zero.
• It simply means the absence of a value for a column value of a table
• NOT NULL keyword does not allow the column values to have NULL.

COLUMN LEVEL TABLE LEVEL


Ex: CREATE TABLE student It is not possible in table level
(
sid VARCHAR2(20) NOT NULL
);
b) UNIQUE
• A UNIQUE keyword is used to maintain the distinct values for a
column and to restrict the duplicate values

TABLE LEVEL
COLUMN LEVEL
Ex:
Ex:
CREATE TABLE STUDENT
CREATE TABLE STUDENT
(
(
sid VARCHAR2(20),
sid VARCHAR2(20) UNIQUE
CONSTRAINT uc1 UNIQUE(sid)
);
);
c) PRIMARY KEY
• A primary key is an attribute that is used to uniquely identify the
records or rows of a relation or table.
• It is a combination of NOT NULL and UNIQUE.
PRIMARY KEY=(UNIQUE + NOT NULL)
• Only one primary key is allowed per table.
TABLE LEVEL
COLUMN LEVEL
Ex:
Ex:
CREATE TABLE STUDENT
CREATE TABLE STUDENT
(
(
sid VARCHAR2(20),
sid VARCHAR2(20) PRIMARY KEY
CONSTRAINT pk1 PRIMARY KEY(sid)
);
);
d) DEFAULT
• DEFAULT keyword is used in SQL to assign a default value for a given
attribute(column) of a relation
• The default value will be added to all new records, if no other value is
specified.

COLUMN LEVEL
Ex: TABLE LEVEL
CREATE TABLE STUDENT It is not possible in table level.
(
age NUMBER(5) DEFAULT 18
);
e) CHECK
• Check constraints are the conditions that are applied on the
attribute(column) of a relation.
COLUMN LEVEL
Ex:
CREATE TABLE employee
(
sid VARCHAR2(10) PRIMARY KEY,
salary NUMBER(10,2) CHECK(salary>0),
age NUMBER(5) CHECK(age BETWEEN 18 AND 50)
);
TABLE LEVEL
Ex:
CREATE TABLE employee
(
sid VARCHAR2(10), salary NUMBER(10,2), age NUMBER(5),
CONSTRAINT pk1 PRIMARY KEY(sid),
CONSTRAINT cck1 CHECK(salary>0),
CONSTRAINT cck2 CHECK(age BETWEEN 18 AND 50)
);
f) FOREIGN KEY
• Foreign key is generally used to establish the link between two tables
• Foreign key is always used with REFERENCES Keyword
• A foreign key is an attribute or combination of attributes present in
one relation that refers to another attribute or combination of
attributes usually the primary key in another relation.
Referencing Table

Referenced Table
20 CSE VIZAG
30 ECE GUNTUR
COLUMN LEVEL
Ex:
CREATE TABLE employee
(
ssn NUMBER(4) PRIMARY KEY,
ename VARCHAR2(10) NOT NULL,
salary NUMBER(10,2) CHECK(salary>0),
deptno NUMBER(2) REFERENCES department(deptno),
age NUMBER(3) CHECK(age BETWEEN 18 AND 50)
);

TABLE LEVEL
Ex:
CREATE TABLE employee
(
ssn NUMBER(4), ename VARCHAR2(10), salary NUMBER(10,2),
deptno NUMBER(2), age NUMBER(3),
CONSTRAINT pk1 PRIMARY KEY(ssn),
CONSTRAINT cck1 CHECK(salary>0),
CONSTRAINT fc1 FOREIGN KEY(deptno) REFERENCES department(deptno),
CONSTRAINT cck2 CHECK(age BETWEEN 18 AND 50)
);
Maintaining referential integrity with ON
DELETE CASCADE option:
• If we use ON DELETE CASCADE option, ORACLE permits deletions of
referenced key values in the parent table and automatically deletes
dependent rows in the child table to maintain referential integrity.

TABLE LEVEL
Ex:
CREATE TABLE employee
(
ssn NUMBER(4),
deptno NUMBER(2), age NUMBER(3),
CONSTRAINT pk1 PRIMARY KEY(ssn),
CONSTRAINT fc1 FOREIGN KEY(deptno) REFERENCES department(deptno) ON DELETE CASCADE
);
Maintaining referential integrity with ON
UPDATE CASCADE option:
• If we use ON UPDATE CASCADE option, ORACLE permits updation of
referenced key values in the parent table and automatically updates
dependent rows in the child table to maintain referential integrity.

TABLE LEVEL
Ex:
CREATE TABLE employee
(
ssn NUMBER(4),
deptno NUMBER(2), age NUMBER(3),
CONSTRAINT pk1 PRIMARY KEY(ssn),
CONSTRAINT fc1 FOREIGN KEY(deptno) REFERENCES department(deptno) ON DELETE CASCADE
);
Basic Retrieval Queries in SQL, INSERT, DELETE, and
UPDATE Statements in SQL / DML
• DML commands are used for adding, retrieving, deleting and
modifying data in a database.
• The main commands of this category are as follows:
i. INSERT
ii. DELETE
iii. UPDATE
iv. SELECT
i) INSERT
• To insert rows of information into DB table.
• Syntax:
INSERT INTO <table_name>
[(<col1>,<col2>,..)] VALUES (<val1>,<val2>,..>)
• Ex:
1) INSERT INTO emp(empno,ename,sal,deptno, hiredate) VALUES(1, ’kiran’,10000, 123, ’12-
jun-20’);
(OR)
2) INSERT INTO emp VALUES(1, ’kiran’,10000, 123, ’12-jun-20’);
(OR)
3) INSERT INTO emp(empno,ename,sal,deptno, hiredate)
VALUES(&empno,’&ename’,&sal,&deptno, ‘&hiredate’);
ii) DELETE
• The DELETE statement is used to delete existing records in a table.
• DELETE Syntax:
DELETE FROM table_name WHERE condition;
• Ex: Delete student data whose sid is 102.
DELETE FROM student WHERE sid=102;

• Delete All Records:


It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
Syntax:
DELETE FROM table_name
iii) UPDATE
• The UPDATE statement is used to modify the existing records in a
table.
• UPDATE Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
• Ex:
UPDATE student SET contact=9797979797 WHERE sid=102;
iv) SELECT
• It is used to retrieve the data from one or more relations.
• Basic Syntax:
SELECT [DISTINCT] <col1>,<col2>…
FROM <tab1>,<tab2>…
WHERE condition;
• Here, col1, col2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use * instead
of list of columns.
• DISTINCT keyword is used to return only distinct (different) values.
• FROM clause describes list tables.
• WHERE clause is used to extract only those records that fulfill a specified
condition.
Consider a relation emp:
Examples:
1) Display the details of employees.
SELECT *FROM emp;
2) Display empno, ename for all employees.
SELECT empno, ename from emp;
• Note: Column alias is an alternative name during data display process.
3) Display empno, ename with more descriptive labels.
SELECT empno as Employee_No, ename as Employee_Name
FROM emp;
4) Display all the unique deptno of the employees.
SELECT DISTINCT deptno FROM emp;
5) Display all the unique deptno with job combinations.
SELECT DISTINCT deptno, job FROM emp;
6) Display the employees joined after 1980.
SELECT *FROM emp WHERE hiredate>=’01-jan-1981’;
7) Display the emps joined after the 3rd quarter of 1981.
SELECT *FROM emp WHERE hiredate>’30-sep-1981’;
8) Display the emps having an experience not less than 39 years.
SELECT *FROM emp WHERE (SYSDATE-hiredate)/365>=39;
Operators
There are 5 operators in Oracle.
a) Arithmetic Operators: +, -, *, /

b) Relational Operators: =, !=, <, <=, >, >=,


IN, NOT IN,
BETWEEN, NOT BETWEEN,
LIKE, NOT LIKE,
IS NULL, IS NOT NULL

c) Logical Operators: AND, OR, NOT

d) Set operators: UNION, UNION ALL,


INTERSECT, MINUS

e) Boolean operators: EXISTS, NOT EXISTS


Note: Mostly we use these operators in WHERE clause.
ORDER BY
• The default sorting order is ascending order.
• Syntax:
SELECT [DISTINCT] <col1>,<col2>…
FROM <tab1>,<tab2>,….
WHERE condition
ORDER BY <col> [ASC/DESC], <col> [ASC/DESC]…;

9) Display the details of all employees in descending order of their salary.


SELECT * FROM emp
ORDER BY sal DESC;
10) Display the details of employees in descending order of experience.
SELECT * FROM emp
ORDER BY hiredate;
11) Display the deptno, job, empno, ename, sal of all employees in descending
order of deptno, descending order of job.
SELECT deptno, job, empno, ename, sal
FROM emp
ORDER BY deptno DESC, job DESC;
(OR)
SELECT deptno, job, empno, ename, sal
FROM emp
ORDER BY 1 DESC, 2 DESC;
// Here “1” represents first attribute (deptno),
// “2” represents second attribute(job) in SELECT LIST.

Note: During sorting process ORACLE will consider NULL values as the biggest
value.
It will place NULL at first in descending order.
It will place NULL at last in ascending order.
12) Display empno, ename, sal, daily sal and annual sal of all employees in
descending order of annual salary.
SELECT empno, ename, sal, sal/30 as d_sal, sal*12 as a_sal
FROM emp
ORDER BY a_sal desc;

13) Display empno, ename, sal, sysdate, hiredate and experience of all the
employees in descending order of experience.
SELECT empno, ename, sal, SYSDATE Today, hiredate doj, SYSDATE-hiredate exp
FROM emp
ORDER BY exp DESC;
Note: Here SYSDATE-hiredate gives number of days.

14) Display all the unique salaries of all the clerks in ascending order.
SELECT DISTINCT sal FROM emp
WHERE job=‘clerk’
ORDER BY sal;
IN operator
• It is used to define a list. Always the elements of list are enclosed
within the parenthesis and separated by commas.

15) Display the details of all clerks and managers.


SELECT *FROM emp WHERE job IN (‘CLERK’, ‘MANAGER’);
(OR)
SELECT *FROM emp WHERE job=‘CLERK’ OR job=‘MANAGER’;
BETWEEN Operator
• The BETWEEN operator selects values within a given range.
• The values can be numbers, text, or dates.
• The BETWEEN operator is inclusive: begin and end values are included.
• Syntax: SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

16) Display all the employees whose salaries lies between 10000 and 20000
SELECT *FROM emp
WHERE sal BETWEEN 10000 AND 20000;
Questions
17) Write a query to list all the employees joined in year 1981.

18) Display all the employees in descending order of their salaries having an
experience which is ranging from 25yrs up to 39yrs.
Solutions
Ans-17) SELECT *FROM emp
WHERE hiredate BETWEEN ‘01-JAN-1981’ AND ‘31-DEC-1981’;
OR
SELECT *FROM emp
WHERE hiredate>=‘01-JAN-1981’ AND hiredate<=‘31-DEC-1981’;

Ans-18) SELECT *FROM emp


WHERE (sysdate-hiredate)/365 BETWEEN 15 AND 30
ORDER BY sal DESC;
LIKE
• The LIKE command is used in a WHERE clause to search for a specified
pattern in a column.
• You can use two wildcards with LIKE:
‘%’  Represents zero, one, or multiple characters
‘_’  Represents a single character.
• Consider a relation “emp”
Questions
19) Display all the 4 character named employees.
20) Display all the 5 character named employees starting with ‘S’.
21) Display all the employees whose name starting with ‘C’.
22) Display all the employees whose name ending with ‘s’.
23) Display all the employees joined in month of ‘APRIL’.
24) List the details of all employees whose ename is starting with ’A’ and ending
with ‘s’ and there should be ‘a’ in between.
25) Display all the employees joined in the month starting with char ‘A’.
26) Display employees joined in first 9 days of any month.
Solutions
Ans-19) SELECT *FROM emp WHERE ename LIKE ‘_ _ _ _’;
Ans-20) SELECT *FROM emp WHERE ename LIKE ‘S_ _ _ _’;
Ans-21) SELECT *FROM emp WHERE ename LIKE ‘C%’;
Ans-22) SELECT *FROM emp WHERE ename LIKE ‘%s’;
Ans-23) SELECT *FROM emp WHERE hiredate LIKE ‘%APR%’;
Ans-24) SELECT *FROM emp WHERE ename LIKE ‘A%a%s’;
Ans-25) SELECT *FROM emp WHERE hiredate LIKE ‘_ _ _A%’;
Ans-26) SELECT *FROM emp WHERE hiredate LIKE ‘0%’;
NULL Values
• A field with a NULL value is a field with NO VALUE/
UNKNOWN value.
• If a field in a table is optional, it is possible to insert a
new record or update a record without adding a value
to this field. Then, the field will be saved with a NULL
value.
How to Test for NULL Values?
• It is not possible to test for NULL values with comparison operators, such as =,
<, or <>.
• We will have to use the IS NULL and IS NOT NULL operators instead.
• IS NULL  is used to match the NULL values.
• IS NOT NULL  is used to match the NOT NULL values.

27) Display the details of all the employees working under some manager.
SELECT *FROM emp
WHERE mgr IS NOT NULL;
28) Display all the employees receiving no commission.
SELECT *FROM emp
WHERE comm IS NULL;
Exercise Problem
Q29) Display all the clerks working for department number 10 and
20 with salary more than 900.
Ans-29)
SELECT *FROM emp
WHERE job=‘CLERK’ AND deptno IN(10,20) AND sal>900
Nested queries
• A sub-query or inner query or a nested query is a query within another query and
embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query as a condition
to further restrict the data to be retrieved.
• Syntax: Subqueries with the SELECT Statement:

SELECT col1 [, col2, … ]


FROM table1 [, table2,.. ]
WHERE column_name OPERATOR
(SELECT col1 [, col2, … ]
FROM table1 [, table2,.. ] [WHERE condition])

• OPERATOR can be =, <, >, >=, <=, IN, BETWEEN, etc.


• Consider a relation “emp”
• Find the details of employees who are getting maximum salary.
SELECT * FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp) ;
• Find names of employee drawing the salary greater then the salary of
“Jones”.
SELECT ename
FROM emp
WHERE sal>(SELECT sal
FROM emp
WHERE ename=‘Jones’);
• In case of multiple “Jones”, the above query fails, in that
case better to use “>ALL”.
• Find name of employee drawing the salary greater then the salary of
every “CLERK”.
SELECT ename
FROM emp
WHERE sal>ALL( SELECT sal
FROM emp
WHERE job=‘Clerk’);
• Find name of employee drawing the salary is equal to the salary of
“Jones”.
SELECT ename
FROM emp
WHERE sal=(SELECT sal
FROM emp
WHERE ename=‘Jones’);
• In case of multiple “Jones”, the above query fails, in that
case better to use “=ANY”.
• Find name of employee drawing the salary equal to the salary of any
“CLERK”.
SELECT ename
FROM emp
WHERE sal=ANY( SELECT sal
FROM emp
WHERE job=‘Clerk’);
NOTE: “=ANY” working is same as “IN”, similarly
“<>ALL” is same as “NOT IN”.
Correlated SubQuery
• If the execution of inner query is depends on the outer query then such type of query is
called correlated sub-query.
• Ex: Find the names of employees who are working in “Research” department.
Normal Sub-query:
SELECT ename FROM emp
WHERE deptno = (SELECT deptno FROM dept
WHERE dname='Research’);
Correlated Sub-query:
SELECT ename FROM emp
WHERE EXISTS (SELECT deptno FROM dept
WHERE emp.deptno = dept.deptno
AND dname='Research');
• Correlated subqueries are used for row-by-row processing. Each
subquery is executed once for every row of the outer query.
SET Operations
• SET operators are special type of operators which are used to combine the
result of two queries.
• Operators covered under SET operators are:
• UNION
• UNION ALL
• INTERSECT
• MINUS
• There are certain rules which must be followed to perform operations
using SET operators in SQL. Rules are as follows:
• The number and order of columns must be the same.
• Data types must be compatible.
Consider two relations employee and student
1. UNION:
• UNION will be used to combine the result of two select statements.
• Duplicate rows will be eliminated from the results obtained after performing the
UNION operation.
Query:
SELECT empname FROM employee UNION SELECT sname FROM student;
2.UNION ALL:
• This operator combines all the records from both the queries.
• Duplicate rows will be not be eliminated from the results obtained after
performing the UNION ALL operation.
Query:
SELECT empname FROM employee UNION ALL SELECT sname FROM student;
3. INTERSECT:
It is used to combine two SELECT statements, but it only returns the records
which are common from both SELECT statements.

Query:
SELECT empname FROM employee INTERSECT SELECT sname FROM student;
4. MINUS (SET DIFFERENCE):
It displays the rows which are present in the first query but absent in the second
query with no duplicates.

Query:
select empname from employee minus select sname from student;
Aggregate Functions or Group Functions
1) MAX(<col_name>): This function is used to find the maximum value of the
column in the given set of rows.
2) MIN(<col_name>): This function is used to find the minimum value of the
column in the given set of rows.
3) SUM(<col_name>): This function is used to find the sum of the column values
in the given set of rows.
4) AVG(<col_name>): This function is used to find the average of the column
values in the given set of rows.
5) COUNT(<col_name>): This function is used to count the number of rows in the
given set.
GROUP BY and HAVING
• GROUP BY clause is used to split the data of tables (or) table into
multiple groups based on one (or) more column based value.
• GROUP BY is used to get the summarised information of multiple
groups based on one or more attributes.
• The GROUP BY statement is often used with aggregate functions
(COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or
more columns.
• HAVING is used to check the conditions of GROUP BY.
• The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Rules:
1) Th columns those are specified in GROUP BY clause only allowed in SELECT list.
2) Any column with any group function can also be used though it is not specified
in GROUP BY.
3) GROUP BY will split the table into multiple groups based on column names.
Consider an EMP relation:
Q1) Find the sum of salaries of all departments.

Q2) Find the sum of salaries of each departments.

Q3) Find maximum and minimum salary, total employees, sum and
average salaries of employees in each department individually.
Q4) Display the number of employees belong to each Job group.

Q5) Display the departments where at least 5 employees are working.


Q6) Display the departments where atleast two clerks are working.

You might also like