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

Unit-2 Final

RDBMS-Oracle notes1
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 views65 pages

Unit-2 Final

RDBMS-Oracle notes1
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/ 65

For more references Please Visit :

https://easy2learncode.in

RDBMS Using Oracle


unit-2
(Unit-2: Managing Tables and Data, Data
Control And Transaction Control Command)
- Sojitra Dhruvi H.

22
RDBMS Using Oracle unit-2

Syllabus:-
 Creating , Altering & Dropping tables

Create:-
 Syntax :
 Create table table_name
(
colums1 datatype(size),
colums2 datatype (soze),
… … … )
 Ex.: create table student (roll number(5),name
varchar2(10),salary number(10))

ALTER :-
 Syntax :
 Alter table table_name ADD(column_name)

 Ex. alter table student add (mobile


number(10))
DROP :-
 Remove fully table.
 Syntax :
 Drop table table_name

https://easy2learncode.in Page 2
RDBMS Using Oracle unit-2

 Ex.: drop table student

 Data Manipulation Command like Insert,


update, delete

INSERT :-
Syntax :
Insert into table_name values
( val_1,val_2,……)

Ex.: insert into student values(1,'angel')

UPDATE :-
Syntax:
Update table_name SET columsname where
columename.

Ex.: UPDATE emp set id=10 where city='jnd'

DELETE :-
Syntax :
Delete from table_name where record_name

Ex.: delete from student where roll=2

Truncate:-
Remove table record
Syntax :
Truncate table table_name

Ex.: truncate table emp

https://easy2learncode.in Page 3
RDBMS Using Oracle unit-2

RENAME:-

Newname of Tablename
Syntax :
Rename old table_name to new table_name

Ex.: remane student to stud;

SQL QUERY

 To display all row and all column


Ex. select *from student;

 To display selected column and all row


Ex. select id,name,city from student

 To display all column and selected row


Ex. select *from student where id >=5
Ex. select *from student where name like’M%’
 To display selected column and selected rows
Ex.Select name,city,mobile from student where
pincode=365440

 To table discribe
Ex. Desc student.

 To specific row update


Ex.update student set city=‘jnd’,
pincode=‘365440’ where rollno=2
https://easy2learncode.in Page 4
RDBMS Using Oracle unit-2

 To adding new column


Ex.alter table student add(mobile number(15))

 To modify existing column


Ex.alter table student modify(mobile
varchar2(15))

 To deleting a column
Ex. alter table student drop column salary

ARITHMETIC OPERATOR
 They are arithmetic operator are +, -, and *.

 Addition:
Ex. select name,salary +5000 from student where
id=1

 Substraction:
Ex. select name,salary -2000 from student where
id=1

 Multiplication:
Ex. select name,salary *500 from student where
id=2

LOGICAL OPERATORS
They are logical operator are AND,OR,NOT.

 AND:
Ex. select *from student where name='aaa' AND
salary=2000
https://easy2learncode.in Page 5
RDBMS Using Oracle unit-2

 OR:
Ex. select *from student where id=2 OR
salary=2000

 NOT:
Ex. select *from student where id NOT LIKE 2

IN (મ ાં હોવ ાં ) / NOT IN OPERATOR


 IN :
Ex. select *from student where id IN(1,2,6,4)

 NOT IN :
Ex. select *from student where name NOT
IN('aaa','bbb','ccc')

BETWEEN OPERATOR

 Ex. select *from student where name between 'aaa' and 'fff‘
 Ex. select *from student where id between 1 and 5

 Built in functions
Function use:
-performing arithmetic and general
calculation on data,
-converting or transformation data,
-modifying individual data,
https://easy2learncode.in Page 6
RDBMS Using Oracle unit-2

-manipulating a group of rows, and


formatting columns.
 -:: CHARACTER FUNCTION /STRING
FUNCTION ::-

(1) lower()
select lower ('DHANAK COLLEGE')
"lowercase" from dual;
o/p:dhanak college

(2) upper()
select upper('dhanak college')"uppercase"
from dual;
o/p:DHANAK COLLEGE

(3)INITCAP()
select INITCAP ('oracle database') "capital"
from dual;
o/p:Oracle Database

https://easy2learncode.in Page 7
RDBMS Using Oracle unit-2

(4)SUBSTR()
select SUBSTR ('SubString',3,5) "substring"
from dual;
o/p:bStri

(5)LPAD()
select LPAD ('Program',10,'*') "LPAD" from
dual;
o/p:***Program

(6)RPAD()
select RPAD ('Program',11,'*') "RPAD" from
dual;
o/p:Program****

(7)LTRIM()

https://easy2learncode.in Page 8
RDBMS Using Oracle unit-2

select LTRIM ('NISHA','N') "LTRIM" from


dual;
o/p:ISHA

(8)RTRIM()
select RTRIM ('PROGRAM','M') "RTRIM"
from dual;
o/p:PROGRA

(9)Ascii()
It return a numeric value base on given
character.
select ascii('D') from dual; o/p=68
select ascii('h') from dual; o/p=104

(10)Length()
select length ('Dhanak College') from dual;

https://easy2learncode.in Page 9
RDBMS Using Oracle unit-2

o/p=14

(11)INSTR()
It find a position of character in a string,
finding start to bigining of a string.
select INSTR ('This a Program' , 'a') from
dual;
o/p:6

1. (12) CHR()
Return the character based on the number
code.
Syntax : CHR(n)
Example: select CHR(67)||CHR(65)||CHR(84)
FROM DUAL;
OUTPUT : CAT

(13) CONCAT()

https://easy2learncode.in Page 10
RDBMS Using Oracle unit-2

The Oracle CONCAT() function returns the


result (a string) of concatenating two string
values. This function is equivalent to the
concatenation operator (||).
SYNTAX : CONCAT(char1, char2)
EXAMPLE: select CONCAT('DHANAK
','COLLEGE')from dual;

select ('DHANAK '||'COLLEGE')from dual;


O/P : DHANAK COLLEGE

(14) REPLACE()
 REPLACES a sequence of characters in a
string with another set of characters.
 Syntax:
 REPLACE(char, search_string [,
replacement_string ] )
 Ex., select replace('DHANAK ','K','C')from
dual;

https://easy2learncode.in Page 11
RDBMS Using Oracle unit-2

(15) SOUNDEX()
 This Function Is Used To Get Soundex
Value, It Returns A Character String
Containing The Phonetic Representation Of
Char.
 SYNTAX : SOUNDEX(CHAR)
CHAR :A String Whose You Retrive
Soundex.
Ex., select SOUNDEX('DHANAK ')from dual;
(16) TRIM
The Oracle TRIM function is used to remove all
leading or trailing characters (or both) from a
character string.
Syntax:
TRIM([ { { LEADING | TRAILING | BOTH }
[ trim_character ]
| trim_character
}
FROM
]
trim_source
)
https://easy2learncode.in Page 12
RDBMS Using Oracle unit-2

EX., select TRIM(TRAILING 'M' from


'MADAM')from dual;
 GROUP Function OR AGGREGATE Function
(1)COUNT()
select count (*) from employee;
o/p:5

(2)MIN()
select MIN(salary) from employee;
o/p:20000

(3)MAX()
https://easy2learncode.in Page 13
RDBMS Using Oracle unit-2

select MAX(salary) from employee;


o/p:30000

(4)SUM()
select sum(salary) from employee
where empno=1;
select sum(salary) from employee;
o/p: Total salary display

(5)AVG()
select AVG(salary) from employee;
o/p: avg to the table

-:: NUMERIC FUNCTION ::-

(1)ABS()
select ABS(-15.11) "absolute" from dual;

o/p:15.11

(2)power()
select power(15,2) "raised" from dual;
o/p:225

(3)round()

https://easy2learncode.in Page 14
RDBMS Using Oracle unit-2

select round(15.22222,3) "round" from


dual;
o/p:15.222

(4)SQRT()
select sqrt(225) "squre root" from dual;
o/p:15

(5)MOD()
select mod(15,7) "mod" from dual;
o/p:1

(6)FLOOR()
select FLOOR(24.8) "floor" from dual;
o/p:24

(7)CEIL()
select ceil(24.8) from dual;
o/p:25

(8)exp()
select exp(1) from dual;
o/p:2.718

(9)GREATEST()

https://easy2learncode.in Page 15
RDBMS Using Oracle unit-2

select greatest(10,10,1,3,44,55,0)from
dual;
o/p:55

(10)LEAST()
select least(10,10,1,3,44,55,0)from dual;
o/p:0

(11) cos()
Cos returns the cosine of any number.
Syntax: cos(n);
Select cos(180*3.14159265359/180)”
cosine of 180 degrees” from dual;

(12) decode()

syntax:
DECODE(expression , search_value , result ,
default[optional])

Ex., SELECT name,DECODE(roll, 1,


'Excellent Student','Grace Pass Student')
"result" FROM student;

https://easy2learncode.in Page 16
RDBMS Using Oracle unit-2

Ex., SELECT name, DECODE(roll, 1, 'SBI',2,


'ICICI', 3, 'Dena','No Bank Selected') As
Results FROM student;

(13) log
Log returns the logarithm, base n2 of n1.
Syntax: LOG(n2,n1);
Ex., select LOG(10,100) “log base 10 of 100”
from dual;

(14) log10()
Returns the base-10 logarithm of X.
Syntax: LOG10(X);

Ex.2, SELECT LOG10(100) FROM DUAL;


o/p:2

(15) max
MAX( expression );
Ex., select max(salary) from employee;

(16) min
MIN( expression );
Ex., select MIN(salary) from employee;

(17) sign()
https://easy2learncode.in Page 17
RDBMS Using Oracle unit-2

This function is used to return the sign of a


given number.
The function returns:
1 when the value of the argument is positive
-1 when the value of the argument is
negative
0 when the value of the argument is 0

For binary floating-point numbers


(BINARY_FLOAT and BINARY_DOUBLE),
this function returns the sign bit of the
number. The sign bit is:
-1 if n<0
+1 if n>=0 or n=NaN

Syntax:
SIGN(n)
Ex., SELECT SIGN(-145), SIGN(0),
SIGN(145) FROM dual;

o/p :

https://easy2learncode.in Page 18
RDBMS Using Oracle unit-2

(18) sin()
SIN returns the sine of n.
Syntax: SIN(n);
Ex., select SIN(30*3.14159265359/180)
"sine of 30 degree" FROM dual;
o/p: 0.5000

(20) sinh()
SINH returns the hyperbolic sine of n.
Syntax: SINH(n);
Ex., select SINH(1) "hyperbolic sine of 1"
from dual;
o/p: 1.17520119

(21) tan()
Returns the tangent of a number
Syntax : TAN(numeric expression)
Ex., select TAN(0.52) from dual;
o/p., 0.572561

(22) trunk()
The TRUNC(number) function returns n1
truncated to n2 decimal places.
If n2 is omitted, then n1 is truncated to 0
places. N2 can be negative to truncate(make
zero) n2 digits left of the decimal point.

https://easy2learncode.in Page 19
RDBMS Using Oracle unit-2

Syntax : TRUNC(n1,n2);
Ex., select TRUNC(15.79,1) "TRUNCATE"
FROM DUAL;
o/p : 15.7

-:: DATE FUNCTION ::-

(1)to_date()
 It is used to convert a string to a date
formate.
 Syntax:
 TO_DATE ( string, format )
Example.
 Example:
 TO_DATE ('062619', 'MMDDYY')
 Output:
date value of June 26, 2019
select to_date(sysdate,'dd-mm-yy') from dual;
o/p: System Date return

(2)add_months()
 This function returns a date with a given
number of months added (date plus integer
months)

https://easy2learncode.in Page 20
RDBMS Using Oracle unit-2

 The return type is always DATE, regardless


of the datatype of date.

Ex., select add_months(sysdate,1)from dual;


o/p:06-OCT-15
Ex., select add_months('05-may-20',1)from
dual;
o/p: 05-jun-20

(3)last_day()
 THIS function returns the last day of the
month that contains a date. The return type
is always DATE.

https://easy2learncode.in Page 21
RDBMS Using Oracle unit-2

Ex., select last_day(sysdate)from dual;


o/p:31-AUG-15

(4)months_between()
 This function is used to get the number of
months between dates (date1, date2).

https://easy2learncode.in Page 22
RDBMS Using Oracle unit-2

Ex., select months_between('31-dec-


2015','31-dec-2017')from dual;
o/p:- -24

(5)next_day()
 NEXT_DAY() returns the date of the first
weekday that is later than the date.

https://easy2learncode.in Page 23
RDBMS Using Oracle unit-2

Ex.,
select next_day(sysdate,'sunday')from dual;
o/p:09-AUG-15
select next_day('22-august-20','wednesday')
from dual;
o/p : 26-aug-20

(6)round()
 The ROUND() function is used to get the
date rounded to the unit specified by the
format model. It operates according to the
rules of the Gregorian calendar.

https://easy2learncode.in Page 24
RDBMS Using Oracle unit-2

Ex.,
select round(sysdate,'Month')from dual;
select round(sysdate,'year')from dual;

select extract(year from sysdate)from dual;


o/p:2022

select extract(month from sysdate)from


dual; o/p:8

(7)sysdate()
 The SYSDATE() function is used to get the
current date for the operating system.
 There have no parameter.
https://easy2learncode.in Page 25
RDBMS Using Oracle unit-2

 Syntax: SYSDATE()
 select SYSDATE from dual;

(8)systimestamp()
The SYSTIMESTAMP() function is used to get
the system date, including fractional seconds
and time zone, of the system.
 Syntax:
 SYSTIMESTAMP()
Ex., select systimestamp from dual;
0/p:07-AUG-15 03.01.27.541000 PM
+05:30

(9)To_date()
It is used to convert a string to a date formate.
Syntax:
TO_DATE ( string, format_mask)
Example:
TO_DATE ('062619', 'MMDDYY')
Output:
date value of June 26, 2019

(10)trunc (date)
The TRUNC (date) function is used to get the date with the
time portion of the day truncated to a specific unit of
measure. It operates according to the rules of the
Gregorian calendar.

https://easy2learncode.in Page 26
RDBMS Using Oracle unit-2

Syntax:
TRUNC(date [, fmt ])
Parameters:
Name Description
date The date to truncate.
The unit of measure for truncating. If fmt is not
fmt
present, then the date is truncated to the
(Optional)
nearest/present day.

Example : select TRUNC(sysdate,'year') from dual;

Example :select TRUNC(to_date('01-06-20','dd-


mm-yy'),'year') from dual;

(11)to_char
The TO_CHAR( ) function is used to convert a datetime datatype to a
value of VARCHAR2 datatype in a specified format.
https://easy2learncode.in Page 27
RDBMS Using Oracle unit-2

Syntax:
TO_CHAR( datetime , fmt )

Parameters:

Name Description
datetime A date that will be converted to a string.
The format that will be used to convert the value to
a string.

fmt If no format (fmt) is present, then date is converted


(Optional) to a VARCHAR2 value as follows :

 DATE values are converted to values in the


default date format.

Example : select to_char(sysdate,'dd-mm-yyyy hh-mi-ss')


from dual;
o/p: 20-08-2022 11-45-24

Different type of constraints and applying of


constration

 Constraints means we are applying certain


conditions on the database.
 It means set of rules to apply in database to give
accurate data by user.

https://easy2learncode.in Page 28
RDBMS Using Oracle unit-2

constraints

I/O Business rule


constraints constraints

PRIMARY KEY FOREIGN KEY NOT NULL UNIQUE KEY CHECK DEFAULT

Constraints are:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT

1. NOT NULL
o NULL means empty, i.e., the value is not available.
o Whenever a table's column is declared as NOT NULL, then
the value for that column cannot be empty for any of the
table's records.
o There must exist a value in the column to which the NOT
NULL constraint is applied.
https://easy2learncode.in Page 29
RDBMS Using Oracle unit-2

NOTE: NULL does not mean zero. NULL means empty column,
not even zero.

Syntax to apply the NOT NULL constraint during table


creation:

1. CREATE TABLE TableName(ColumnName1 datatype NOT NULL


, ColumnName2 datatype,…., ColumnName N datatype);

Create a student table and apply a NOT NULL constraint on one


of the table's column while creating a table.

CREATE TABLE student1(StudentID int NOT NULL,


Student_FirstName VARCHAR(20), Student_LastName
VARCHAR(20), Student_PhoneNumber number(10),
Student_Email_ID VARCHAR(40));

1. To verify that the not null constraint is applied to the table's


column , execute the following query:

2. mysql> DESC student;

3. insert into stud


values('','xyz','patel',1231221212,'[email protected]');// it make an
error code.

4. insert into student1 values(1,'andy','rubin',1234567891,'');


//success.

https://easy2learncode.in Page 30
RDBMS Using Oracle unit-2

5. select * from student1;

2. UNIQUE
o Duplicate values are not allowed in the columns to which
the UNIQUE constraint is applied.
o The column with the unique constraint will always contain
a unique value.
o This constraint can be applied to one or more than one
column of a table, which means more than one unique
constraint can exist on a single table.

Syntax to apply the UNIQUE constraint on a single column:

1. CREATE TABLE TableName (ColumnName1 datatype UNIQUE,


ColumnName2 datatype,…., ColumnNameN datatype);
Create a student table and apply a UNIQUE constraint on one
of the table's column while creating a table.

Ex.,
CREATE TABLE student(StudentID INT UNIQUE, Student_First
Name VARCHAR(20), Student_LastName VARCHAR(20), Stude
nt_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(
40));

If alredy table exist then we would alter specific column which


you want to apply specific constrain is applying.

https://easy2learncode.in Page 31
RDBMS Using Oracle unit-2

Ex.,
alter table student1 modify(StudentID int UNIQUE);
alter table student1 modify(Student_PhoneNumber
number(10) UNIQUE);
Ex. insert into student1
values('','andy','rubin',1234567891,'[email protected]');//error

insert into student1 values(1,'andy','rubin',1234567891,'');//error

insert into student1 values(2,'andy','rubin',1234567891,'');


//error
insert into student1 values(2,'andy','rubin','','');
OR
insert into student1
values(3,'tejas','patel','1212121212','[email protected]');
//success.

3. PRIMARY KEY
o PRIMARY KEY Constraint is a combination of NOT NULL
and Unique constraints.
o NOT NULL constraint and a UNIQUE constraint together
forms a PRIMARY constraint.
o The column to which we have applied the primary
constraint will always contain a unique value and will not
allow null values.

Syntax of primary key constraint during table creation:

https://easy2learncode.in Page 32
RDBMS Using Oracle unit-2

1. CREATE TABLE TableName (ColumnName1 datatype PRIMAR


Y KEY, ColumnName2 datatype,…., ColumnNameN datatype);

Example:

Create a student table and apply the PRIMARY KEY constraint


while creating a table.

CREATE TABLE student(StudentID INT PRIMARY KEY, Student


_FirstName VARCHAR(20), Student_LastName VARCHAR(20), S
tudent_PhoneNumber VARCHAR(20), Student_Email_ID VARC
HAR(40));

To verify that the primary key constraint is applied to the table's


column, we will execute the following query:

 DESC student;
o/p :-

FOREIGN KEY
o A foreign key is used for referential integrity.
o When we have two tables, and one table takes reference
from another table, i.e., the same column is present in

https://easy2learncode.in Page 33
RDBMS Using Oracle unit-2

both tables and that column acts as a primary key in one


table. That particular column will act as a foreign key in
another table.

Syntax to apply a foreign key constraint during table


creation:

1. CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRI


MARY KEY, ColumnNameN Datatype(SIZE), FOREIGN KEY( Col
umnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_
ColumnName));

Example:

Tab1: department (parent)

Dept_ID (prim_key) Dept_Name

Tab2: employee (child)

Emp_ ID Emp_Name Emp_salary Dept_ID (foreign_key)


(Prim_key)

 Create an employee table and apply the FOREIGN KEY


constraint while creating a table.
 To create a foreign key on any table, first, we need to
create a primary key on a table.

Example.

CREATE TABLE department1(Dept_ID number(5) PRIMARY


KEY,Dept_Name VARCHAR(40));

https://easy2learncode.in Page 34
RDBMS Using Oracle unit-2

To verify that the primary key constraint is applied to the


department table's column, we will execute the following query:

mysql> DESC department;

Now, we will write a query to apply a foreign key on the


employee table referring to the primary key of the department
table, i.e., Dept_ID.

Example.,

CREATE TABLE employee(Emp_ID NUMBER(10) PRIMARY


KEY, Emp_Name VARCHAR(40), Emp_Salary number(10),
Dept_ID NUMBER NOT NULL, FOREIGN KEY(Dept_ID) REFERE
NCES department(Dept_ID));

To verify that the foreign key constraint is applied to the


employee table's column, we will execute the following query:

Example:

Step : insert record in parent table .,i.e, department table and


then that references give to child table’s column(dept_id).

1. Insert record in department table(not allow duplicate


record.)
 Insert into department values(1,'BCA');
 Insert into department values(2,'BA');
 Insert into department values(3,'BBA');
 Insert into department values(4,'B.Com');
2. Show record
 Select * from department;

3. Insert record in employee table.(allow duplicate record.)


https://easy2learncode.in Page 35
RDBMS Using Oracle unit-2

 insert into employee values(101,'Andy Rubin', 20000,


1);
 insert into employee values(102,'Ayan
sharma',20000,1);
 insert into employee values(103,'sundar
pichai',20000,2);
 insert into employee values(104,'nil
armstrong',20000,3);
 insert into employee values(105,'rasmus
ledorf',20000,4);
 insert into employee
values(106,'shyam',20000,5);//error

4. Show record
 Select * from employee

5. CHECK
o Whenever a check constraint is applied to the table's
column, and the user wants to insert the value in it, then
the value will first be checked for certain conditions before
inserting the value into that column.
o For example: if we have an age column in a table, then
the user will insert any value of his choice. The user will
also enter even a negative value or any other invalid value.
But, if the user has applied check constraint on the age
column with the condition age greater than 18. Then in
such cases, even if a user tries to insert an invalid value
such as zero or any other value less than 18, then the age
column will not accept that value and will not allow the
user to insert it due to the application of check constraint
on the age column.
https://easy2learncode.in Page 36
RDBMS Using Oracle unit-2

Syntax to apply check constraint on a single column:

1. CREATE TABLE TableName (ColumnName1 datatype CHECK (C


olumnName1 Condition), ColumnName2 datatype,…., ColumnN
ameN datatype);

Example:

Create a student table and apply CHECK constraint to check for


the age less than or equal to 15 while creating a table.

Example:
CREATE TABLE student(StudentID INT, Student_FirstName VA
RCHAR(20), Student_LastName VARCHAR(20), Student_Phone
Number NUMBER(10), Student_Email_ID VARCHAR(40), Age N
UMBER CHECK( Age <= 15));

To verify that the check constraint is applied to the student


table's column, we will execute the following query:

Ex.

insert record:-

insert into student(StudentID,Student_FirstName,Student


_LastName,Student_PhoneNumber,Student_Email_ID,Age)
values(1,'alpha','patel',1234561231,'',15);//success

insert into student


values(2,'arpita','sharma',1234561231,'',16);//violated

https://easy2learncode.in Page 37
RDBMS Using Oracle unit-2

6. DEFAULT
Whenever a default constraint is applied to the table's column,
and the user has not specified the value to be inserted in it,
then the default value which was specified while applying the
default constraint will be inserted into that particular column.

Syntax to apply default constraint during table creation:

1. CREATE TABLE TableName (ColumnName1 datatype DEFAULT


Value, ColumnName2 datatype,…., ColumnNameN datatype);

Example:

Create a student table and apply the default constraint while


creating a table.

Example :-
CREATE TABLE BCA(StudentID number(10), Student_FirstNam
e VARCHAR(20), Student_LastName VARCHAR(20), Student_Ph
oneNumber number(10), Student_Email_ID VARCHAR(40) DEF
AULT '[email protected]');

To verify that the default constraint is applied to the student


table's column, we will execute the following query:

Example:-
DESC BCA;
insert into BCA (studentid,student_firstname,student_lastname,
student_phonenumber) values(2,'james','goslin',9929925125);

select * from BCA;

https://easy2learncode.in Page 38
RDBMS Using Oracle unit-2

SUBQUERY:
 A query within query is known as Sub-Query. It is also
known as ‘Nested Query’.
 You can have any number of sub-queries nested, oracle does
not place a limit.
 The innermost query is executed first and output is utilized
to execute the outer query.

TYPES OF SUB-QUERY:
[1]Single-Row Subqueries:
 Queries that return only one row from the inner(sub)
SELECT statement.
 This is used to single-row operator. That is (= , > , >= , < , <= ,
<> )
Example .,

 Display the employee whose job is the same as that of


emp_id = 3;

Solution :

 SELECT emp_nm, job_id FROM employees WHERE job_id =


(SELECT job_id FROM employees WHERE emp_id=3);

[2]Multiple-Row Subqueries:
 Queries that return more than one row from the inner(sub)
SELECT statement.

 Subqueries that return more than one row are called


Multiple-row subqueries.

 Following are the operators of the multiple row subquries.


 The multiple-row operators expects one or more values.

Operator Meaning

https://easy2learncode.in Page 39
RDBMS Using Oracle unit-2

IN Equal to any member in the list.


ANY or SOME Compare value to each value returned by
the subquery.
ALL Compare value to every value returned by
the subquery.

Example :
Find the employees who earn the same salary as the minimum
salary for every department.

Solution:
SELECT emp_id, emp_nm FROM employees WHERE salary IN
(SELECT min(salary) FROM employees GROUP BY dept_id);

SELECT statement with WHERE

The WHERE clause specifies a search condition for rows returned


by the SELECT statement.

Syntax:
SELECT select_list FROM table_name WHERE
search_condition ;

ex., SELECT id, name, city, FROM student WHERE name =


'Shivansh';

SELECT statement with GROUP BY


The GROUP BY clause is used for grouping the data.
It means the rows in a table can be divided into different groups
to treat each group separately.

Syntax:
Select column, group function(column)
From table_name GROUP BY column_nm;

https://easy2learncode.in Page 40
RDBMS Using Oracle unit-2

Example:
Select department,count(*) from student GROUP BY
department;

SELECT statement with HAVING


The GROUP function works on each group, and The HAVING
clause keeps the groups that match the group condition.
HAVING is just like WHERE clause, You can HAVING when you are
interested only in specific groups.

Syntax :
Select column_list from table_nm group by column_nm having
group_condition;

Ex., select roll, name,city from student GROUP BY roll HAVING


roll>3;

SELECT statement with ORDER BY

The ORDER BY clause is used to sort or re-arrange the records in


the result set.
The ORDER BY clause is only used with SELECT statement.

Syntax:
Select col_nm from table_nm [WHERE CLAUSE] ORDER BY
col_nm[ASC/ DESC];

Example:
Select * from student ORDER BY name;

Select * from student where roll=>4 ORDER BY roll DESC;

https://easy2learncode.in Page 41
RDBMS Using Oracle unit-2

SELECT statement with ROLLUP


 The ROLLUP is an extension of the GROUP BY clause.
 The ROLLUP calculates multiple levels of subtotals across a
group of columns (or dimensions) along with the grand
total.

Syntax :

 SELECT col1,col2, aggregate(col3) FROM table_name GROUP


BY ROLLUP (col1, col2);

 The ROLLUP clause generates the number of grouping


sets which is the same as the number grouping columns
specified in the ROLLUP plus a grand total.

 In the syntax above, the ROLLUP clause generates the


following grouping sets:

1. (col1, col2)
2. (group_total)
3. (grand total)

Example:
SELECT dept_id,emp_name,sum(emp_salary) FROM employee
GROUP BY ROLLUP(dept_id,emp_name);

SELECT statement with CUBE


 The CUBE is an extension of the GROUP BY clause that
allows you to generate grouping sets for all possible
combinations of dimensions(columns).

 Syntax of the CUBE with three columns (or dimensions):

https://easy2learncode.in Page 42
RDBMS Using Oracle unit-2

Syntax:

SELECT c1, c2, c3, aggregate(c4)


FROM table_name
GROUP BY CUBE(c1,c2,c3);

Example:
SELECT dept_id,emp_name,sum(emp_salary) FROM employee
GROUP BY CUBE(dept_id,emp_name);

SELECT statement with DISTINCT


 The DISTINCT clause is used in a SELECT statement to filter
duplicate rows in the result set.

 It ensures that rows returned are unique for the column.

SYNTAX :
SELECT DISTINCT column_1 FROM table;

Example :
SELECT DISTINCT student_firstname FROM student;

SELECT statement with ANY


The Oracle ANY operator is used to compare a value to a list of
values or result set returned by a subquery.

syntax:
operator ANY ( subquery)
Example:
select * from student where studentid =ANY(select studentid
from student where dept_id=104);

Syntax:
https://easy2learncode.in Page 43
RDBMS Using Oracle unit-2

• The ANY operator must be a comparison operator such as =,


!=, >, >=,<, <=.
• The list or subquery must be surrounded by the
parentheses.

 When you use the ANY operator to compare a value to a list.


Syntax:
SELECT * FROM table_name WHERE c > ANY (v1,v2, v3 );
Example: select * from student where roll=ANY(1,3,4,5) ;

SELECT statement with ALL


The Oracle ALL operator is used to compare a value to a list of
values or result set returned by a subquery.
Syntax of the ALL operator used with a list or a subquery:
Syntax :
operator ALL ( subquery)
Example:
select * from student where age>ALL(select AVG(studentid) from
student) ORDER BY studentid ASC;

When you use the ALL operator to compare a value to a list:-


SELECT * FROM table_name WHERE c > ALL ( v1, v2, v3 );
Example: select * from student where studentid > ALL(1,3) ;

SELECT statement with EXISTS


The Oracle EXISTS operator is a Boolean operator that returns
either true or false.
The EXISTS operator is often used with a subuery to test for the
existence of rows:
Syntax : SELECT * from tab_nm where EXISTS (subquery);

Example : SELECT studentid,student_firstname from student


where EXISTS (select * from BCA) ORDER BY studentid;

https://easy2learncode.in Page 44
RDBMS Using Oracle unit-2

Join (Inner join ,outer join, self join)


 To combine the data from two or more
tables ,it is called a JOIN.
 Table are joined on columns that have the
same data type and data width in the
tables.
 In joins Rows in one table can be joined to
rows in another table according to
common values (that are relational values
)existing in corresponding columns, that
is usually primary and foreign key
columns.
 Types of joins
 [1]Inner join
 [2]Outer (Left , Right)
 [3]Self join

https://easy2learncode.in Page 45
RDBMS Using Oracle unit-2

SELF JOIN

We have create first two table and insert some


record:
Create table dept (deptno number(3),dname
varchar2(10),loc varchar2(10))
 Insert into dept values (10,'mrk','hyd')
 insert into dept values (20,'acco','bgsr')
 Insert into dept values (30,'hr','mumbai')
 select *from dept

https://easy2learncode.in Page 46
RDBMS Using Oracle unit-2

Create table emp (empno number(3),ename


varchar2(10),job varchar2(10),mgr
number(3),deptno number(3));
 Insert into emp values
(111,'ram','analyst',444,10)
 Insert into emp values
(222,'syam','clark',333,20)
 Insert into emp values
(333,'jigar','manager',111,10)
 Insert into emp values
(444,'kam','engineer',222,40)
 Select *from emp

https://easy2learncode.in Page 47
RDBMS Using Oracle unit-2

[1] Inner join


 Inner joins are also knows as equal joins
,because here the where statement
generally compares two columns from the
two table with equivalence operator(=).
 Ex.
 select empno,ename,job,dname,loc from
emp e,dept d where e.deptno =
d.deptno;
 Select empno,ename,job,dname,loc from
emp inner join dept using(deptno)

[2] Outer join


 An outer join allows you to join two tables
and results even when the second table
doesn’t have an records corresponding with
the first.
 LEFT-OUTER Join
 The left outer join can be used to returns
all the rows from the first table even if
there are no matches in the second table.

https://easy2learncode.in Page 48
RDBMS Using Oracle unit-2

 Ex. Select
e.empno,e.ename,e.job,d.dname,d.deptno
from emp e,dept d where e.deptno =
d.deptno(+)

 RIGHT-OUTER Join
 The right outer join can be used to
returns all the rows from the second
table even if there are no matches in the
first table.
Ex.
 Select
e.empno,e.ename,e.job,d.dname,d.loc
from emp e,dept d where e.deptno(+) =
d.deptno

https://easy2learncode.in Page 49
RDBMS Using Oracle unit-2

[2] Self join

 A self join is a join in which a table is joined


with itself.
 To join a table itself means that each row of
the table is combined with itself and with
every other row of the table.
 The table appears twice in the FROM clause
and is followed by table aliases that qualify
column names in the join condition.
 To perform a self join, Oracle Database
combines and returns rows of the table that
satisfy the join condition

Syntax:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Example: Oracle Self Join
The following SQL query uses a self join to
return the id of each employee along with
the id of the employee's manager.
Sample table: employee

https://easy2learncode.in Page 50
RDBMS Using Oracle unit-2

Create table:
create table employee (id number(10),name
varchar2(255), mngr_id number(10),
mngr_name varchar2(255));
insert record:
insert into employee values(10,'angel
patel',11,'riya sharma');
insert into employee values(11,'diya
patel',12,'sudhir maheta');
insert into employee values(101,'vinay
yadav',110,'krishna yadav');
insert into employee
values(1,'ganesh',10,'ram');
show record:
select * from employee;
Self join query:
select e1.name,e2.mngr_name from employee
e1, employee e2 where e1.id=e2.mngr_id;

https://easy2learncode.in Page 51
RDBMS Using Oracle unit-2

Set Operator: Minus, Intersect, Union

create table emp1 (emp_id number


(3),emp_name varchar2(10),dept_id
number(3))
insert into emp1 values(1,'ram',10)
insert into emp1 values(2,'syam',20)
insert into emp1 values(3,'kam',30)
insert into emp1 values(4,'man',10)
select *from emp1

https://easy2learncode.in Page 52
RDBMS Using Oracle unit-2

create table dept (dept_id number


(3),dept_name varchar2(10),emp_id
number(3))
insert into dept values(1,'ram',10)
insert into dept values(2,'syam',20)
insert into dept values(3,'kam',30)
insert into dept values(4,'man',10)
select *from dept

UNION
 UNION is used to combine the results of
two or more SELECT statements.

 However it will eliminate duplicate rows


from its result set.

Ex.
Select dept_id from emp1 UNION select
dept_id from dept

https://easy2learncode.in Page 53
RDBMS Using Oracle unit-2

[2] intersect
 Intersect operation is used to combine
two SELECT statements,
 but it only retuns the records which are
common from both SELECT statements.

Ex.
Select emp_name from emp1 INTERSECT select
dept_name from dept

[3] minus
 The Minus operation combines results of
two SELECT statements and return only
those in the final result, which belongs to
the first set of the result.

https://easy2learncode.in Page 54
RDBMS Using Oracle unit-2

Ex.
Select emp_id from emp1 MINUS select emp_id
from dept

 General Functions
COALESCE
The Oracle COALESCE() function accepts a list of
arguments and returns the first non-null value.
Syntax:
COALESCE(exp1, exp2, ..., exp n)
In this syntax, the COALESCE() function returns the first
non-null expression in the list. It requires at least two
expressions.
In case all expressions evaluate to null, the function
returns null.
The following example returns 1 because it is the first
non-null argument:
SELECT COALESCE(NULL,1,2) result FROM dual;

https://easy2learncode.in Page 55
RDBMS Using Oracle unit-2

Return type:
If all arguments have the same data type, the COALESCE()
function returns a value of that data type.
If the arguments have different data types, the COALESCE
function implicitly converts all arguments to the data type
of the first non-null argument. In case the conversion fails,
then Oracle issues an error.
Use in table :student
Select id,name,city, COALESCE(mobile,telephone) from
student

 CASE WHEN STATEMENT


CASE Statement is work like as if…else
statement.

Syntax
CASE [ expression ]

WHEN condition_1 THEN result_1


WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n

ELSE [default result]

END

Example:
https://easy2learncode.in Page 56
RDBMS Using Oracle unit-2

SELECT
(CASE 'BCA'
WHEN 'BA' THEN 'BA STUDENT'
WHEN 'BCA' THEN 'BCA STUDENT'
WHEN 'B.Com' THEN 'B.Com STUDENT'
ELSE 'NOT A VALID FIELD'
END) As student
FROM dual;

Use in table :-
SELECT id,name,course,
(CASE course
WHEN 'BA' THEN 'BA STUDENT'
WHEN 'BCA' THEN 'BCA STUDENT'
WHEN 'B.Com' THEN 'B.Com STUDENT'
ELSE 'NOT A VALID FIELD'
END) As selected_course
FROM student;

Creating user & role:


User
https://easy2learncode.in Page 57
RDBMS Using Oracle unit-2

Syntax :
create user username IDETIFIED by password
Ex :
[1] CREATE USER admin identified by
dhanak
Role
 A role is a set(group) of privileges that can be granted
to users or to other roles.
 It is a used for privilege management.
 Roles are a collection of privileges or access rights.
 Any combination of system privileges ,object
privileges ,and role privileges may be granted to a
role.
Ex.
 Create role bca
 grant create table,create view to bca
 Grant bca to admin

DCL/TCL COMMAND

https://easy2learncode.in Page 58
RDBMS Using Oracle unit-2

 GRANT
Grant Privileges on Table
 You can grant users various privileges to
tables.
 These privileges can be any combination
of SELECT, INSERT, UPDATE, DELETE,
REFERENCES, ALTER, INDEX, or ALL.
The Syntax for the GRANT command is:
GRANT privilege_name
ON object_name
TO {user_name}

https://easy2learncode.in Page 59
RDBMS Using Oracle unit-2

privilege_name is the access right or


privilege granted to the user. Some of the
access rights are ALL, EXECUTE, and SELECT.
object_name is the name of an database
object like TABLE, VIEW, and SEQUENCE.
user_name is the name of the user to whom
an access right is being granted.
Ex.
 create table emp(deptno number(5), name
varchar2(255),post varchar2(255),city
varchar2(255),mobile number(10));
 GRANT SELECT, INSERT, UPDATE ON emp
TO admin;
 select * from system.emp;
 insert into system.emp values
(1,'aaa','professor','bagasara',1234567890);
 update update system.emp set deptno=10
where name=‘aaa';
 Delete FROM SYSTEM.EMP WHERE
deptno=10;
https://easy2learncode.in Page 60
RDBMS Using Oracle unit-2

Revoke
 The REVOKE command removes user access rights or
privileges to the database objects.

 Once you have granted EXECUTE privileges on a


function or procedure, you may need to REVOKE
these privileges from a user.

 This command use to remove accessibility to the


perticular user of perticular rights.

Syntax
REVOKE privileges ON object FROM user;
Ex.
REVOKE insert on emp from admin
REVOKE all on emp from admin

What is transaction?

 A series of different operations performed on


table data is knows as TRANSACTION.

 A transaction will implicitly with an


insert,update delete or select statement.
Types of transaction command:
https://easy2learncode.in Page 61
RDBMS Using Oracle unit-2

1)commit
2)rollback
3)savepoint

[1]Commit
 COMMIT command is used to permanently
save any transaction into the database.
 A commit ends the current transaction and
makes permanent any changes made during
the transaction.
 Ex. :
o Create table student(id
number(5),name varchar2(50),city
varchar2(50))
o Insert into student
values(1,'krupa','delhi');
o Insert into student
values(2,'ansh','bombay');
o Insert into student
values(3,'aaa','rajkot');
o commit

Rollback
 A rollback exactly opposite of commit.
 Recover the data in database.
https://easy2learncode.in Page 62
RDBMS Using Oracle unit-2

 This is work to same as “ctrl+z”.


Ex.
Select *from student;

delete from student where id=2;

ROLLBACK;

select *from student;

savepoint
 Save point marks and saves the current point In the
processing of a transaction.

 Always savepoint can be used with rollback command.

 SQL SAVEPOINT command create new save point.

 SAVEPOINT command save the current point with the


unique name in the processing of a transaction.

Syntax :

 SAVEPOINT savepoint_name;
Example:
CREATE TABLE emp_data ( no NUMBER(3), name
VARCHAR(50), code VARCHAR(12) );

SAVEPOINT table_create;
https://easy2learncode.in Page 63
RDBMS Using Oracle unit-2

insert into emp_data VALUES(1,'Opal', 'e1401');

SAVEPOINT insert_1;

insert into emp_data VALUES(2,'Becca', 'e1402');

SAVEPOINT insert_2;

SELECT * FROM emp_data;

 ROLLBACK TO insert_1;

 SELECT * FROM emp_data;

https://easy2learncode.in Page 64
RDBMS Using Oracle unit-2

Follow Us :

https://easy2learncode.in Page 65

You might also like