Oracle SQL and PL SQL Notes
Oracle SQL and PL SQL Notes
ORACLE 19C
Data:
• Data is a raw collection of facts about people, places, and things.
• It is unprocessed one. It means, it is not meaningful form.
• Data can be divided into 2 types. They are:
i. Structured Data
ii. Unstructured Data
Structured Data:
It is made up of with letters, digits, and special symbols.
Example:
25 1-2-123/A Ramu
Unstructured Data:
Multimedia objects come under Unstructured data.
Example:
Audios
Videos
Images
Animations
Documents
Data
Types of Data
Information:
If the data is arranged in meaningful form, then it called “Information”. It is
processed one. It is in meaningful form.
Example:
STUDENT
STUDENT_ID STUDENT_NAME MARKS
25 Ramu 500
Note:
If the data is processed by the process of data processing, it becomes
Information.
Data
Information
25 SID SNAME MARKS
Ramu Data Processing
500 25 Ramu 500
Database:
• Database is a collection of interrelated data.
• It contains records and fields.
• Rows are called records and columns are fields.
• Field holds individual values.
• Record is a collection of field values.
• A row can be also called as record (or) tuple (or) entity instance.
• A column can be also called as field (or) attribute (or) property.
• Database can be divided into two types. They are:
i. OLTP
ii. OLAP
OLTP:
• OLTP stands for “OnLine Transaction Processing”.
• This database is used for day-to-day operations.
• CRUD operations are performed in day-to-day operations. CRUD
operations are:
C = Create
R = Read
U = Update
D = Delete
Example:
Maintaining day-to-day operations of Bank Customers like
withdrawals, deposits, checking balance and fund transfers
OLAP:
• OLAP stands for “OnLine Analytical Processing”.
• This database is used for Data Analysis.
• In this, we write complex queries for data analysis.
• It can be also called “Dataware Housing [DWH]” or “Decision
Support System [DSS]”.
Example:
Retrieving sales of past 5 years
STUDENT
SID SName Scity
1001 Ramu Hyd
1002 Arun Chennai
Interrelated Data
MARKS
SID M1 M2 M3
1001 40 60 50
1002 70 90 80
Database
DBMS:
• DBMS stands for DataBase Management System/Software.
• It is a software that is used to create and maintain the database.
• This software allows us to store, manipulate and retrieve the data of
database. “Retrieve” means opening existing data. Manipulate means,
Inserting, Deleting and Updating [modifying] the data.
RDBMS:
• RDBMS stands for Relational DataBase Management System / Software.
• In this, we maintain database in the form of tables.
Example: Oracle, SQL Server, MY SQL, PostGre SQL, DB2
Table:
• Table is a collection of rows and columns.
• It can be also called as “Relation” (or) “Entity”.
• Rows are called Records (or) Tuples (or) Entity Instances.
• Columns are called Fields (or) Attributes (Or) Fields.
• Field holds individual values.
• Record is a collection of field values.
STUDENT
Column Row
(Or) (Or)
Attribute Record
(or) (Or)
Property Entity Instance
(Or)
Tuple
Metadata:
• Metadata is the data about the data.
• It describes about the data.
Example:
Field Name
Table Name
Data Type
Field Size
Disadvantages of FMS:
• Data Redundancy
• Data Dependence
• No Security
• Limited Data Sharing
• Excessive Program Maintenance
• Lengthy Development Times
Advantages of DBMS:
• Minimal Data Redundancy
• Data Independence
• Security
• Improved Data Sharing
• Improved Data Consistency
• Improved Data Integrity
• Improved Data Accessibility and Responsiveness
• Increased Productivity
ORACLE:
• Oracle is a Relational Database management software.
• It is used to create & maintain the database.
• In this we maintain database in the form of tables.
• It allows us to store, manipulate and retrieve the data of database.
• Second version of “Oracle” introduced in 1979.
• Latest version is Oracle 19C. [c =Cloud].
• It is a product of “ORACLE” company. This company is established in 1977
by “Larry Ellison” with the name “Software Development Laboratories”.
Later it renamed as “Relation Software Inc.” [Incorporation] in 1979. Later
it renamed as “ORACLE CORPORATION” in 1983.
Tools of ORACLE:
Oracle provides following tools:
• SQL
• PL/SQL
SQL:
• SQL stands for “Structured Query Language”.
• It is a query language used to write the queries.
• Query is a request that is sent to Database Server.
• Query is used to communicate with the database.
• It is a Non-Procedural Language. We will not write any set of statements.
• It is a Fourth Generation Language [4GL]. In 4GLs, we much concentrate
on what to do rather than how to do.
• It is a Unified Language. It is common for many relational databases such
as SQL Server, My SQL, Postgre SQL ..etc.
• It provides operators to perform operations like +, -, >, Between and, In
Like ..etc.
• It provides built-in functions to perform specific actions.
• It does not provide control structures. Because we cannot write set of
statements in SQL. We have no need to control the flow of execution.
• It provides 5 sub languages. Every sub language provides commands to
work with the database. They are:
i. DDL
ii. DML
iii. DQL /DRL
iv. DCL / ACL
v. TCL
nChar(n)
nVarchar2(n)
nCLOB
[ n = National ]
Number(p,s):
• It is used to hold floating point type values.
• “p” stands for Precision. “s” stands for Scale.
• Precision means, Total Number of Decimal Places
• Scale means, Number oF Decimal Plces.
• Valid Range of Precision is: 1 t0 38.
• Valid range of Scale is -84 to 127.
Example:
If maximum average is 100.00 then declare as:
Avrg_Marks Number(5,2) => Range: -999.99 to 999.99
If maximum salary is 100000 .00[1 Lakh] then declare as:
Salary Number(8,2) => -999999.99 to 999999.99
Varchar(n):
• It is used to hold a set of characters.
• “n” means maximum number of characters.
• It is a Variable Length Character Data Type.
• It is a single byte Character Data Type.
• It is ASCII Code Character Data type.
• Maximum size is: 4000 Bytes
• There is no default size for it. We must specify the size.
• To hold variable length characters like Emp_Name, Student_Name,
Product_Name …etc. we can use this data type.
Example:
Emp_Name Varchar2(20) => it can hold maximum of 20 characters
Job Varchar2(10) => it can hold maximum of 10 characters
Long:
• It is used to hold a set of characters.
• It is a Variable Length Character Data Type.
• It is a single byte Character Data Type.
• It is ASCII Code Character Data type.
• Maximum size is: 2 GB
Example:
Experience_summary LONG
Customer_Feedback LONG
CLOB:
• It is used to hold a set of characters.
• CLOB stands for Character Large Object.
• It is a Variable Length Character Data Type.
• It is a single byte Character Data Type.
• It is ASCII Code Character Data type.
• Maximum size is: 4 GB
Example:
Experience_Summary CLOB
Product_Features CLOB
Remarks CLOB
Customer_Feedback CLOB
nChar(n):
• It is used to hold a set of characters.
• In “nChar“, n means National.
• It is a Fixed Length Character Data Type.
• It is a multi-byte Character Data Type.
• It is UNI Code Character Data type.
• Maximum size is: 2000 Bytes
• Default size is: 1
• To hold English and other language characters, we use it.
nVarchar(n):
• It is used to hold a set of characters.
• In “nVarchar“, n means National.
• It is a Variable Length Character Data Type.
• It is a multi-byte Character Data Type.
• It is UNI Code Character Data type.
• Maximum size is: 4000 Bytes
• No default size for it. We must specify the size.
• To hold English and other language characters, we use it.
nCLOB:
• It is used to hold a set of characters.
• In “nCLOB“, n means National.
• It is a Variable Length Character Data Type.
• It is a multi-byte Character Data Type.
• It is UNI Code Character Data type.
• Maximum size is: 4 GB.
• To hold English and other language characters, we use it.
Timestamp:
• It is used to hold time values.
• It can hold date values also.
• It can hold day, month, year, hours, minutes, seconds and fractional
seconds [Milli Seconds].
• 11 Bytes Fixed Memory will be allocated for it.
BLOB:
• BLOB stands for “Binary Large Object”.
• It is used to hold multimedia objects like images, audios, videos and
documents.
• It can hold binary data of the multimedia object and displays to us in
hexadecimal format.
• It maintains path of the object & object is stored out of the database.
That’s why it can be also called as “External Large Object”.
• It is secured one. Because object stored with in the database.
• Maximum size is: 4 GB.
Example:
Student_Photo BLOB
Constraints in SQL:
• Constraint is a rule which is applied on a column.
• Constraint is used to maintain accurate and quality data.
• Constraint restricts the user from entering invalid data.
• The goal of constraint is maintaining accurate and quality data. This
feature is called “Data Integrity”.
• SQL provides Data Integrity.
1. Primary Key:
• It should not accept duplicate values.
• It should not accept null values.
• If our requirement is not to accept duplicate value and null value in
a column then use it.
Example:
SID [Primary Key] SName M1
1001 Ravi 45
1002 Arun 70
1003 Ravi 70
1001 Sai 50
Ramu 90
2. Unique:
• It should not accept duplicate values.
• It accepts null values.
• If our requirement is accepting null values but not accepting
duplicate values, then use it.
Example:
CUSTOMER
CID SName Mobile_Number[Unique]
1001 Ravi 90123 12312
1002 Arun 90123 12313
1003 Ravi 90123 12314
1004 Sai 90123 12312
1005 Ramu
3. Not Null:
• It should not accept null values.
• It can accept duplicate values.
• When we want to accept duplicate value and demand for entering
a value in field then use it.
Example:
SID SName [Not Null] M1
1001 Ravi 45
1002 70
1003 Ravi 70
4. Check:
It is used to write our own conditions [rules] on a column.
Example:
If M1 value Must be between 0 to 100 only then write:
M1 Number(3) Check(M1>=0 and M1<=100)
5. Default:
• It is used to apply default value to a column.
• We have no need to pass this value when we insert the record. It
will be taken automatically when we don’t pass the value.
• If we pass the value, it takes the value. If we don’t pass the value,
it takes default value.
Example:
Empno EName Company_Name Company_City
[default ‘Naresh IT’] [default ‘Hyd’]
7001 Raju Naresh IT Hyd
7002 Ashok Naresh IT Hyd
7003 Kiran Naresh IT Hyd
COURSE STUDENT
Cid Cname Sid SName Cid
[Primary Key] [Foreign Key]
10 Java 1001 Ashok 20
20 Python 1002 Ravi 30
30 Oracle 1003 Sai 90
DDL Commands
“Create” Command:
• It is a DDL Command.
• It is used to create the database objects like tables, views, and
indexes …etc.
Example:
Create Table emp(Empno number(4) constraint c1 Primary Key,
Ename varchar2(20) constraint c2 Not Null);
Creating Table:
SQL> Create Table Student(
Rno Number(2),
Name Varchar2(20) );
Output:
Table Created
Output:
Name Null? Type
----------------------- -------- ----------------
RNO NUMBER(2)
NAME VARCHAR2(20)
Output:
1 row created.
Output:
old 1: insert into student values(&rno,'&name')
new 1: insert into student values(20,'Vijay')
1 row created.
Note: / (or) Run => is used to repeat recent command
Output:
RNO NAME
---------- --------------------
10 Raju
20 Vijay
30 Sai
Example-2:
Create a table with following structure, Insert the records and retrieve
the records:
Emp
Empno Ename Job Sal DOJ
Creating Table:
SQL> Create Table Emp(
empno number(4),
ename varchar2(20),
job varchar2(15),
sal number(7,2),
doj date);
Output:
Table created.
Inserting a Record:
SQL> Insert into Emp values(1234,'ravi','clerk',5000,'12-Dec-2017');
Output:
1 row created.
Output:
old 1: Insert into Emp values(&empno,'&en','&j','&sal','&doj')
new 1: Insert into Emp values(1235,'arun','salesman','7000','23-aug-
2018')
1 row created.
Output:
old 1: Insert into Emp values(&empno,'&en','&j','&sal','&doj')
new 1: Insert into Emp values(1236,'sravan','accountant','6000','25-
Nov-2017')
1 row created.
Output:
EMPNO ENAME JOB SAL DOJ
---------- -------------------- --------------- ---------- ---------
1234 ravi clerk 5000 12-DEC-17
1235 arun salesman 7000 23-AUG-18
1236 sravan accountant 6000 25-NOV-17
Example-1:
Create a Table using following structure:
Student1
Rno Name M1
Set Primary Key for Rno
Set Not Null for Name
Set Check for M1 [Marks must be between 0 to 100]
Output:
Table created.
Inserting a Record:
SQL> Insert into Student1 values(12,'Ravi',45);
Output:
1 row created.
Inserting null value in Rno field to check Primary Key does not accept
null value:
SQL> Insert into Student1 values(null,'Kiran',70);
Output:
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."STUDENT1"."RNO")
Inserting duplicate value in Rno field to check Primary Key does not
accept duplicate value:
SQL> Insert into Student1 values(12,'Arun',65);
Output:
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C007590) violated
Output:
1 row created.
Inserting null value in name field to check ‘not null’ does not accept
null value:
SQL> Insert into Student1 values(14,null,80);
Output:
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."STUDENT1"."NAME")
Output:
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C007589) violated
Output:
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C007589) violated
Example-2:
Create a Table with following structure:
Student2
StudentId Name Fee College_City
Output:
Table created.
Inserting a record:
SQL> Insert into Student2(StudentId,Name) values(1234,'Raju');
Output:
1 row created.
Output:
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C007592) violated
Output:
1 row created.
Retrieve the records from Table and observe default values inserted
in Fee and College_City fields:
SQL> Select * from Student2;
Output:
STUDENTID NAME FEE COLLEGE_CITY
---------- --------------- ---------- ---------------
1234 Raju 15000 Hyd
Amar 15000 Hyd
Example-3:
Create following tables:
Dept
Deptno Dname
Set Deptno as Primary Key
Emp
Empno Ename Job Sal DeptNo
Set Empno as Primary Key
Set Dept No as Foreign Key [References].
Output:
Table created.
Output:
Table created.
Output:
old 1: Insert into Dept values(&dno,'&dn')
new 1: Insert into Dept values(10,'Sales')
1 row created.
Output:
old 1: Insert into Dept values(&dno,'&dn')
new 1: Insert into Dept values(20,'HR')
1 row created.
SQL> /
Enter value for dno: 30
Enter value for dn: Payroll
Output:
old 1: Insert into Dept values(&dno,'&dn')
new 1: Insert into Dept values(30,'Payroll')
1 row created.
SQL> /
Enter value for dno: 40
Enter value for dn: Orders
Output:
old 1: Insert into Dept values(&dno,'&dn')
new 1: Insert into Dept values(40,'Orders')
1 row created.
DEPTNO DNAME
---------- ---------------
10 Sales
20 HR
30 Payroll
40 Orders
Output:
1 row created.
Output:
1 row created.
Output:
ERROR at line 1:
ORA-02291: integrity constraint (SYSTEM.SYS_C007595) violated -
parent key not found
Example-1:
Create a Table with following structure:
Student3
Std_Id Std_Name M1
Set Primary Key for Std_Id with Constraint Name c1
Set Not Null for Std_Name with Constraint Name c2
Set Check for M1 with Constraint Name c3 [M1 must be b/w 0 to 100]
Example-2:
Create a Table with following Structure:
Emp1
Empno Ename MobileNo Company_City Job Salary
Set Primary Key for Empno with constraint name emp_pk
Set Not Null for Ename with constraint name emp_nn
Set Unique for MobileNo with constraint name emp_u
Set Default valu as ‘Hyd’ for Company_City
Set Check for Salary with constraint name emp_chk (Salary must be
between 5000 to 100000)
Creating Table:
SQL> Create Table Emp1(
Empno Number(4) Constraint Emp_Pk Primary Key,
Ename varchar2(20) Constraint Emp_nn Not Null,
MobileNo varchar2(10) Constraint Emp_u Unique,
Company_City varchar2(12) Default 'Hyd',
Salary Number(8,2) Constraint Emp_chk Check(salary>=5000 and
salary<=10000));
Output:
Table created.
Example-3:
Crete following Tables with Constraint Names and Constraint Types:
Course
Course_Id Course_Name
Set Course Id as Primary Key with Constraint Name Course_PK
Student
Student_Id SName Course_Id
Set Course_Id as Foreign Key (References) with Constraint Name
Student_FK
“Alter” Command:
• It is a DDL Command.
• It is used to change the structure of database objects like tables,
views, and indexes …etc.
• This command can be used for following purposes:
▪ To Add the Columns
▪ To Modify the Field Sizes and Field Data types
▪ To Drop the Columns
▪ To Rename the Columns
▪ To Rename the Constraints
▪ To Disable the Constraints
▪ To Enable the Constraints
▪ To Add the Constraints
▪ To Drop the Constraints
Example-1:
Student5
Rno Name
Creating Table:
SQL> Create Table Student5(
StdId Number(2),
SName Varchar2(20));
Table created.
Note:
See Table Structure using “Desc” Command After Altering the table to
see whether changes applied or not.
Ex: Desc Student5;
Adding a Column:
SQL> Alter Table Student5 add m1 number(3);
(OR)
SQL> Alter Table Student5 add(m1 number(3));
Output:
Table altered.
Output:
Table altered.
Dropping a Column:
SQL> Alter Table Student5 Drop Column m3;
(OR)
SQL> Alter Table Student5 Drop(m3);
Output:
Table altered.
Output:
Table altered.
Output:
Table altered.
Renaming a Column:
SQL> Alter Table Student5 rename Column Sname to Std_Name;
Output:
Table altered.
Output:
Table altered.
Disabling a Constraint:
SQL> Alter Table Student5 disable constraint std5_pk;
Output:
Table altered.
Note: Temporarily Primary Key will not work for this field. Now this field
can accept duplicate and null values.
Output:
1 row created.
Output:
1 row created.
Output:
1 row created.
Note: To enable it, the column should not have duplicate and null values
Output:
3 rows deleted.
Output:
Table altered.
Dropping Constraint:
SQL> Alter table student5 drop constraint std5_pk;
Output:
Table altered.
Note:
Using “Add Constraint”, we can add Table Level Constraints like Primary
Key, Check, Foreign Key, and Unique. We cannot add Not Null and
Default. These are column level constraints.
To add Not Null and Default, we can use “Modify”.
Output:
Table altered.
Output:
Table altered.
Table altered.
Output:
Table altered.
Output:
Table altered.
Adding m1 Column:
SQL> Alter table student5 add m1 number(3);
Table altered.
Table altered.
Example-2:
Create Tables:
SQL> create table dept5(
deptno number(2),
dname varchar2(15));
Output:
Table created.
Output:
Table created.
Output:
Table altered.
Output:
Table altered.
Output:
Table altered.
“Drop” Command:
• It is a DDL Command.
• It is used to drop [delete] the database objects like tables, views, and
Indexes …etc.
Example:
Drop Table Emp; -- Emp table dropped to Recycle bin
“Flashback” Command:
• It is a DDL Command.
• It is used to recollect the dropped database objects from recycle bin.
Syntax to Flashback [Recollect] a Table:
Example:
Flashback Table Emp to before drop; --Emp table restored
“Purge” Command:
• It is a DDL Command.
• It is used to remove a dropped database object from Recycle Bin.
Example:
Purge Table Emp; -- emp table deleted permanently
Note:
To empty the recycle bin we write:
SQL> Purge recyclebin;
Example-1:
Create aTable with following Structure:
Product
pid pname
Set pid as Primary key with the name prd_pk
Insert the records
Creating Table:
SQL> create table product(
pid number(4) constraint prd_pk primary key,
pname varchar2(20) );
Output:
Table created.
Output:
old 1: Insert into product values(&pid,'&pname')
new 1: Insert into product values(1001,'Hard Disk')
1 row created.
Output:
old 1: Insert into product values(&pid,'&pname')
new 1: Insert into product values(1002,'Monitor')
1 row created.
SQL> /
Enter value for pid: 1003
Enter value for pname: RAM
Output:
old 1: Insert into product values(&pid,'&pname')
new 1: Insert into product values(1003,'RAM')
1 row created.
SQL> /
Enter value for pid: 1004
Enter value for pname: SMPS
Output:
old 1: Insert into product values(&pid,'&pname')
new 1: Insert into product values(1004,'SMPS')
1 row created.
PID PNAME
---------- --------------------
1001 Hard Disk
1002 Monitor
1003 RAM
1004 SMPS
Dropping a Table:
SQL> Drop Table product;
Output:
Table dropped.
Output:
ORIGINAL NAME RECYCLEBIN NAME OBJECT TYPE DROP TIME
---------------- ------------------------------ ------------ -------------------
PRODUCT BIN$7VyxkH38QPCoCke0Qx/t6Q==$0 TABLE 2021-06-15:10:49:28
Note:
PRODUCT table dropped. So below query gives error.
Output:
ERROR at line 1:
ORA-00942: table or view does not exist
Output:
Flashback complete.
Note:
Product table recollected from recycle bin. Now we can see the records
in Product Table.
PID PNAME
---------- --------------------
1001 Hard Disk
1002 Monitor
1003 RAM
1004 SMPS
Output:
Table dropped.
Output:
ORIGINAL NAME RECYCLEBIN NAME OBJECT TYPE DROP TIME
---------------- ------------------------------ ------------ -------------------
PRODUCT BIN$5eEJqn+HTF6yEaXYgkeKSg==$0 TABLE 2021-06-15:11:06:17
Output:
Table purged.
Note:
product table deleted from recycle bin. It means, product table deleted
permanently. We cannot recollect it.
Output:
Table Created.
Output:
Table dropped.
Output:
Table purged.
Note:
Using above two queries we can remove a table permanently.
(OR)
Instead of writing two queries we can delete t1 table permanently using
one query as following:
Output:
Table dropped.
SQL> show recyclebin;
Output:
Empty
Note:
No dropped objects in recycle bin. It is empty.
“Truncate” Command:
• It is a DDL Command.
• It is used to remove all records from a table.
• It does not remove structure of the table.
• It cannot be used to remove one record (or) a set of records from
table.
Syntax to truncate a Table:
Example:
Truncate table emp; -- deleted all records from emp table
“Rename” Command:
• It is a DDL Command.
• It is used to rename the data base objects like tables.
Example:
Rename emp to employee; -- emp table renamed to employee
DML Commands
“Insert” Command:
• It is a DML Command.
• It is used to insert the records into table.
Syntax :
Example:
Insert into emp(empno,ename,job,sal) values(1001, ‘Ramu’, ‘CLERK’,
4000);
Create a table with following structure and insert records into table &
Customer
CID CNAME CCITY
Creating Table:
SQL> create table customer(
cid number(4),
cname varchar2(20),
ccity varchar2(10) );
Output:
Table created.
Inserting a record:
SQL> Insert into Customer values(1001,'Ravi','Hyd');
Output:
1 row created.
Output:
old 1: Insert into Customer values(&cid,'&cname','&city')
new 1: Insert into Customer values(1002,'Krishna','Mumbai')
1 row created.
SQL> /
Enter value for cid: 1003
Enter value for cname: Prasad
Enter value for city: Bangalore
Output:
old 1: Insert into Customer values(&cid,'&cname','&city')
new 1: Insert into Customer values(1003,'Prasad','Bangalore')
1 row created.
Output:
1 row created.
Output:
1 row created.
Output:
CID CNAME CCITY
---------- -------------------- ----------
1001 Ravi Hyd
1002 Krishna Mumbai
1003 Prasad Bangalore
1004 Kishore
1005 Naresh
Output:
Table created.
Output:
5 rows created.
Output:
3 rows created.
4 rows created.
“Delete” Command:
• It is a DML Command.
• It is used to delete the records.
• Using this command we can delete single record, set of records or all
records.
Syntax :
Example:
Delete from emp where empno=7900;
Create a table with following structure, Insert the records and delete the
records:
Book
BookId BookName Author Price Publisher
1001 Oracle Kevin 1200 TATA MH
1002 Oracle Edward 1500 Techmedia
1003 Java James 1000 TATA MH
1004 C#.Net Steve 3500 Wrox
1005 Java Norton 2000 Techmedia
Creating Table:
SQL> Create Table Book(
Bookid Number(4),
BookName varchar2(10),
Author Varchar2(10),
price number(7,2),
publisher varchar2(10));
Output:
Table created.
“Update” Command:
• Is a DML Command.
• It is a used to update [modify] the records.
• It can be also used to perform calculations and store the result in
tables.
• Using this command we can update single record, a set of records &
all records.
Syntax:
Update <Table_Name>
Set <column-1>=<value-1>[, <column-2>=<value-2>, ……….]
[Where <Condition>];
Example:
Update emp set sal=4000,comm=500 where empno=7900;
Output:
1 row updated.
Updating job value as manager and sal as 5000 to the employee whose
empno is 7369 [Updating multiple field values of a record]:
SQL> Update emp set sal=5000, job='MANAGER' where empno=7369;
Output:
1 row updated.
Output:
4 rows updated.
SQL> /
Enter value for sal: 3000
Enter value for empno: 7934
Output:
old 1: Update emp set sal=&sal where empno=&empno
new 1: Update emp set sal=3000 where empno=7934
1 row updated.
Increasing 10% sal to the employees whose name is started with 's':
Update emp set sal=sal+sal*0.1 where ename like 'S%';
Increasing 10% sal to the employees who have greater than 40 years
experience:
Update emp set sal=sal+sal*0.1 where (sysdate-hiredate)/365>40;
Example-2:
Create a Table with following Structure & Insert the records. Then
calculate total and average marks:
Student
StdID SName M1 M2 M3 Total Avrg
1001 Ravi 40 80 60
1002 Sravan 66 44 77
Output:
Table created.
Output:
1 row created.
Calculating Total:
SQL> Update Student Set Total=M1+M2+M3;
Output:
2 rows updated.
Output:
2 rows updated.
Output:
Table created.
Inserting Records:
SQL> Insert into Employee(Empno,Ename,Job,BasicSal)
values(1001,'Sai','CLERK',4000);
Output:
1 row created.
Output:
1 row created.
Output:
2 rows updated.
Output:
EMPNO ENAME JOB BASICSAL TA DA HRA GROSS
---------- --------------- ---------- ---------- ---------- ---------- ---------- ----------
1001 Sai CLERK 4000 400 800 600 5800
1002 Krishna MANAGER 8000 800 1600 1200 11600
“Merge” Command:
• Is a DML Command.
• It is a combination of Update and Insert Commands.
• It is used to merge one table records into another table (Replica /
Duplicate Copy) based on condition.
• It avoids writing multiple DML Statements.
• It is used to deal with Replicas [Duplicate Copies].
Syntax:
Example:
Customer1
Cid Cname Ccity
1001 Ravi Hyd
1002 Kiran Mumbai
Output:
Table created.
Output:
1 row created.
Output:
CID CNAME CCITY
---------- -------------------- ----------
1001 Ravi Hyd
1002 Kiran Mumbai
Output:
Table created.
Output:
CID CNAME CCITY
---------- -------------------- ----------
1001 Ravi Hyd
1002 Kiran Mumbai
Output:
1 row created.
Updation:
SQL> Update Customer1 Set Ccity='Bangalore' where Cid=1001;
Output:
1 row updated.
Output:
3 rows merged.
Flashback Query:
Output:
Displays parameters list. Check undo_retention value in the list. Default
value is 900.
ACL Commands
“Grant” Command:
• It is an ACL Command.
• It is used to give permissions on database objects like tables, views
to other users.
Syntax :
Example:
Grant select on Std to raju;
Example:
Create user c##raju identified by kumar
Default tablespace users
Quota unlimited on users;
“Revoke” Command:
• It is an ACL Command.
• It is used to cancel the permissions on database objects like tables,
views from other users.
Syntax :
Example:
Revoke select on Std from raju;
Example-1:
Create two users with the names c##userA and c##userB. Log in as
c##userA. Create a table with following structure, insert the records, give
permissions on this table c##userB & Cancel the Permissions:
Student
Sid SName
Note:
Give your DBA password in place of nareshit. When Oracle software
installed, at that time you fad given one password. That is DBA
Password.
Output:
User created.
Output:
Grant succeeded.
Log in as DBA
Output:
Connected.
Output:
User created.
Output:
Grant succeeded.
Note:
Connect and Resource are the roles on which DBA is giving permission
to the userB.
Connect => This permission for log in
Resource => This permission for creating resources like tables
Output:
Connected.
Output:
USER is "C##USERA"
Output:
Table created.
Output:
1 row created.
Output:
1 row created.
Output:
SID SNAME
---------- --------------------
10 Ramu
20 Vijay
Output:
Grant succeeded.
Output:
Connected.
SID SNAME
---------- --------------------
10 Ramu
20 Vijay
Output:
ORA-01031: insufficient privileges
Output:
ORA-01031: insufficient privileges
Output:
ORA-01031: insufficient privileges
Note:
Above 3queries are giving same errors. Insufficient privileges. With this
we can understand that c##userB has select permission only. Insert,
Update and delete permissions had not given.
Log in as c##userA
Output:
Connected.
Output:
Grant succeeded.
Output:
1 row created.
Output:
1 row updated.
Output:
ORA-01031: insufficient privileges
Note:
With above 3 queries we can understand that c##UserB got permission
for updating data and inserting the record. But unable to delete the
record. Because, He has no “Delete” permission.
Output:
Grant succeeded.
Output:
Connected.
Output:
1 row deleted.
Output:
1 row created.
Output:
1 row updated.
Note:
With above 3 queries we can understand that now c##userB has all
permissions. He can see the data, insert, delete & update the records.
Output:
Connected.
Output:
Grant succeeded.
Note:
If C##userA gives permission “with Grant Option” to C##UserB,
Now C##UserB can give permission on this table to other users.
Output:
Connected.
Output:
Grant succeeded.
Note:
With above query c##userB is giving permission on c##userA’s student
table to other user “c##oracle7am”.
Output:
Connected.
Output:
Revoke succeeded.
Output:
Connected.
SID SNAME
---------- --------------------
20 Srinu
30 Ravi
40 Sai
Output:
ORA-01031: insufficient privileges
Note:
With above query we can understand that c##userB unable to delete
the record. Because. “Delete” permission has been cancelled by
c##userA.
Output:
Connected.
Output:
Revoke succeeded.
Output:
Connected.
Output:
ORA-01031: insufficient privileges
Output:
ORA-01031: insufficient privileges
Note:
With above 2 queries we can understand that insert & update
permissions canceled.
Output:
Connected.
Output:
Revoke succeeded.
Output:
Grant succeeded.
Output:
Revoke succeeded.
Output:
Grant succeeded.
Output:
Revoke succeeded.
Changing Password:
Login as DBA
Output:
User altered.
Dropping a User:
Log in as DBA
Output:
User dropped.
TCL Commands
“Commit” Command:
• It is a TCL Command.
• It is used to make the changes permanent. It means, it is used to save
the transactions. When we perform Insert or delete or update
operation, it will be performed on “Oracle Instance”. To apply these
changes to “Oracle Database” permanently, we use “commit”
command.
• After commit, we cannot use rollback.
Syntax :
Commit;
Example:
Insert into student values(1234, ‘Ravi’);
Commit;
Note:
Not only one. But also, all the previous actions will be saved
permanently in “Oracle Database” when we use “Commit” command.
“Rollback” Command:
• It is a TCL Command.
• It is used to cancel the previous actions. It means, it will undo the
previous actions.
• It must be used before “Commit” to cancel the previous actions.
After commit, we cannot use “Rollback” Command.
Syntax :
Example:
Insert into student values(1234, ‘Ravi’);
Rollback;
Note:
Not only one. But also, all the previous actions will be canceled when
we use “Rollback” command [Uncommitted actions will be cancelled].
“SavePoint” Command:
• It is a TCL Command.
• It is used to set margin for “Rollback”. When rollbacked using the
Save_Point_Name, the actions will be cancelled up to this point only.
• Save_Point_name must be unique.
• If we define same Save_Point_Name again, previous SavePoint will
be replaced with new SavePoint. This new point will be considered
as SavePoint. Previous savepoint [old savepoint] will be gone.
Syntax :
SavePoint <Save_Point_name>;
Example:
Insert into student values(1234, ‘Ravi’);
SavePoint NareshIT;
Insert into student values(1235, ‘Sai’);
Rollback To NareshIT;
Example-1:
Create a table with following structure, perform manipulations, save
the manipulations, and cancel the manipulations:
Product
Pid PName Qunatity_on_Hand
Output:
Table created.
Output:
1 row created.
Output:
1 row created.
SQL> Commit;
Output:
Commit complete.
Note:
Above two insertions will be saved permanently
Output:
1 row created.
Output:
1 row created.
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 2000
1002 Pen Drive 3000
1003 Monitor 1500
1004 Keyboard 2500
SQL> Rollback;
Output:
Rollback complete.
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 2000
1002 Pen Drive 3000
Note:
Previous two insertions are canceled because of “Rollback”
Using Savepoint:
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 2000
1002 Pen Drive 3000
Output:
Savepoint created.
Inserting a Record:
SQL> Insert into product values(2001,'SMPS',4000);
Output:
1 row created.
Output:
Savepoint created.
Updating a Record:
SQL> Update product set Quantity_On_Hand=5000 where pid=1001;
Output:
1 row updated.
Output:
Savepoint created.
Deleting a Record:
SQL> Delete from product where pid=1002;
Output:
1 row deleted.
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 5000
2001 SMPS 4000
Output:
Rollback complete.
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 5000
1002 Pen Drive 3000
2001 SMPS 4000
Note:
Rollbacked up to p3. Deleted record “1002”. Came again in table. It
means, deletion cancelled. But, not cancelled insertion and updation.
Output:
Rollback complete.
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 2000
1002 Pen Drive 3000
2001 SMPS 4000
Note:
Rollbacked up to p2. Deletion and updation canceled.
Output:
Rollback complete.
Output:
PID PNAME QUANTITY_ON_HAND
---------- --------------- ----------------
1001 Hard Disk 2000
1002 Pen Drive 3000
Note:
Rollbacked up to p1. Deletion, updation and insertion canceled.
Built-In Functions
• Conversion Functions
• Date Functions
Syntax:
Sqrt(<Number>)
Ex:
Sqrt(100) => 10
Sqrt(81) => 9
Syntax:
Power(<Number>, <Power>)
Ex:
Power(2,3) => 8
Power(5,2) => 25
Syntax:
Abs(<Number>)
Ex:
Abs(5) => 5
Abs(-5) => 5
Syntax:
Sign(<Number>)
Ex:
Sign(5) => 1
Sign(-5) => -1
Sign(0) => 0
Syntax:
Mod(<Number>, <Divisor>)
Ex:
Mod(5,2) => 1
Mod(10,6) => 4
Syntax:
Sin(<Angle>)
Ex:
Sin(90*3.14/180) => 1
Syntax:
Cos(<Angle>)
Ex:
Cos(0*3.14/180) => 1
Syntax:
Tan(<Angle>)
Ex:
Tan(45*3.14/180) => 1
Syntax:
Ln(<Number>)
Ex:
Ln(7) => 1.94591015
Ln(10) => 2.30258509
Syntax:
Log(<Number>, <Base>)
Ex:
Log(10,10) => 1
Syntax:
Trunc(<Number> [, <Number_Of_Decimal_Places>])
Ex:
Trunc(123.4567) => 123
Trunc(123.4567, 1) => 123.4
Trunc(123.4567, 2) => 123.45
Syntax:
Round(<Number>, <Number of Decimal_Places>)
Ex:
Round(123.4567) => 123
Round(123.6567) => 124
Round(123.5567) => 124
Round(123.4567,2) => 123.46
Round(123.4547,2) => 123.45
Round(123.4557,2) => 123.46
Round(123.4557,-1) => 120
Round(126.4557,-1) => 130
Round(123.4557,-2) => 100
Round(126.4557,-2) => 100
Round(153.4557,-1) => 150
Round(153.4557,-2) => 200
Syntax:
Ceil(<Number>)
Ex:
Ceil(123.4567) => 124
Syntax:
Floor(<Number>)
Ex:
Ceil(123.4567) => 123
Function Purpose
Name
Upper() Returns string in upper case [All Capital Letters].
Syntax:
Upper(<String>)
Ex:
Upper(‘raju’) => RAJU
Syntax:
Lower(<String>)
Ex:
Lower(‘RAJU’) => raju
Syntax:
Initcap(<String>)
Ex:
Initcap(‘RAJ KUMAR’) => Raj Kumar
Syntax:
Concat(<String-1>, <String-2>)
Ex:
Concat(‘Raj’, ‘Kumar’) => RajKumar
Concat(Concat(‘Raj’, ‘ ’), ‘Kumar’) => Raj Kumar
Syntax:
Length(<String>)
Ex:
Length(‘Sai’) => 3
Lemgth(‘Arun’) => 4
Length(‘Sai Teja’) => 8
Syntax:
Lpad(<String>, <Size> [, <Char / Chars>])
Ex:
Lpad(‘raju’, 10) => raju -- 6 spaces & raju
Syntax:
Rpad(<String>, <Size> [, <Char / Chars>])
Ex:
Rpad(‘raju’, 10) => raju -- raju & 6 spaces
Ltrim() Returns the string by removing all characters from left side
which are in character set. Default char is ‘ ’ [Space].
Syntax:
LTrim(<String> [, <Char_Set>])
Ex:
LTrim(‘ raju’) => raju -- removes left side spaces
Syntax:
LTrim(<String> [, <Char_Set>])
Ex:
RTrim(‘raju ’) => raju -- removes right side spaces
RTrim('Raju@@@@', '@') => Raju
RTrim('Rajuabcabcaabbcc','abc') => Raju
Syntax:
Trim(<Both / Leading / Trailing> <char> from <string>)
Ex:
raju
Trim(‘ raju ’) => -- removes left & right side
spaces
Trim(Leading ‘@’ from ‘@@@@raju’) => raju
Trim(Trailing ‘@’ from ‘raju@@@@’) => raju
Trim(Both '@' from '@@@raju@@@') => raju
Syntax:
Substr(<String>, <Position> [, <Number_Of_Chars>])
Ex:
substr('raj kumar',5) => kumar
substr('raj kumar',1,3) => raj
substr('raj kumar',1,5) => raj k
substr('raj kumar',5,3) => kum
substr('raj kumar',-4) => umar
substr('raj kumar',-4,3) => uma
Syntax:
Instr(<String>, <Sub-String> [, <Position>, <Occurrence>])
Ex:
Instr('This is his wish','is') => 3
Instr('This is his wish','is',4) => 6
Instr('This is his wish','is',7) => 10
Instr('This is his wish','is',11) => 14
Syntax:
Replace(<String>, <Search_String>, <Replace_String>)
Ex:
Replace('raj kumar','raj','sai') => sai kumar
Replace('abcabcxyzaabbccabc','abc','pqr') =>
pqrpqrxyzaabbccpqr
Syntax:
Translate(<String>, <From_String>, <To_String>)
Ex:
Translate('abcabcxyzaabbccabc','abc','pqr') =>
pqrpqrxyzppqqrrpqr
Syntax:
Soundex(<String>)
Ex:
Select ename from emp where Soundex(Ename) =
Soundex(‘Smyt’); => SMITH
Syntax:
ASCII(<Char>)
Ex:
ASCII('A') => 65
ASCII('a') => 97
Syntax:
Chr(<Number>)
Ex:
Chr(65) => A
Chr(97) => a
Syntax:
Sum(<Column>)
Ex:
Select Sum(Sal) from emp;
Syntax:
Avg(<Column>)
Ex:
Select Avg(Sal) from emp;
Syntax:
Max(<Column>)
Ex:
Select Max(Sal) from emp;
Syntax:
Min(<Column>)
Ex:
Select Min(Sal) from emp;
Syntax:
Select Count(Comm) from emp; -- cannot count nulls
Select Count(Empno) from emp; --cannot count nulls
Select Count(*) from emp; --counts number of records
Conversion Functions:
Syntax:
To_Char(<Date> [, Format])
Ex:
To_Char(Sysdate) => 12-JUL-21
To_Char(Sysdate,'dd') => 12
To_Char(Sysdate,'mm') => 07
To_Char(Sysdate,'yy') => 21
To_Char(Sysdate,'yyyy') => 2021
To_Char(Sysdate,'hh:mi AM') => 12:53 AM
To_Char(Sysdate,'Q') => 3
To_Char(Sysdate,'d') => 2
To_Char(Sysdate,'dy') => mon
To_Char(Sysdate,'day') => Monday
To_Char(Sysdate,'CC') => 21
Syntax:
To_Date(<String> [, <Format>])
Ex:
To_Date('23 december 2020') => 23-DEC-20
To_Date('25-Dec-2019') => 25-DEC-19
To_Date('25/12/2019','dd/mm/yyyy') => 25-DEC-19
Syntax:
To_Number(<String> [, <Format>])
Ex:
To_Number(‘123’) => 123
TO_Number(‘$1,000’, ‘L9,999’) => 1000
Syntax:
To_Char(<Number> [, <Format>)
Ex:
To_Char(123) => 123
To_Char(2000,'L9,999.99') => $2,000.00
To_Char(2000,'C9,999.99') => USD2,000.00
Date Functions:
Ex:
Sysdate => 12-JUL-21
Syntax:
Add_Months(<Date>, <Number_Of_Months>)
Ex:
Add_Months(sysdate,2) => 12-SEP-21
Add_Months(sysdate,-2) => 12-MAY-21
Syntax:
Next_Day(Date, <Week_day_name>)
Ex:
Next_Day(sysdate, ‘fri’) => 16-JUL-21
Syntax:
Last_Day(<Date>)
Ex:
Last_Day(sysdate) => 31-JUL-21
Syntax:
Months_Between(<Date-1>, <Date-2>)
Ex:
Months_Between(sysdate, ‘12-APR-21’) => 3
Function Purpose
Name
User Returns Current Username.
Ex:
User => C##Oracle7AM
Ex:
UId => 111
Syntax:
Greatest(<n1>,<n2>,………)
Ex:
Greatest(10,20,50,30) => 50
Syntax:
Least(<n1>,<n2>,………)
Ex:
Least(10,20,50,40) => 10
Syntax:
NVL(<First_Value>, <Second_Value>)
Ex:
NVL(100,200) => 100
NVL(Null,200) => 200
NVL2() It returns Second Value if first value is not null. It returns
third value if the first value is null. It is used to replace
nulls and not nulls.
Syntax:
NVL2(<first_value>, <second_value>, third_Value>)
Ex:
NVL2(100,200,300) => 200
NVL2(Null,200,300) => 300
Syntax:
VSize(<value>)
Ex:
VSize(‘raju’) => 4
Syntax:
Rank() over(order by <column_name> Asc/ Desc [,…..])
Ex:
Rank() over(order by sal desc) =>
Syntax:
Dense_Rank() over(order by <column_name> Asc/ Desc
[,…..])
Ex:
Dense_Rank() over(order by sal desc) =>
Syntax:
Row_Number() over(order by <column_name> Asc/
Desc [,…..])
Ex:
Row_Number() over(order by sal desc) =>
Output:
POWER(2,3)
----------
8
Output:
POWER(5,2) POWER(3,3)
---------- ----------
25 27
Output:
SQRT(100)
----------
10
Output:
SQRT(81) SQRT(144)
---------- ----------
9 12
Finding 5 mod 2:
SQL> Select Mod(5,2) from dual;
Output:
MOD(5,2)
----------
1
Output:
MOD(10,6) MOD(20,7)
---------- ----------
4 6
Output:
SIN(90*3.14/180)
----------------
.999999683
Output:
COS(0*3.14/180) TAN(45*3.14/180)
--------------- ----------------
1 .99920399
Output:
LN(7)
----------
1.94591015
Output:
LOG(10,10)
----------
1
Examples on Trunc():
1. SQL> Select Trunc(123.4567) from dual;
Output:
TRUNC(123.4567)
---------------
123
Output:
TRUNC(123.4567,2)
-----------------
123.45
Output:
TRUNC(123.4567,3)
-----------------
123.456
Output:
TRUNC(123.4567,-1)
------------------
120
120……………………….123.4567…………………………..130
Output:
TRUNC(123.4567,-2)
------------------
100
100……………………123.4567……………………….200
Examples on Round():
Output:
ROUND(123.4567)
---------------
123
Output:
ROUND(123.6567)
---------------
124
Output:
ROUND(123.5567)
---------------
124
Output:
ROUND(123.5567,2)
-----------------
123.56
Output:
ROUND(123.5547,2)
-----------------
123.55
Output:
ROUND(123.5557,2)
-----------------
123.56
Output:
ROUND(123.4567,-1)
------------------
120
Output:
ROUND(126.6567,-1)
------------------
130
-1 means, rounds to 10s
120……………………..126.6567…………………….130
6 is there at 1’s position. >5. So, rounds to 130
Output:
ROUND(125.6567,-1)
------------------
130
120……………….125.6567………………………130
5 is there 1’s position. Eqauls to 5. So rounds to 130
Output:
ROUND(124.6567,-1)
------------------
120
120………………124.6567………………………..130
4 is there 1’s position. So, rounds to 120
Output:
ROUND(123.6567,-2)
------------------
100
Output:
ROUND(152.6567,-2)
------------------
200
Output:
ROUND(150.6567,-2)
------------------
200
Output:
ROUND(149.6567,-2)
------------------
100
Example on Ceil():
SQL> Select Ceil(123.456) from dual;
Output:
CEIL(123.456)
-------------
124
Example on Floor():
SQL> Select Floor(123.456) from dual;
Output:
FLOOR(123.456)
--------------
123
Floor() function always gives lower integer value. So, Printed 123
Output:
Avrg Score
----------
33.3333333
46.6666667
52.3076923
45
Output:
Avrg Score
----------
33
47
52
45
Output:
Avrg Score
----------
33.33
46.67
52.31
45
Output:
Avrg Score
----------
33
46
52
45
Output:
Avrg Score
----------
33.33
46.66
52.3
45
Avrg Score
----------
33.333
46.666
52.307
45
Output:
Avrg Score
----------
33
46
52
45
Output:
Avrg Score
----------
34
47
53
45
Sum of Salaries
---------------
29025
Average Salary
--------------
2073.21429
Average Salary
--------------
2073.21
Average Salary
--------------
2074
Average Salary
--------------
2073
Average Salary
--------------
2073
Average Salary
--------------
2073.21
Min Salary
----------
800
Max Salary
----------
5000
COUNT(COMM)
-----------
3
Note:
Count(Comm) cannot count nulls.
COUNT(EMPNO)
------------
14
COUNT(*)
----------
14
Output:
ENAME
----------
KING
Output:
ENAME
----------
SMITH
Output:
MAX(SAL)
----------
3000
Output:
ENAME
----------
SCOTT
FORD
Output:
Number Of Clerks
----------------
4
Output:
Number Of Managers
----------------
3
Output:
Number Of Employees
-------------------
5
Output:
UPPE
----
RAJU
Output:
LOWE
----
raju
Output:
INITCAP('
---------
Raj Kumar
Output:
CONCAT('
--------
rajkumar
Output:
CONCAT(CO
---------
raj kumar
(Or)
Output:
'RAJ'||''
---------
raj kumar
Getting space between two names and display initial letters as capital in
name:
SQL> Select Initcap(concat(concat('raj', ' '),'kumar')) from dual;
Output:
INITCAP(C
---------
Raj Kumar
Output:
UPPER(ENAM
----------
SMITH
ALLEN
.
.
Output:
LOWER(ENAM
----------
smith
allen
.
.
Output:
INITCAP(EN
----------
Smith
Allen
.
.
Concatenating First Name and Last Name and getting name’s initial
letters as capital:
Output:
NAME
---------------------
Sachin Tendulkar
Virat Kohli
Rohit Sharma
Rahul Dravid
Output:
UPPER(FNAM
----------
SACHIN
VIRAT
ROHIT
RAHUL
Output:
LOWER(FNAM
----------
sachin
virat
rohit
rahul
Output:
Table altered.
Output:
4 rows updated.
Output:
Table altered.
Output:
PID PNAME
---------- ------------------------------
1001 Sachin Tendulkar
1002 Virat Kohli
1003 Rohit Sharma
1004 Rahul Dravid
Output:
LENGTH('RAJU')
--------------
4
Output:
ENAME Ename Length
---------- ------------
SMITH 5
ALLEN 5
WARD 4
…
Output:
ENAME
----------
WARD
KING
FORD
[Or]
Output:
ENAME
----------
WARD
KING
FORD
PID PNAME
---------- ------------------------------
1001 Sachin Tendulkar
1002 Virat Kohli
1003 Rohit Sharma
1004 Rahul Dravid
PNAME
------------------------------
Rohit Sharma
Rahul Dravid
Displaying player names whose names are having more than 12 chars:
SQL> Select pname from player where length(pname)>12;
PNAME
------------------------------
Sachin Tendulkar
Output:
SUBST
-----
kumar
Output:
SUB
---
raj
Output:
SUBST
-----
raj k
Output:
SUB
---
uma
Output:
SUBS
----
umar
Output:
SUBS
----
umar
Output:
SUB
---
uma
Output:
SUBST
-----
kumar
Output:
SUB
---
kum
Note:
-ve position => Position Number From Right Side
+ve Position => Position Number From Left Side
Generating Email IDs by taking emp name’s first 3 chars and empno’s last
3 digits:
SQL> Select
substr(Ename,1,3) || substr(empno,-3,3) || '@nareshit.com'
As "E-Mail ID" from emp;
Output:
E-Mail ID
-------------------------------------
[email protected]
[email protected]
[email protected]
…
…
Output:
ENAME
----------
SMITH
SCOTT
(Or)
Output:
ENAME
----------
SMITH
SCOTT
Retrieving the emp record whose name is ‘blake’ and when we don’t
know whether the name is in upper case or lower case:
SQL> Select ename, sal from emp where lower(ename) = 'blake';
Output:
ENAME SAL
---------- ----------
BLAKE 2850
Output:
ENAME
----------
WARD
FORD
(Or)
Output:
ENAME
----------
WARD
FORD
Displaying employee names whose names are started and ended with
same letter:
Output:
1 row created.
Output:
1 row created.
Output:
ENAME
----------
DAVID
SRINIVAS
Output:
INSTR('THISISHISWISH','IS')
---------------------------
3
Output:
INSTR('THISISHISWISH','IS',4)
-----------------------------
6
Output:
INSTR('THISISHISWISH','IS',7)
-----------------------------
10
Output:
INSTR('THISISHISWISH','IS',11)
------------------------------
14
Output:
INSTR('THISISHISWISH','IS',15)
------------------------------
0
Note:
If substring is not found in the string, then it returns 0
Output:
INSTR('THISISHISWISH','IS',-1)
------------------------------
14
Note:
Positive Position => Starts searching from left side
Negative Position => Starts searching from right side
Output:
INSTR('THISISHISWISH','IS',-4)
------------------------------
10
Output:
INSTR('THISISHISWISH','IS',-4,2)
--------------------------------
6
Output:
ENAME
----------
ADAMS
JAMES
(or)
Output:
ENAME
----------
ADAMS
JAMES
Output:
LPAD('RAJU
----------
******raju
Output:
LPAD('RAJU',15,
---------------
@#@#@#@#@#@raju
Output:
RPAD('RAJU
----------
raju******
Output:
RPAD('RAJU',15,
---------------
raju@#@#@#@#@#@
Output:
LPAD('RAJU
----------
raju
Output:
RPAD('RAJ',10)|
---------------
raj kumar
Output:
LPAD('*',1
----------
**********
MESSAGE
------------------------------------
amount credited from the acno XXXXXX6789
Output:
LTRIM('RAJ')
------------
raj kumar
Output:
RTRIM('RAJ')|
-------------
rajkumar
Output:
TRIM('RA
--------
rajkumar
Output:
LTRIM('@@@@@R
-------------
@@@@@raju@@@@
Output:
LTRIM('@
--------
raju@@@@
Output:
RTRIM('@@
---------
@@@@@raju
Output:
LTRIM('@#@####@@@R
------------------
raju@#@####@@@@###
Output:
RTRIM('@#@####
--------------
@#@####@@@raju
Output:
TRIM(LEAD
---------
raju@@@@@
Output:
TRIM(TRA
--------
@@@@raju
Output:
TRIM
----
raju
Output:
LTRIM('RAJU@NARES
-----------------
[email protected]
Output:
RTRIM('RAJU@N
-------------
raju@nareshit
Output:
RTRI
----
raju
Output:
LTRIM('O
--------
F11 Pro
Output:
REPLACE('SAI
------------
rama krishna
Output:
REPLACE('XYZXYZXXYYZZ
---------------------
abcabcxxyyzzabcxxyyzz
Output:
TRANSLATE('XYZXYZXXYY
---------------------
abcabcaabbccabcaabbcc
Output:
ENAME SALARY
---------- ----------
SMITH +!!
ALLEN @&!!
WARD @#^!
..
Output:
ASCII('A')
----------
65
Output:
ASCII('A') ASCII('Z')
---------- ----------
97 122
Output:
C
-
A
Output:
CC
--
az
Output:
EMPNO ENAME
---------- ----------
7369 SMITH
Output:
EMPNO ENAME
---------- ----------
7788 SCOTT
Output:
REVE
----
umar
Output:
ENAME Rev Name
---------- ----------
SMITH HTIMS
ALLEN NELLA
WARD DRAW
JONES SENOJ
.
.
Output:
TO_C
----
2021
Output:
TO
--
21
Output:
T
-
1
TO_
---
021
Output:
TO_CHAR(SYSDATE,'YEAR')
------------------------------------------
twenty twenty-one
Output:
TO
--
07
Output:
TO_CHAR(SYSD
------------
jul
Output:
TO_CHAR(SYSDATE,'MONTH')
------------------------------------
july
Output:
TO_CHAR(SYSD
------------
JUL
Output:
TO_CHAR(SYSDATE,'MONTH')
------------------------------------
JULY
Getting date two digits [day number in month] from today’s date:
SQL> Select to_char(sysdate,'dd') from dual;
Output:
TO
--
15
Output:
TO_
---
196
Output:
T
-
5
Output:
TO_CHAR(SYSD
------------
thu
Output:
TO_CHAR(SYSDATE,'DAY')
------------------------------------
thursday
Output:
TO_CHAR(SYSD
------------
THU
Output:
TO_CHAR(SYSDATE,'DAY')
------------------------------------
THURSDAY
Output:
TO_CHAR(
--------
11:41 AM
Output:
T
-
3
Output:
T
-
3
Output:
TO
--
28
TO
--
21
Output:
TO_CH
-----
21 AD
Output:
ENAME HIREDATE
---------- ---------
SCOTT 09-DEC-82
MILLER 23-JAN-82
[Or]
Output:
ENAME HIREDATE
---------- ---------
SCOTT 09-DEC-82
MILLER 23-JAN-82
Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
SCOTT 09-DEC-82
ADAMS 12-JAN-83
MILLER 23-JAN-82
Output:
ENAME HIREDATE
---------- ---------
WARD 22-FEB-81
[Or]
Output:
ENAME HIREDATE
---------- ---------
WARD 22-FEB-81
[Or]
Output:
ENAME HIREDATE
---------- ---------
WARD 22-FEB-81
Output:
ENAME HIREDATE
---------- ---------
JONES 02-APR-81
BLAKE 01-MAY-81
CLARK 09-JUN-81
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
JONES 02-APR-81
SCOTT 09-DEC-82
ADAMS 12-JAN-83
JAMES 03-DEC-81
FORD 03-DEC-81
MILLER 23-JAN-82
Output:
ENAME HIREDATE
---------- ----------
SMITH 12/17/1980
ALLEN 02/20/1981
.
.
Output:
ENAME HIREDATE
---------- ----------
SMITH 17/12/1980
ALLEN 20/02/1981
Output:
TO_DATE('
---------
20-DEC-21
Output:
TO_DATE('
---------
02-DEC-21
Output:
TO_DATE('
---------
23-DEC-20
Output:
TO_C
----
2020
Output:
TO_
---
dec
Output:
TO_CHAR(T
---------
wednesday
Output:
SYSDATE+1
---------
25-JUL-21
Output:
TO_DATE('
---------
26-JUN-21
Output:
TO_CHAR(T
---------
friday
Output:
TO_CHAR(T
---------
tuesday
Output:
1 row created.
Output:
TO_CHAR(5000,'L999
------------------
$5000.00
Output:
TO_CHAR(5000,'C
---------------
USD5000.00
Output:
PARAMETER VALUE
------------------------------------------ --------------------
NLS_LANGUAGE AMERICAN
NLS_TERRITORY AMERICA
NLS_CURRENCY $
.
Output:
Session altered.
Output:
Session altered.
Output:
TO_CHAR(5000,'L999
------------------
RS5000.00
Output:
TO_CHAR(5000,'C
---------------
INR5000.00
Output:
ENAME SALARY
---------- -------------------
SMITH RS800.00
ALLEN RS1600.00
WARD RS1250.00
.
.
.
.
Output:
ENAME SALARY
---------- ----------------
ccc
SMITH INR800.00
ALLEN INR1600.00
WARD INR1250.00
.
.
TO_CHAR
-------
001234
Output:
TO_NUMBER('123')
----------------
123
Output:
TO_NUMBER('$5000.00','L9999.99')
--------------------------------
5000
TO_NUMBER('USD5000.00','C9999.99')
----------------------------------
5000
Output:
SYSDATE
---------
16-JUL-21
Output:
SYSTIMESTAMP
---------------------------------------------------------------------------
16-JUL-21 04.20.34.223000 PM +05:30
Output:
TO_CHAR(
--------
04:21 PM
Output:
TO_CH
-----
16:21
Output:
TO_CHAR(SY
----------
16/07/2021
Output:
TO_CHAR(
--------
04:22 PM
Output:
TO_CH
-----
16:22
Output:
ADD_MONTH
---------
16-SEP-21
Output:
ADD_MONTH
---------
16-MAY-21
Output:
ADD_MONTH
---------
20-DEC-20
Output:
ADD_MONTH
---------
20-AUG-20
Output:
1 row created.
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2001 Krishna 16-JUL-21
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2001 Krishna 16-JUL-21
Output:
1 row created.
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 15-JUL-21
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 15-JUL-21
Output:
1 row created.
Displaying emp records who joined one month ago on same date:
SQL> Select empno, ename, hiredate from emp
where to_char(hiredate,'dd/mm/yyyy') =
to_char(Add_Months(sysdate,-1),'dd/mm/yyyy');
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 16-JUN-21
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 16-JUN-21
Output:
1 row created.
Displaying employee records who joined one year ago on same date:
SQL> Select empno, ename, hiredate from emp
where to_char(hiredate,'dd/mm/yyyy') =
to_char(Add_Months(sysdate,-12),'dd/mm/yyyy');
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2003 Sai 16-JUL-20
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2003 Sai 16-JUL-20
Output:
ENAME HIREDATE
---------- ---------
Ganesh 15-JUL-21
Displaying employee record who joined one month ago on same date
using ‘Interval’ Expression:
SQL> Select ename, hiredate from emp
where trunc(hiredate) = trunc(sysdate-interval '1' month);
Output:
ENAME HIREDATE
---------- ---------
Ganesh 16-JUN-21
Displaying employee record who joined one month ago on same date
using ‘Interval’ Expression:
SQL> Select ename, hiredate from emp
where trunc(hiredate) = trunc(sysdate-interval '1' year);
Output:
ENAME HIREDATE
---------- ---------
Sai 16-JUL-20
Output:
Table created.
Output:
1 row created.
Output:
1 row created.
Output:
1 row created.
Output:
1 row created.
Output:
DATEID AMOUNT
--------- ----------
16-JUL-21 10000
15-JUL-21 10000
16-JUN-21 10000
16-JUL-20 10000
Output:
DATEID AMOUNT
--------- ----------
16-JUL-21 10000
Output:
DATEID AMOUNT
--------- ----------
15-JUL-21 10000
Output:
DATEID AMOUNT
--------- ----------
16-JUN-21 10000
(Or)
Output:
DATEID AMOUNT
--------- ----------
16-JUL-20 10000
Output:
DATEID AMOUNT
--------- ----------
16-JUL-20 10000
(Or)
Output:
DATEID AMOUNT
--------- ----------
16-JUL-20 10000
Output:
Table created.
Output:
1 row created.
Output:
1 row created.
Output:
1 row created.
Output:
3 rows updated.
(Or)
Output:
3 rows updated.
Output:
EMPNO DOB HIREDATE RETIREMEN
---------- --------- --------- ---------
1001 12-JAN-95 01-JUN-18 12-JAN-55
1002 12-JAN-00 20-OCT-20 12-JAN-60
1003 25-DEC-90 20-AUG-15 25-DEC-50
Output:
Table created.
Inserting records into IndiaCMs Table:
SQL> Insert into IndiaCMs(State, CM_Name, Term_Starting_Date)
values('Telangana','KCR','13-DEC-2018');
Output:
1 row created.
Output:
1 row created.
Output:
STATE CM_NAME TERM_STAR TERM_ENDI
--------------- -------------------- --------- ---------
Telangana KCR 13-DEC-18
AP YS JAGAN 30-MAY-19
Output:
2 rows updated.
(Or)
SQL> Update IndiaCMs Set Term_Ending_Date =
Term_Starting_Date+Interval '5' Year;
Output:
2 rows updated.
Displaying all records:
SQL> Select * from IndiaCMs;
Output:
LAST_DAY(
---------
31-JUL-21
Output:
LAST_DAY(
---------
01-AUG-21
Output:
LAST_DAY(
---------
01-JUN-21
Finding Previous month last date:
SQL> select last_day(add_months(sysdate,-1)) from dual;
Output:
LAST_DAY(
---------
30-JUN-21
Output:
LAST_DAY(
---------
01-JUL-21
Output:
NEXT_DAY(
---------
19-JUL-21
Output:
NEXT_DAY(
---------
26-JUL-21
Output:
NEXT_DAY(
---------
02-AUG-21
Output:
NEXT_DAY(
---------
07-JUN-21
Output:
ENAME EXPERIENCE
---------- ----------
SMITH 41
ALLEN 40
WARD 40
JONES 40
MARTIN 40
BLAKE 40
CLARK 40
SCOTT 39
KING 40
Output:
AGE
----------
48
Output:
YEARS MONTHS
---------- ----------
48 2
Output:
YEARS MONTHS
---------- ----------
40 7
40 4
40 4
40 3
39 9
40 2
40 1
38 7
39 8
39 10
Output:
USER
--------------------------------------------------------------------------------
C##ORACLE7AM
Output:
UID
----------
111
Output:
GREATEST(100,200,300)
---------------------
300
Output:
LEAST(100,200,300)
------------------
100
Output:
VSIZE('RAJU') VSIZE('SAI')
------------- ------------
4 3
Output:
NVL(100,200)
------------
100
Output:
NVL(NULL,200)
-------------
200
Output:
NULL+200
----------
Output:
NVL(NULL,100)+200
-----------------
300
Output:
ENAME SAL COMM Total Salary
---------- ---------- ---------- ------------
SMITH 800 800
ALLEN 1600 300 1900
WARD 1250 500 1750
JONES 2975 2975
MARTIN 1250 1400 2650
Output:
ENAME SAL COMM
---------- ---------- ----------------------------------------
SMITH 800 N/A
ALLEN 1600 300
WARD 1250 500
JONES 2975 N/A
MARTIN 1250 1400
BLAKE 2850 N/A
Output:
STDID SNAME M1 M2 M3
---------- -------------------- ---------- ---------- ----------
2001 aa 55 77
1001 Ravi 40 80 60
1002 Sravan 66 44 77
Output:
SNAME M3
-------------------- ----------------------------------------
aa ABSENT
Ravi 60
Sravan 77
Output:
NVL2(100,200,300)
-----------------
200
Output:
NVL2(NULL,200,300)
------------------
300
Output:
ENAME COMM
---------- ----------
SMITH 1000
ALLEN 500
WARD 700
JONES 1000
MARTIN 1600
BLAKE 1000
CLARK 1000
Output:
EMPNO ENAME SAL RANK
---------- ---------- ---------- ----------
7839 KING 5000 1
7902 FORD 3000 2
7788 SCOTT 3000 2
7566 JONES 2975 4
7698 BLAKE 2850 5
7782 CLARK 2450 6
7499 ALLEN 1600 7
7844 TURNER 1500 8
7934 MILLER 1300 9
7521 WARD 1250 10
7654 MARTIN 1250 10
7876 ADAMS 1100 12
7900 JAMES 950 13
7369 SMITH 800 14
Output:
EMPNO ENAME SAL RANK
---------- ---------- ---------- ----------
7839 KING 5000 1
7902 FORD 3000 2
7788 SCOTT 3000 2
7566 JONES 2975 3
7698 BLAKE 2850 4
7782 CLARK 2450 5
7499 ALLEN 1600 6
7844 TURNER 1500 7
7934 MILLER 1300 8
7521 WARD 1250 9
7654 MARTIN 1250 9
7876 ADAMS 1100 10
7900 JAMES 950 11
7369 SMITH 800 12
Output:
ENAME HIREDATE SAL RANK
---------- --------- ---------- ----------
KING 17-NOV-81 5000 1
FORD 03-DEC-81 3000 2
SCOTT 09-DEC-82 3000 3
JONES 02-APR-81 2975 4
BLAKE 01-MAY-81 2850 5
CLARK 09-JUN-81 2450 6
Date Functions:
Ex:
Sysdate => 12-JUL-21
Syntax:
Add_Months(<Date>, <Number_Of_Months>)
Ex:
Add_Months(sysdate,2) => 12-SEP-21
Add_Months(sysdate,-2) => 12-MAY-21
Syntax:
Next_Day(Date, <Week_day_name>)
Ex:
Next_Day(sysdate, ‘fri’) => 16-JUL-21
Syntax:
Last_Day(<Date>)
Ex:
Last_Day(sysdate) => 31-JUL-21
Syntax:
Months_Between(<Date-1>, <Date-2>)
Ex:
Months_Between(sysdate, ‘12-APR-21’) => 3
Function Purpose
Name
User Returns Current Username.
Ex:
User => C##Oracle7AM
Ex:
UId => 111
Syntax:
Greatest(<n1>,<n2>,………)
Ex:
Greatest(10,20,50,30) => 50
Syntax:
Least(<n1>,<n2>,………)
Ex:
Least(10,20,50,40) => 10
NVL() Returns first value if first value is not null. Returns
second value if first value is null. It is used to replace
null value with other value.
Syntax:
NVL(<First_Value>, <Second_Value>)
Ex:
NVL(100,200) => 100
NVL(Null,200) => 200
NVL2() It returns Second Value if first value is not null. It returns
third value if the first value is null. It is used to replace
nulls and not nulls.
Syntax:
NVL2(<first_value>, <second_value>, third_Value>)
Ex:
NVL2(100,200,300) => 200
NVL2(Null,200,300) => 300
VSize() Returns number of bytes in internal representation of
value.
Syntax:
VSize(<value>)
Ex:
VSize(‘raju’) => 4
Syntax:
Rank() over(order by <column_name> Asc/ Desc [,…..])
Ex:
Rank() over(order by sal desc) =>
Syntax:
Dense_Rank() over(order by <column_name> Asc/ Desc
[,…..])
Ex:
Dense_Rank() over(order by sal desc) =>
Syntax:
Row_Number() over(order by <column_name> Asc/
Desc [,…..])
Ex:
Row_Number() over(order by sal desc) =>
applies record number for every row. Highest salary
record number is 1. Second Highest Salary record
number is 2 and so on.
Output:
POWER(2,3)
----------
8
Output:
POWER(5,2) POWER(3,3)
---------- ----------
25 27
Output:
SQRT(100)
----------
10
Output:
SQRT(81) SQRT(144)
---------- ----------
9 12
Finding 5 mod 2:
SQL> Select Mod(5,2) from dual;
Output:
MOD(5,2)
----------
1
Output:
MOD(10,6) MOD(20,7)
---------- ----------
4 6
Output:
SIN(90*3.14/180)
----------------
.999999683
Output:
LN(7)
----------
1.94591015
Output:
LOG(10,10)
----------
1
Examples on Trunc():
1. SQL> Select Trunc(123.4567) from dual;
Output:
TRUNC(123.4567)
---------------
123
Output:
TRUNC(123.4567,2)
-----------------
123.45
Output:
TRUNC(123.4567,3)
-----------------
123.456
Output:
TRUNC(123.4567,-1)
------------------
120
120……………………….123.4567…………………………..130
Output:
TRUNC(123.4567,-2)
------------------
100
100……………………123.4567……………………….200
Examples on Round():
Output:
ROUND(123.4567)
---------------
123
Output:
ROUND(123.6567)
---------------
124
Output:
ROUND(123.5567)
---------------
124
Output:
ROUND(123.5567,2)
-----------------
123.56
Output:
ROUND(123.5547,2)
-----------------
123.55
Output:
ROUND(123.5557,2)
-----------------
123.56
Output:
ROUND(123.4567,-1)
------------------
120
Output:
ROUND(126.6567,-1)
------------------
130
-1 means, rounds to 10s
120……………………..126.6567…………………….130
6 is there at 1’s position. >5. So, rounds to 130
Output:
ROUND(125.6567,-1)
------------------
130
120……………….125.6567………………………130
5 is there 1’s position. Eqauls to 5. So rounds to 130
Output:
ROUND(124.6567,-1)
------------------
120
120………………124.6567………………………..130
4 is there 1’s position. So, rounds to 120
Output:
ROUND(123.6567,-2)
------------------
100
Output:
ROUND(152.6567,-2)
------------------
200
Output:
ROUND(150.6567,-2)
------------------
200
Output:
ROUND(149.6567,-2)
------------------
100
Example on Ceil():
SQL> Select Ceil(123.456) from dual;
Output:
CEIL(123.456)
-------------
124
Example on Floor():
SQL> Select Floor(123.456) from dual;
Output:
FLOOR(123.456)
--------------
123
Floor() function always gives lower integer value. So, Printed 123
Output:
Avrg Score
----------
33.3333333
46.6666667
52.3076923
45
Output:
Avrg Score
----------
33
47
52
45
Output:
Avrg Score
----------
33.33
46.67
52.31
45
Output:
Avrg Score
----------
33
46
52
45
Output:
Avrg Score
----------
33.33
46.66
52.3
45
Avrg Score
----------
33.333
46.666
52.307
45
Output:
Avrg Score
----------
33
46
52
45
Output:
Avrg Score
----------
34
47
53
45
Sum of Salaries
---------------
29025
Average Salary
--------------
2073.21429
Average Salary
--------------
2073.21
Average Salary
--------------
2074
Average Salary
--------------
2073
Average Salary
--------------
2073
Average Salary
--------------
2073.21
Min Salary
----------
800
Max Salary
----------
5000
COUNT(COMM)
-----------
3
Note:
Count(Comm) cannot count nulls.
COUNT(EMPNO)
------------
14
COUNT(*)
----------
14
Output:
ENAME
----------
KING
Output:
ENAME
----------
SMITH
Output:
MAX(SAL)
----------
3000
Output:
ENAME
----------
SCOTT
FORD
Output:
Number Of Clerks
----------------
4
Output:
Number Of Managers
----------------
3
Output:
Number Of Employees
-------------------
5
Output:
UPPE
----
RAJU
Output:
LOWE
----
raju
Output:
INITCAP('
---------
Raj Kumar
Output:
CONCAT('
--------
rajkumar
Output:
CONCAT(CO
---------
raj kumar
(Or)
Output:
'RAJ'||''
---------
raj kumar
Getting space between two names and display initial letters as capital in
name:
SQL> Select Initcap(concat(concat('raj', ' '),'kumar')) from dual;
Output:
INITCAP(C
---------
Raj Kumar
Output:
UPPER(ENAM
----------
SMITH
ALLEN
.
Output:
LOWER(ENAM
----------
smith
allen
.
.
Output:
INITCAP(EN
----------
Smith
Allen
.
.
Concatenating First Name and Last Name and getting name’s initial
letters as capital:
Output:
NAME
---------------------
Sachin Tendulkar
Virat Kohli
Rohit Sharma
Rahul Dravid
Output:
UPPER(FNAM
----------
SACHIN
VIRAT
ROHIT
RAHUL
Output:
LOWER(FNAM
----------
sachin
virat
rohit
rahul
Output:
Table altered.
Output:
4 rows updated.
Output:
Table altered.
Output:
PID PNAME
---------- ------------------------------
1001 Sachin Tendulkar
1002 Virat Kohli
1003 Rohit Sharma
1004 Rahul Dravid
Output:
LENGTH('RAJU')
--------------
4
Output:
ENAME Ename Length
---------- ------------
SMITH 5
ALLEN 5
WARD 4
…
Output:
ENAME
----------
WARD
KING
[Or]
Output:
ENAME
----------
WARD
KING
Output:
PID PNAME
---------- ------------------------------
1001 Sachin Tendulkar
1002 Virat Kohli
1003 Rohit Sharma
1004 Rahul Dravid
Output:
PNAME
------------------------------
Rohit Sharma
Rahul Dravid
Displaying player names whose names are having more than 12 chars:
SQL> Select pname from player where length(pname)>12;
Output:
PNAME
------------------------------
Sachin Tendulkar
Output:
SUBST
-----
kumar
Output:
SUB
---
raj
Output:
SUBST
-----
raj k
Output:
SUB
---
uma
Output:
SUBS
----
umar
Output:
SUBS
----
umar
Note:
-ve position => Position Number From Right Side
+ve Position => Position Number From Left Side
Generating Email IDs by taking emp name’s first 3 chars and empno’s last
3 digits:
SQL> Select
substr(Ename,1,3) || substr(empno,-3,3) || '@nareshit.com'
As "E-Mail ID" from emp;
Output:
E-Mail ID
-------------------------------------
[email protected]
[email protected]
..
Output:
ENAME
----------
SMITH
SCOTT
(Or)
Output:
ENAME
----------
SMITH
SCOTT
Retrieving the emp record whose name is ‘blake’ and when we don’t
know whether the name is in upper case or lower case:
SQL> Select ename, sal from emp where lower(ename) = 'blake';
Output:
ENAME SAL
---------- ----------
BLAKE 2850
Displaying Employee names whose names are ended with ‘RD’:
SQL> Select ename from emp where substr(ename,-2,2) = 'RD';
Output:
ENAME
----------
WARD
FORD
(Or)
Output:
ENAME
----------
WARD
FORD
Displaying employee names whose names are started and ended with
same letter:
SQL> Insert into emp(empno,ename) values(1001,'DAVID');
Output:
1 row created.
Output:
ENAME
----------
DAVID
SRINIVAS
Output:
INSTR('THISISHISWISH','IS')
---------------------------
3
Note:
If substring is not found in the string, then it returns 0
Output:
INSTR('THISISHISWISH','IS',-4)
------------------------------
10
Output:
INSTR('THISISHISWISH','IS',-4,2)
--------------------------------
6
Output:
ENAME
----------
ADAMS
JAMES
(or)
Output:
ENAME
----------
ADAMS
JAMES
Output:
LPAD('RAJU
----------
******raju
Output:
LPAD('RAJU',15,
---------------
@#@#@#@#@#@raju
Output:
RPAD('RAJU
----------
raju******
Output:
RPAD('RAJU',15,
---------------
raju@#@#@#@#@#@
Output:
LPAD('RAJU
----------
raju
Output:
RPAD('RAJ',10)|
---------------
raj kumar
SQL> Select Lpad('*',10,'*') from dual;
Output:
LPAD('*',1
----------
**********
MESSAGE
------------------------------------
amount credited from the acno XXXXXX6789
Output:
LTRIM('RAJ')
------------
raj kumar
Output:
RTRIM('RAJ')|
-------------
rajkumar
Output:
TRIM('RA
--------
rajkumar
Output:
LTRIM('@@@@@R
-------------
@@@@@raju@@@@
Output:
LTRIM('@
--------
raju@@@@
Output:
RTRIM('@@
---------
@@@@@raju
Output:
LTRIM('@#@####@@@R
------------------
raju@#@####@@@@###
Output:
RTRIM('@#@####
--------------
@#@####@@@raju
Output:
TRIM(LEAD
---------
raju@@@@@
Output:
TRIM(TRA
--------
@@@@raju
Output:
TRIM
----
raju
Output:
LTRIM('RAJU@NARES
-----------------
[email protected]
Output:
RTRIM('RAJU@N
-------------
raju@nareshit
Output:
RTRI
----
raju
Output:
LTRIM('O
--------
F11 Pro
Output:
REPLACE('SAI
------------
rama krishna
Output:
REPLACE('XYZXYZXXYYZZ
---------------------
abcabcxxyyzzabcxxyyzz
Output:
TRANSLATE('XYZXYZXXYY
---------------------
abcabcaabbccabcaabbcc
Output:
ENAME SALARY
---------- ----------
SMITH +!!
ALLEN @&!!
WARD @#^!
..
Output:
ASCII('A')
----------
65
Output:
ASCII('A') ASCII('Z')
---------- ----------
97 122
Output:
C
-
A
Output:
CC
--
az
Output:
EMPNO ENAME
---------- ----------
7369 SMITH
Output:
EMPNO ENAME
---------- ----------
7788 SCOTT
Output:
REVE
----
umar
Output:
ENAME Rev Name
---------- ----------
SMITH HTIMS
ALLEN NELLA
WARD DRAW
JONES SENOJ
.
.
Output:
TO_C
----
2021
Output:
TO
--
21
Output:
T
-
1
Output:
TO_
---
021
Output:
TO_CHAR(SYSDATE,'YEAR')
------------------------------------------
twenty twenty-one
Output:
TO
--
07
Output:
TO_CHAR(SYSD
------------
jul
Output:
TO_CHAR(SYSDATE,'MONTH')
------------------------------------
july
Output:
TO_CHAR(SYSD
------------
JUL
Output:
TO_CHAR(SYSDATE,'MONTH')
------------------------------------
JULY
Getting date two digits [day number in month] from today’s date:
SQL> Select to_char(sysdate,'dd') from dual;
Output:
TO
--
15
Output:
TO_
---
196
Output:
T
-
5
Output:
TO_CHAR(SYSD
------------
thu
Output:
TO_CHAR(SYSDATE,'DAY')
------------------------------------
thursday
Output:
TO_CHAR(SYSD
------------
THU
Output:
TO_CHAR(SYSDATE,'DAY')
------------------------------------
THURSDAY
Output:
TO_CHAR(
--------
11:41 AM
Output:
T
-
3
Output:
T
-
3
Output:
TO
--
28
TO
--
21
Output:
TO_CH
-----
21 AD
Output:
ENAME HIREDATE
---------- ---------
SCOTT 09-DEC-82
MILLER 23-JAN-82
[Or]
Output:
ENAME HIREDATE
---------- ---------
SCOTT 09-DEC-82
MILLER 23-JAN-82
Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
SCOTT 09-DEC-82
ADAMS 12-JAN-83
MILLER 23-JAN-82
Output:
ENAME HIREDATE
---------- ---------
WARD 22-FEB-81
[Or]
Output:
ENAME HIREDATE
---------- ---------
WARD 22-FEB-81
[Or]
Output:
ENAME HIREDATE
---------- ---------
WARD 22-FEB-81
Output:
ENAME HIREDATE
---------- ---------
JONES 02-APR-81
BLAKE 01-MAY-81
CLARK 09-JUN-81
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
JONES 02-APR-81
SCOTT 09-DEC-82
ADAMS 12-JAN-83
JAMES 03-DEC-81
FORD 03-DEC-81
MILLER 23-JAN-82
Output:
ENAME HIREDATE
---------- ----------
SMITH 12/17/1980
ALLEN 02/20/1981
.
.
Output:
ENAME HIREDATE
---------- ----------
SMITH 17/12/1980
ALLEN 20/02/1981
Output:
TO_DATE('
---------
20-DEC-21
Output:
TO_DATE('
---------
02-DEC-21
Output:
TO_DATE('
---------
23-DEC-20
Output:
TO_C
----
2020
Output:
TO_
---
dec
Output:
TO_CHAR(T
---------
wednesday
Output:
SYSDATE+1
---------
25-JUL-21
Output:
TO_DATE('
---------
26-JUN-21
Output:
TO_CHAR(T
---------
friday
Output:
TO_CHAR(T
---------
tuesday
Output:
1 row created.
Output:
TO_CHAR(5000,'L999
------------------
$5000.00
Output:
TO_CHAR(5000,'C
---------------
USD5000.00
Output:
PARAMETER VALUE
------------------------------------------ --------------------
NLS_LANGUAGE AMERICAN
NLS_TERRITORY AMERICA
NLS_CURRENCY $
.
Output:
Session altered.
Output:
Session altered.
Output:
TO_CHAR(5000,'L999
------------------
RS5000.00
Output:
TO_CHAR(5000,'C
---------------
INR5000.00
Output:
ENAME SALARY
---------- -------------------
SMITH RS800.00
ALLEN RS1600.00
WARD RS1250.00
.
.
.
.
Output:
ENAME SALARY
---------- ----------------
ccc
SMITH INR800.00
ALLEN INR1600.00
TO_CHAR
-------
001234
Output:
TO_NUMBER('123')
----------------
123
Output:
TO_NUMBER('$5000.00','L9999.99')
--------------------------------
5000
SQL> Select to_number('USD5000.00','C9999.99') from dual;
TO_NUMBER('USD5000.00','C9999.99')
----------------------------------
5000
Output:
SYSDATE
---------
16-JUL-21
Output:
SYSTIMESTAMP
---------------------------------------------------------------------------
16-JUL-21 04.20.34.223000 PM +05:30
Output:
TO_CHAR(
--------
04:21 PM
Output:
TO_CH
-----
16:21
Output:
TO_CHAR(SY
----------
16/07/2021
Output:
TO_CHAR(
--------
04:22 PM
Output:
TO_CH
-----
16:22
Output:
ADD_MONTH
---------
16-SEP-21
Output:
ADD_MONTH
---------
16-MAY-21
Output:
ADD_MONTH
---------
20-DEC-20
Output:
ADD_MONTH
---------
20-AUG-20
Output:
1 row created.
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2001 Krishna 16-JUL-21
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2001 Krishna 16-JUL-21
Output:
1 row created.
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 15-JUL-21
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 15-JUL-21
Output:
1 row created.
Displaying emp records who joined one month ago on same date:
SQL> Select empno, ename, hiredate from emp
where to_char(hiredate,'dd/mm/yyyy') =
to_char(Add_Months(sysdate,-1),'dd/mm/yyyy');
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 16-JUN-21
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2002 Ganesh 16-JUN-21
Output:
1 row created.
Displaying employee records who joined one year ago on same date:
SQL> Select empno, ename, hiredate from emp
where to_char(hiredate,'dd/mm/yyyy') =
to_char(Add_Months(sysdate,-12),'dd/mm/yyyy');
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2003 Sai 16-JUL-20
(Or)
Output:
EMPNO ENAME HIREDATE
---------- ---------- ---------
2003 Sai 16-JUL-20
Output:
ENAME HIREDATE
---------- ---------
Ganesh 15-JUL-21
Displaying employee record who joined one month ago on same date
using ‘Interval’ Expression:
SQL> Select ename, hiredate from emp
where trunc(hiredate) = trunc(sysdate-interval '1' month);
Output:
ENAME HIREDATE
---------- ---------
Ganesh 16-JUN-21
Displaying employee record who joined one month ago on same date
using ‘Interval’ Expression:
SQL> Select ename, hiredate from emp
where trunc(hiredate) = trunc(sysdate-interval '1' year);
Output:
ENAME HIREDATE
---------- ---------
Sai 16-JUL-20
Output:
1 row created.
Output:
DATEID AMOUNT
--------- ----------
15-JUL-21 10000
Output:
DATEID AMOUNT
--------- ----------
16-JUN-21 10000
(Or)
Output:
DATEID AMOUNT
--------- ----------
16-JUL-20 10000
Output:
DATEID AMOUNT
--------- ----------
16-JUL-20 10000
(Or)
Output:
DATEID AMOUNT
--------- ----------
16-JUL-20 10000
Output:
Table created.
Output:
1 row created.
Output:
1 row created.
Output:
1 row created.
Output:
3 rows updated.
(Or)
Output:
3 rows updated.
Output:
EMPNO DOB HIREDATE RETIREMEN
---------- --------- --------- ---------
1001 12-JAN-95 01-JUN-18 12-JAN-55
1002 12-JAN-00 20-OCT-20 12-JAN-60
1003 25-DEC-90 20-AUG-15 25-DEC-50
Output:
Table created.
Output:
1 row created.
Output:
STATE CM_NAME TERM_STAR TERM_ENDI
--------------- -------------------- --------- ---------
Telangana KCR 13-DEC-18
AP YS JAGAN 30-MAY-19
Output:
2 rows updated.
(Or)
SQL> Update IndiaCMs Set Term_Ending_Date =
Term_Starting_Date+Interval '5' Year;
Output:
2 rows updated.
Output:
STATE CM_NAME TERM_STAR TERM_ENDI
--------------- -------------------- --------- ---------
Telangana KCR 13-DEC-18 13-DEC-23
AP YS JAGAN 30-MAY-19 30-MAY-24
Output:
LAST_DAY(
---------
31-JUL-21
Output:
LAST_DAY(
---------
01-AUG-21
Output:
LAST_DAY(
---------
01-JUN-21
Output:
LAST_DAY(
---------
30-JUN-21
Output:
LAST_DAY(
---------
01-JUL-21
Output:
NEXT_DAY(
---------
19-JUL-21
Output:
NEXT_DAY(
---------
26-JUL-21
Output:
NEXT_DAY(
---------
02-AUG-21
Output:
NEXT_DAY(
---------
07-JUN-21
Output:
ENAME EXPERIENCE
---------- ----------
SMITH 41
ALLEN 40
WARD 40
JONES 40
MARTIN 40
BLAKE 40
CLARK 40
SCOTT 39
KING 40
Output:
AGE
----------
48
Output:
UID
----------
111
Output:
GREATEST(100,200,300)
---------------------
300
Output:
LEAST(100,200,300)
------------------
100
Output:
VSIZE('RAJU') VSIZE('SAI')
------------- ------------
4 3
Output:
NVL(100,200)
------------
100
Output:
NVL(NULL,200)
-------------
200
Output:
NULL+200
----------
Output:
NVL(NULL,100)+200
-----------------
300
Output:
ENAME SAL COMM Total Salary
---------- ---------- ---------- ------------
SMITH 800 800
ALLEN 1600 300 1900
WARD 1250 500 1750
JONES 2975 2975
MARTIN 1250 1400 2650
Output:
ENAME SAL COMM
---------- ---------- ----------------------------------------
SMITH 800 N/A
ALLEN 1600 300
WARD 1250 500
JONES 2975 N/A
MARTIN 1250 1400
BLAKE 2850 N/A
Output:
STDID SNAME M1 M2 M3
---------- -------------------- ---------- ---------- ----------
2001 aa 55 77
1001 Ravi 40 80 60
1002 Sravan 66 44 77
Output:
SNAME M3
-------------------- ----------------------------------------
aa ABSENT
Ravi 60
Sravan 77
Output:
NVL2(100,200,300)
-----------------
200
Output:
NVL2(NULL,200,300)
------------------
300
Output:
ENAME COMM
---------- ----------
SMITH 1000
ALLEN 500
WARD 700
JONES 1000
MARTIN 1600
BLAKE 1000
CLARK 1000
Output:
EMPNO ENAME SAL RANK
---------- ---------- ---------- ----------
7839 KING 5000 1
7902 FORD 3000 2
7788 SCOTT 3000 2
7566 JONES 2975 4
7698 BLAKE 2850 5
7782 CLARK 2450 6
7499 ALLEN 1600 7
7844 TURNER 1500 8
7934 MILLER 1300 9
7521 WARD 1250 10
7654 MARTIN 1250 10
7876 ADAMS 1100 12
7900 JAMES 950 13
7369 SMITH 800 14
Output:
EMPNO ENAME SAL RANK
---------- ---------- ---------- ----------
7839 KING 5000 1
Output:
ENAME HIREDATE SAL RANK
---------- --------- ---------- ----------
KING 17-NOV-81 5000 1
FORD 03-DEC-81 3000 2
SCOTT 09-DEC-82 3000 3
JONES 02-APR-81 2975 4
BLAKE 01-MAY-81 2850 5
CLARK 09-JUN-81 2450 6
ALLEN 20-FEB-81 1600 7
TURNER 08-SEP-81 1500 8
MILLER 23-JAN-82 1300 9
WARD 22-FEB-81 1250 10
MARTIN 28-SEP-81 1250 11
ADAMS 12-JAN-83 1100 12
JAMES 03-DEC-81 950 13
SMITH 17-DEC-80 800 14
Interval Expressions:
▪ Interval Expressions are introduced in “Oracle 9i”.
▪ Interval expressions are used to add/subtract the days,
months, and years to a date or from a date.
▪ Interval expressions are also used to add/subtract the hours,
minutes, and seconds to a time or from a time.
Output:
SYSDATE+I
---------
22-JUL-21
Output:
SYSDATE+I
---------
20-SEP-21
Output:
SYSDATE+I
---------
20-JUL-23
Output:
SYSDATE+I
---------
20-JAN-23
Output:
SYSDATE-I
---------
18-JUL-21
Output:
SYSDATE-I
---------
20-MAY-21
Output:
SYSDATE-I
---------
20-JUL-19
Output:
SYSDATE-I
---------
20-JAN-20
Output:
TO_DATE('
---------
23-DEC-20
Output:
TO_DATE('
---------
20-MAR-21
Output:
TO_DATE('
---------
20-DEC-23
Output:
TO_DATE('
---------
20-FEB-22
Output:
SYSTIMESTAMP+INTERVAL'2'HOUR
---------------------------------------------------------------------------
20-JUL-21 09.56.55.507000000 AM +05:30
Output:
SYSTIMESTAMP+INTERVAL'2'MINUTE
---------------------------------------------------------------------------
20-JUL-21 07.59.15.396000000 AM +05:30
Output:
SYSTIMESTAMP+INTERVAL'2'SECOND
---------------------------------------------------------------------------
20-JUL-21 07.57.25.627000000 AM +05:30
Output:
SYSTIMESTAMP+INTERVAL'1:30'HOURTOMINUTE
---------------------------------------------------------------------------
20-JUL-21 09.28.18.530000000 AM +05:30
Output:
SYSTIMESTAMP-INTERVAL'2'HOUR
---------------------------------------------------------------------------
20-JUL-21 06.01.52.627000000 AM +05:30
Output:
SYSTIMESTAMP-INTERVAL'2'MINUTE
---------------------------------------------------------------------------
20-JUL-21 08.00.00.867000000 AM +05:30
CASE Expressions:
Syntax:
Case <Column_Name>
When <Value> Then <Return_Expression>
[When <Value> Then <Return_Expression>]
[………………………………………………………………..]
[Else <Return_Expression>]
End
Syntax:
Case
When <Condition> Then <Return_Expression>
[When <Condition> Then <Return_Expression>]
[………………………………………………………………..]
[Else <Return_Expression>]
End
Output:
ENAME JOB
---------- --------
SMITH WORKER
ALLEN EMPLOYEE
JONES BOSS
KING BIG BOSS
Output:
14 rows updated.
Output:
ENAME SAL Salary Rang
---------- ---------- -----------
SMITH 800 Low Salary
ALLEN 1600 Low Salary
SCOTT 3000 Avrg Salary
KING 5000 High Salary
STDID SNAME M1 M2 M3
---------- -------------------- ---------- ---------- ----------
2001 srinu 55 77 25
1001 Ravi 40 80 60
1002 Sravan 66 44 77
Finding result of a student if subject marks are <40 in any subject result
is fail. In every subject if marks are >=40 then result is pass:
SQL> Select Sname,
CASE
When M1>=40 and M2>=40 and M3>=40 Then 'PASS'
ELSE 'FAIL'
END RESULT
From Student;
Output:
SNAME RESU
-------------------- ----
srinu FAIL
Ravi PASS
Sravan PASS
Decode() Function:
It is used to implement the ‘If-Then-Else’ in SQL Statement.
Syntax:
Decode(<Column>,
<Value>,<Return_Expression>
[<Value>,<Return_Expression>,]
[<Value>,<Return_Expression>,]
[<Else_Expression>])
Output:
ENAME JOB
---------- --------
SMITH WORKER
ALLEN EMPLOYEE
WARD EMPLOYEE
JONES BOSS
KING BIG BOSS
Output:
14 rows updated.
Note:
Decode() Function can check equality only. It cannot check other
conditions.
Output:
DEPTNO SUM(SAL)
---------- ----------
10 8750
20 10875
30 9400
Output:
DEPTNO ROUND(AVG(SAL),2)
---------- -----------------
10 2916.67
20 2175
30 1566.67
Output:
DEPTNO MAX(SAL) MIN(SAL)
---------- ---------- ----------
10 5000 1300
20 3000 800
30 2850 950
Output:
DEPTNO COUNT(*)
---------- ----------
10 3
20 5
30 6
Output:
YEAR NUMBER_OF_EMPS
---- --------------
1980 1
1981 10
1982 2
1983 1
Output:
WEEKDAY NUMBER_OF_EMPS
------------------------------------ --------------
thursday 4
wednesday 2
friday 2
sunday 1
monday 1
tuesday 3
saturday 1
Output:
JOB SUM(SAL)
--------- ----------
CLERK 4150
SALESMAN 5600
ANALYST 6000
MANAGER 8275
PRESIDENT 5000
Output:
JOB ROUND(AVG(SAL))
--------- ---------------
CLERK 1038
SALESMAN 1400
ANALYST 3000
MANAGER 2758
PRESIDENT 5000
Output:
JOB MAX(SAL) MIN(SAL)
--------- ---------- ----------
CLERK 1300 800
SALESMAN 1600 1250
ANALYST 3000 3000
MANAGER 2975 2450
PRESIDENT 5000 5000
Output:
JOB COUNT(*)
--------- ----------
CLERK 4
SALESMAN 4
ANALYST 2
MANAGER 3
PRESIDENT 1
Output:
DEPTNO SUM(SAL)
---------- ----------
10 8750
30 9400
Output:
JOB SUM(SAL)
--------- ----------
CLERK 4150
MANAGER 8275
Output:
DEPTNO COUNT(*)
---------- ----------
30 6
20 5
Output:
DEPTNO COUNT(*)
---------- ----------
10 3
Displaying the Job Titles which are having more than 3 employees:
SQL> Select Job, Count(*)
From Emp
Group By Job
Having Count(*)>3;
Output:
JOB COUNT(*)
--------- ----------
CLERK 4
SALESMAN 4
Output:
JOB SUM(SAL)
--------- ----------
SALESMAN 5600
ANALYST 6000
MANAGER 8275
Output:
DEPTNO
----------
20
Output:
DEPTNO
----------
30
Output:
JOB
---------
MANAGER
Output:
JOB
---------
CLERK
SALESMAN
Output:
CNAME COUNT(*)
---------- ----------
Oracle 2
C 4
Java 2
Python 2
Output:
CNAME COUNT(*)
---------- ----------
C 4
Output:
CNAME SUM(FEE)
---------- ----------
Oracle 10000
C 16000
Java 12000
Python 16000
Output:
CNAME SUM(FEE)
---------- ----------
Oracle 10000
Java 12000
Output:
CNAME
----------
Oracle
Output:
DEPTNO JOB SUM(SAL)
---------- --------- ----------
10 CLERK 1300
MANAGER 2450
PRESIDENT 5000
20 ANALYST 6000
CLERK 1900
MANAGER 2975
30 CLERK 950
MANAGER 2850
SALESMAN 5600
20 ANALYST 6000
CLERK 1900
MANAGER 2975
10875 20th Dept Sub Total
30 CLERK 950
MANAGER 2850
SALESMAN 5600
9400 30th Dept Sub Total
Output:
DEPTNO JOB SUM(SAL)
---------- --------- ----------
10 CLERK 1300
MANAGER 2450
PRESIDENT 5000
8750 10th Dept Sub Total
20 ANALYST 6000
CLERK 1900
MANAGER 2975
10875 20th Dept Sub Total
30 CLERK 950
MANAGER 2850
SALESMAN 5600
9400 30th Dept Sub Total
Output:
YEAR Q Number of Emps
---- - --------------
1980 4 1
1981 1 2
2 3
3 2
4 3
1982 1 1
4 1
1983 1 1
Output:
YEAR Q Number of Emps
---- - --------------
1980 4 1
1 1980 Sub Total
1981 1 2
2 3
3 2
4 3
10 1981 Sub Total
1982 1 1
4 1
2 1982 Sub Total
1983 1 1
1 1983 Sub Total
14 Grand Total
Output:
YEAR Q Number of Emps
---- - --------------
1980 4 1
1 1980 Sub Total
1981 1 2
2 3
3 2
4 3
10 1981 Sub Total
1982 1 1
4 1
2 1982 Sub Total
1983 1 1
1 1983 Sub Total
14 Grand Total
Create a table with the name sales and enter 3 years sales as following:
DATEID AMOUNT
--------- ----------
01-JAN-15 5000
02-JAN-15 5000
03-JAN-15 10000
01-APR-15 8000
02-APR-15 6000
01-MAY-15 6000
01-JUN-15 6000
01-JUL-15 6000
02-JUL-15 7000
02-NOV-15 9000
02-DEC-15 9000
01-JAN-16 4000
02-JAN-16 3000
01-MAY-16 3000
02-MAY-16 6000
01-DEC-16 3000
01-AUG-16 3000
02-AUG-16 2000
01-JAN-17 2000
02-JAN-17 8000
02-MAY-17 8000
03-MAY-17 7000
01-AUG-17 7000
02-AUG-17 5000
01-DEC-17 5000
Output:
YEAR Q SUM(AMOUNT)
---- - -----------
2015 1 20000
2 26000
3 13000
4 18000
2016 1 7000
2 9000
3 5000
4 3000
2017 1 10000
2 15000
3 12000
4 5000
Displaying year wise, with in year quarter wise sales and Calculate sub
totals and grand total according to year:
SQL> Select to_char(DateID,'yyyy') Year, to_char(DateID,'Q') Qrtr,
Sum(Amount)
from Sales
Group By Rollup(to_char(DateID,'yyyy'), to_char(DateID,'Q'))
Order By 1;
Output:
YEAR Q SUM(AMOUNT)
---- - -----------
2015 1 20000
2 26000
3 13000
4 18000
77000 2015 Sub Total
2016 1 7000
2 9000
3 5000
4 3000
24000 2016 Sub Total
2017 1 10000
2 15000
3 12000
4 5000
42000 2017 Sub Total
Displaying year wise, with in year quarter wise sales and Calculate sub
totals and grand total according to year and quarter:
SQL> Select to_char(DateID,'yyyy') Year, to_char(DateID,'Q') Qrtr,
Sum(Amount)
from Sales
Group By Cube(to_char(DateID,'yyyy'), to_char(DateID,'Q'))
Order By 1;
Output:
YEAR Q SUM(AMOUNT)
---- - -----------
2015 1 20000
2 26000
3 13000
4 18000
77000 2015 Sub Total
2016 1 7000
2 9000
3 5000
4 3000
24000 2016 Sub Total
2017 1 10000
2 15000
3 12000
4 5000
42000 2017 Sub Total
Create a Table with the name “Person” and enter the data as following:
Output:
PID PNAME STATE G AGE AADHARNO
---------- ---------- ---------- - ---------- ----------
1 aa Telangana M 45 123456
2 bb Telangana M 62 123457
3 cc Telangana F 48 123458
4 cc Telangana F 65 123459
5 cc Telangana M 32 123460
6 dd Telangana F 35 123461
7 dd Telangana F 23 123462
8 dd Telangana M 25 123463
9 ee Telangana M 28 123464
10 ff Gujarat M 65 123465
11 gg Gujarat M 62 123466
12 gg Gujarat M 45 123467
12 gg Gujarat F 41 123468
13 hh Gujarat F 45 123469
14 hh Gujarat F 23 123470
14 hh Gujarat F 35 123471
15 hh Gujarat M 36 123472
Output:
STATE G COUNT(*)
---------- - ----------
Gujarat F 4
M 4
Telangana F 4
M 5
Displaying state wise, with in state gender wise number of people and
calculate subtotals and grand total according to state:
SQL> Select State, Gender, Count(*)
from Person
Group By Rollup(State, Gender)
Order By State;
Output:
STATE G COUNT(*)
---------- - ----------
Gujarat F 4
M 4
8 Gujarat Sub Total
Telangana F 4
M 5
9 Telangana Sub Total
17 Grand Total
Displaying state wise, with in state gender wise number of people and
calculate subtotals and grand total according to state and gender:
Select State, Gender, Count(*)
from Person
Group By Cube(State, Gender)
Order By State;
Output:
SQL> Select State, Gender, Count(*)
2 from Person
3 Group By Cube(State, Gender)
4 Order By State;
STATE G COUNT(*)
---------- - ----------
Gujarat F 4
M 4
8 Gujarat Sub Total
Telangana F 4
M 5
9 Telangana Sub Total
17 Grand Total
Displaying State wise, age range wise, gender wise number of people:
SQL> Select State, CASE
when age between 1 and 20 then '1 to 20'
when age between 21 and 40 then '21 to 40'
when age between 41 and 60 then '41 to 60'
Else 'Above 60'
End "Age Range", Gender, Count(*) from Person
Group By State,
CASE
when age between 1 and 20 then '1 to 20'
when age between 21 and 40 then '21 to 40'
when age between 41 and 60 then '41 to 60'
Else 'Above 60'
End, Gender
Order By State;
Output:
STATE Age Rang G COUNT(*)
---------- -------- - ----------
Gujarat 21 to 40 F 2
M 1
41 to 60 F 2
M 1
Above 60 M 2
Telangana 21 to 40 F 2
M 3
41 to 60 F 1
M 1
Above 60 F 1
M 1
Displaying State wise, Age range wise, gender wise number of people and
calculate sub totals & grand total according to state:
SQL> Select State, CASE
when age between 1 and 20 then '1 to 20'
when age between 21 and 40 then '21 to 40'
when age between 41 and 60 then '41 to 60'
Else 'Above 60'
End "Age Range", Gender, Count(*) from Person
Group By Rollup(State,
CASE
when age between 1 and 20 then '1 to 20'
when age between 21 and 40 then '21 to 40'
when age between 41 and 60 then '41 to 60'
Else 'Above 60'
End, Gender)
Order By State;
Output:
STATE Age Rang G COUNT(*)
---------- -------- - ----------
Gujarat 21 to 40 F 2
M 1
3 Gujarat 21 to 40 age Sub Total
41 to 60 F 2
M 1
3 Gujarat 41 to 60 age Sub Total
Above 60 M 2
2 Gujarat above 60 age Sub Total
Telangana 21 to 40 F 2
M 3
5 Telangana 21 to 40 age Sub Total
41 to 60 F 1
M 1
2 Telangana 41 to 60 age Sub Total
Above 60 F 1
M 1
2 Telangana Above 60 age Sub Total
17 Grand Total
Displaying State wise, Age range wise, gender wise number of people and
calculate sub totals & grand total according to state, age range and
gender:
SQL> Select State,
CASE
when age between 1 and 20 then '1 to 20'
when age between 21 and 40 then '21 to 40'
when age between 41 and 60 then '41 to 60'
Else 'Above 60'
End "Age Range", Gender, Count(*)
from Person
Group By Cube(State,
CASE
when age between 1 and 20 then '1 to 20'
when age between 21 and 40 then '21 to 40'
when age between 41 and 60 then '41 to 60'
Else 'Above 60'
End, Gender)
Order By State;
Output:
STATE Age Rang G COUNT(*)
---------- -------- - ----------
Gujarat 21 to 40 F 2
M 1
3 Gujarat 21 to 40 age Sub Total
41 to 60 F 2
M 1
3 Gujarat 41 to 60 age Sub Total
Above 60 M 2
2 Gujarat above 60 age Sub Total
Telangana 21 to 40 F 2
M 3
5 Telangana 21 to 40 age Sub Total
41 to 60 F 1
M 1
2 Telangana 41 to 60 age Sub Total
Above 60 F 1
M 1
2 Telangana Above 60 age Sub Total
21 to 40 F 4
M 4
8 21 to 40 Sub Total
41 to 60 F 3
M 2
5 41 to 60 Sub Total
Above 60 F 1
M 3
4 Above 60 Sub Total
17 Grand Total
Output:
Salary Ran COUNT(*)
---------- ----------
1001-2000 6
2001-3000 5
700-1000 2
4001-5000 1
Examples on Joins
Example-1:
Output:
1 row created.
[OR]
ANSI STYLE:
SQL> Select e.ename, e.sal, d.dname, d.loc
from emp e Inner Join Dept d
On e.deptno=d.deptno;
Output:
ENAME SAL DNAME LOC
---------- ---------- -------------- -------------
SMITH 800 RESEARCH DALLAS
ALLEN 1600 SALES CHICAGO
.
.
[OR]
ANSI STYLE:
SQL> Select e.ename, e.sal, s.grade
from emp e JOIN salgrade s
On e.sal between s.losal and s.hisal;
Output:
ENAME SAL GRADE
---------- ---------- ----------
SMITH 800 1
JAMES 950 1
ADAMS 1100 1
WARD 1250 2
MARTIN 1250 2
MILLER 1300 2
TURNER 1500 3
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e INNER JOIN dept d
On e.deptno=d.deptno
where e.ename='BLAKE';
Output:
ENAME DNAME
---------- --------------
BLAKE SALES
Display the dept names in which ‘BLAKE’ is not working [NON-EQUI JOIN]:
ORACLE STYLE:
SQL> Select e.ename, d.dname
from emp e, dept d
where e.deptno!=d.deptno and e.ename='BLAKE';
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e JOIN dept d
On e.deptno!=d.deptno
where e.ename='BLAKE';
Output:
ENAME DNAME
---------- --------------
BLAKE ACCOUNTING
BLAKE RESEARCH
BLAKE OPERATIONS
Display the emp records who are working in NEW YORK [EQUI-JOIN]:
ORACLE STYLE:
SQL> Select e.ename, e.sal, d.dname, d.loc
from emp e, dept d
where e.deptno=d.deptno and d.loc='NEW YORK';
ANSI STYLE:
SQL> Select e.ename, e.sal, d.dname, d.loc
from emp e INNER JOIN dept d
On e.deptno=d.deptno where d.loc='NEW YORK';
Output:
ENAME SAL DNAME LOC
---------- ---------- -------------- -------------
CLARK 2450 ACCOUNTING NEW YORK
KING 5000 ACCOUNTING NEW YORK
MILLER 1300 ACCOUNTING NEW YORK
Display all the employees who are assigned to department and not
assigned to department [Left Outer Join]:
ORACLE STYLE:
SQL> Select e.ename, d.dname
from emp e, dept d
where e.deptno = d.deptno(+);
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e LEFT OUTER JOIN dept d
On e.deptno=d.deptno;
Output:
ENAME DNAME
---------- --------------
CLARK ACCOUNTING
KING ACCOUNTING
MILLER ACCOUNTING Matched Records
SMITH RESEARCH
JONES RESEARCH
STEVE Unmatched Record
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e RIGHT OUTER JOIN dept d
On e.deptno=d.deptno;
Output:
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES Matched Records
WARD SALES
JONES RESEARCH
OPERATIONS Unmatched Record
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e FULL OUTER JOIN dept d
On e.deptno=d.deptno;
Output:
ENAME DNAME
---------- --------------
ADAMS RESEARCH
ALLEN SALES Matched Records
SMITH RESEARCH
STEVE Unmatched Record from left table
OPERATIONS Unmatched Record from right table
Display the employees who are not assigned to any department [Left
Outer Join and Condition]:
ORACLE STYLE:
SQL> Select e.ename, d.dname
from emp e, dept d
where e.deptno=d.deptno(+) and d.dname is Null;
[OR]
Output:
ENAME DNAME
---------- --------------
STEVE Unmatched Record from left table
Display the departments which are not having employees [Right Outer
Join and Condition]:
ORACLE STYLE:
SQL> Select e.ename, d.dname
from emp e, dept d
where e.deptno(+)=d.deptno and e.ename is Null;
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e RIGHT OUTER JOIN dept d
On e.deptno=d.deptno
where e.ename is Null;
Output:
ENAME DNAME
---------- --------------
OPERATIONS Unmatched Record from right table
Display the employees who are not assigned to any department and the
departments which are not having employees [Left Outer and Condition
UNION Right Outer and Condition]:
ORACLE STYLE:
SQL> Select e.ename, d.dname
from emp e, dept d
where e.deptno=d.deptno(+) and d.dname is Null
UNION
Select e.ename, d.dname
from emp e, dept d
where e.deptno(+)=d.deptno and e.ename is Null;
[OR]
ANSI STYLE:
SQL> Select e.ename, d.dname
from emp e FULL OUTER JOIN dept d
On e.deptno=d.deptno
where d.dname is null or e.ename is null;
Output:
ENAME DNAME
---------- --------------
Unmatched Record from left table
STEVE
OPERATIONS Unmatched Record from right table
Example-2:
COURSE
Cid CName
STUDENT
Sid Sname Cid
Output:
CID CNAME
---------- --------------------
10 JAVA
20 PYTHON
30 ORACLE
40 HTML
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s INNER JOIN course c
On s.cid=c.cid;
Output:
SNAME CNAME
-------------------- --------------------
Ravi PYTHON
Srinu ORACLE
Sai PYTHON
Arun ORACLE
Sravan JAVA
Display all student details including the students registered but not
joined in the course [LEFT OUTER JOIN]:
ORACLE STYLE:
SQL> Select s.sname, c.cname
from student s, course c
where s.cid=c.cid(+);
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s LEFT JOIN course c
On s.cid=c.cid;
Output:
SNAME CNAME
-------------------- --------------------
Sravan JAVA
Ravi PYTHON
Sai PYTHON
Srinu ORACLE
Arun ORACLE
Vijay
Display all student details with course details. Also Display the courses
which are not having students [RGHT OUTER JOIN]:
ORACLE STYLE:
SQL> Select s.sname, c.cname
from student s, course c
where s.cid(+)=c.cid;
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s RIGHT JOIN course c
On s.cid=c.cid;
Output:
SNAME CNAME
-------------------- --------------------
Ravi PYTHON
Srinu ORACLE
Sai PYTHON
Arun ORACLE
Sravan JAVA
HTML
Display the students who are registered but not joined in the course [Left
Outer and Condition]:
ORACLE STYLE:
SQL> Select s.sname, c.cname
from student s, course c
where s.cid=c.cid(+) and c.cname is Null;
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s LEFT JOIN course c
On s.cid=c.cid
where c.cname is null;
Output:
SNAME CNAME
-------------------- --------------------
Vijay
Display the courses which are not having students [Right Outer and
Condition]:
ORACLE STYLE:
SQL> Select s.sname, c.cname
from student s, course c
where s.cid(+)=c.cid and s.sname is Null;
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s RIGHT JOIN course c
On s.cid=c.cid
where s.sname is null;
Output:
SNAME CNAME
-------------------- --------------------
HTML
Display all students details with course details and display the students
who are registered but not joined in any course. Also Display the courses
which are not having students [FULL OUTER JOIN]:
ORACLE STYLE:
SQL> Select s.sname, c.cname
from student s, course c
where s.cid=c.cid(+)
UNION
Select s.sname, c.cname
from student s, course c
where s.cid(+)=c.cid;
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s FULL JOIN course c
On s.cid=c.cid;
Output:
SNAME CNAME
-------------------- --------------------
Arun ORACLE
Ravi PYTHON
Sai PYTHON
Sravan JAVA
Srinu ORACLE
Vijay
HTML
Display the students who are registered but not joined in any course and
display the courses which are not having students [Left Outer and
Condition Union Right Outer and Condition]:
ORACLE STYLE:
SQL> Select s.sname, c.cname
from student s, course c
where s.cid=c.cid(+) and c.cname is null
UNION
Select s.sname, c.cname
from student s, course c
where s.cid(+)=c.cid and s.sname is null;
[OR]
ANSI STYLE:
SQL> Select s.sname, c.cname
from student s FULL JOIN course c
On s.cid=c.cid
Where c.cname is null or s.sname is null;
Output:
SNAME CNAME
-------------------- --------------------
Vijay
HTML
Output:
DEPTNO DNAME LOCID
---------- ---------- ----------
10 ACCOUNTS 101
20 SALES 102
30 RESEARCH 103
40 OPERATIONS 104
Output:
EMPNO ENAME JOB SAL DEPTNO
---------- -------------------- --------------- ---------- ----------
2001 ravi clerk 5000 10
2002 kiran clerk 4000 20
2003 sravan manager 8000 20
2004 sai manager 10000 10
Output:
LID LNAME CID
---------- -------------------- ----------
101 CHICAGO 1002
102 DELHI 1001
103 MUMBAI 1001
104 NEWYORK 1002
Output:
CID CNAME
---------- ----------
1001 INDIA
1002 AMERICA
1003 JAPAN
1004 RUSSIA
Output:
ENAME DNAME LNAME CNAME
-------------------- ---------- -------------------- ----------
kiran SALES DELHI INDIA
sravan SALES DELHI INDIA
ravi ACCOUNTS CHICAGO AMERICA
sai ACCOUNTS CHICAGO AMERICA
Sub Queries
Syntax:
Select <column_list>
From <Table_Name>
Where <column_name> <operator> (<Select statement>);
Ouptut:
ENAME SAL
---------- ----------
JONES 2975
SCOTT 3000
KING 5000
FORD 3000
Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
ALLEN 20-FEB-81
.
Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
Output:
ENAME SAL
---------- ----------
KING 5000
Output:
MAX(SAL)
----------
3000
Output:
ENAME
----------
SCOTT
FORD
Output:
1 row deleted.
Output:
1 row updated.
Output:
2 rows updated.
Output:
DEPTNO
----------
20
Output:
DEPTNO
----------
30
• An inner query which returns more than one value is called “Multi
Row Sub Query”.
• We cannot use = operator for Multi row sub queries. Because =
operator can check comparison with one value only. But Multi row
sub query returns more than one value.
• We can use In, Not In, Any, All operators in Multi Row Sub Queries.
Output:
ENAME JOB
---------- ---------
SMITH CLERK
ADAMS CLERK
JAMES CLERK
MILLER CLERK
JONES MANAGER
BLAKE MANAGER
CLARK MANAGER
Output:
ENAME SAL DEPTNO
---------- ---------- ----------
BLAKE 2850 30
KING 5000 10
SCOTT 3000 20
FORD 3000 20
Output:
ENAME HIREDATE
---------- ---------
ALLEN 20-FEB-81
CLARK 09-JUN-81
SMITH 17-DEC-80
Output:
ENAME SAL
---------- ----------
WARD 1250
MARTIN 1250
SCOTT 3000
FORD 3000
Output:
ENAME SAL
---------- ----------
JONES 2975
SCOTT 3000
FORD 3000
KING 5000
Output:
ENAME SAL
---------- ----------
KING 5000
FORD 3000
SCOTT 3000
JONES 2975
BLAKE 2850
CLARK 2450
SMITH 1600
TURNER 1500
MILLER 1300
[OR]
Output:
ENAME DEPTNO
---------- ----------
SMITH 20
JONES 20
ALLEN 30
WARD 30
BLAKE 30
..
..
Output:
ENAME SAL DEPTNO
---------- ---------- ----------
ALLEN 1600 30
JONES 2975 20
BLAKE 2850 30
SCOTT 3000 20
KING 5000 10
FORD 3000 20
Output:
ENAME SAL DEPTNO
---------- ---------- ----------
BLAKE 2850 30
SCOTT 3000 20
KING 5000 10
FORD 3000 20
Output:
SAL
----------
2975
Output:
SAL
----------
2850
SQL> /
Enter value for n: 2 --second maximum salary
Output:
SAL
----------
3000
3000
SQL> /
Enter value for n: 3 --third aximum salary
Output:
SAL
----------
2975
SQL> /
Enter value for n: 4 --fourth maximum salary
Output:
SAL
----------
2850
Output:
DNAME
--------------
RESEARCH
SALES
ACCOUNTING
Output:
DNAME
--------------
OPERATIONS
Output:
EMPNO ENAME JOB
---------- ---------- --------- -
7902 FORD ANALYST
7698 BLAKE MANAGER
7839 KING PRESIDENT
7566 JONES MANAGER
7788 SCOTT ANALYST
7782 CLARK MANAGER
Output:
EMPNO ENAME JOB
---------- ---------- ---------
7876 ADAMS CLERK
7521 WARD SALESMAN
7499 ALLEN SALESMAN
7900 JAMES CLERK
7369 SMITH CLERK
7934 MILLER CLERK
7654 MARTIN SALESMAN
7844 TURNER SALESMAN
Inline View:
1. Display the emp records whose annual salary is greater than 30000:
SQL> Select * from (Select ename, sal, sal*12 an_Sal from emp) e
where an_Sal>30000;
Output:
ENAME SAL AN_SAL
---------- ---------- ----------
JONES 2975 35700
BLAKE 2850 34200
SCOTT 3000 36000
KING 5000 60000
FORD 3000 36000
Output:
ENAME SAL RNK
---------- ---------- ----------
KING 5000 1
SCOTT 3000 2
FORD 3000 2
JONES 2975 3
Output:
RN ENAME SAL
---------- ---------- ----------
3 WARD 1250
Output:
RN ENAME SAL
---------- ---------- ----------
3 WARD 1250
5 MARTIN 1250
11 ADAMS 1100
Output:
RN ENAME SAL
---------- ---------- ----------
6 BLAKE 2850
7 CLARK 2450
8 SCOTT 3000
9 KING 5000
10 TURNER 1500
Output:
RN ENAME SAL
---------- ---------- ----------
2 ALLEN 1600
4 JONES 2975
6 BLAKE 2850
8 SCOTT 3000
10 TURNER 1500
12 JAMES 950
14 MILLER 1300
Output:
RN ENAME SAL
---------- ---------- ----------
1 SMITH 800
3 WARD 1250
5 MARTIN 1250
7 CLARK 2450
9 KING 5000
11 ADAMS 1100
13 FORD 3000
Output:
EMP DEPT
---------- ----------
14 4
Output:
DEPTNO DEPT_TOT_SAL TOT_SAL PERCENTAGE
---------- ------------ ---------- ----------
30 9400 29025 32.39
10 8750 29025 30.15
20 10875 29025 37.47
Views
View:
Advantages:
• View provides security for the data.
• It reduces complexity & simplifies the usage of query.
Note:
Database security can be implemented in three levels.
• To implement Database Level Security, use Schemas [Creating Users]
• To implement Table Level Security, use privileges [Granting
permissions]
• To implement data level [row level & column level] security, use
views.
Types of Views:
Views can be divided into two types according to the number of Base
Tables. They are:
• Simple View
• Complex View
Simple View:
• A view which is created based on one table is called “Simple View”.
• We can perform DML operations like Insert, Delete and Update on
this view.
• It can be updated. So, it can be also called as “Updatable View”.
Output:
Grant succeeded.
Connect as C##ravi:
SQL> conn c##ravi/nareshit
Output:
Connected.
Output:
Connected.
Output:
Grant succeeded.
Output:
Connected.
Output:
View created.
Output:
1 row updated.
Output:
1 row deleted.
Note:
In the above example, “c##ravi” user is owner of emp table. He created
a view “v1” & given permission to “c##oracle7am” user.
“c##oracle7am” user can access 4 columns of emp table. He cannot
access remaining clolumns like sal, comm …etc. Hence Column Level
security implemented.
“c##oracle7am” user can select, insert, update and delete the records
through view.
Output:
Connected.
Output:
View created.
Output:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
Output:
Grant succeeded.
Output:
Connected.
Output:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
Output:
1 row created.
Output:
1 row updated.
Output:
1 row deleted.
Output:
1 row created.
Note:
“c##oracle7am” user has no permission to view the deptno 10 records.
Still he is able to insert deptno 10 emp record. To prevent this, recreate
the view using “WITH CHECK OPTION” clause.
Even if he inserts the record, he cannot see that record through view.
To check it write following query:
SQL> Select * from c##ravi.v2;
Output:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
Connect as “c##ravi”:
SQL> conn c##ravi/nareshit
Output:
Connected.
Output:
View created.
Complex View:
• A view which is created based on multiple tables is called “Complex
View”.
• A view which is created using joins or group by or having or
aggregate functions or expressions or set operators or sub queries
can be called as “Complex View”.
• This view cannot be updated. So, it can be also called as “Read-Only
View”.
Output:
View created.
Output:
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-
preserved table
Note:
With above query, we can understand that insertion operation cannot
be performed on “Complex View”.
Output:
ERROR at line 1:
ORA-01752: cannot delete from view without exactly one key-
preserved table
Note:
With above query, we can understand that deletion operation cannot
be performed on “Complex View”.
Output:
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-
preserved table
Note:
With above query, we can understand that updation operation cannot
be performed on “Complex View”.
Example:
SQL> Create view v4 as select * from v3;
Output:
View created.
Output:
ENAME JOB DEPTNO DNAME LOC
---------- --------- ---------- -------------- -------------
SMITH CLERK 20 RESEARCH DALLAS
ALLEN SALESMAN 30 SALES CHICAGO
Note:
If data of base table modified, we can see the changes through view.
If Structure of base table modified, we cannot see the changes through
view.
FORCE VIEW:
A view which is created without existing table with some compilation
errors is called “Force View”.
Even if we create the view, this view will not until we create the base
table.
Example:
SQL> Create Force View FV1
As
Select * from ABC;
Output:
Warning: View created with compilation errors.
Output:
ERROR at line 1:
ORA-04063: view "C##RAVI.FV1" has errors
Note:
After creating ABC table above view will work.
Output:
VIEW_NAME
----------------------
V1
V2
V3
V4
FV1
Dropping a View:
“Drop” command is used to drop the view.
Syntax:
Drop view <view_name>;
Example:
SQL> Drop view v1;
Output:
View dropped.
PL / SQL
Features of PL/SQL:
Improves Performance:
In PL/SQL, SQL commands can be grouped into one block, and we can
submit this block to Oracle. Oracle executes this block and gives
response to user. PL/SQL reduces number of requests and response. So,
performance will be improved.
Provides Reusability:
PL/SQL provides Functions, Procedures, Triggers and Packages. Because
of these database objects we can reuse the code. We define code only
once. But we can use that code for any number of times by calling.
Provides Security:
PL/SQL programs are stored in database. So, these are centralized. Only
authorized users can execute these programs.
PL/SQL Blocks:
PL/SQL program contains blocks. These PL/SQL blocks are 2 Types. Theya
are:
• Anonymous Blocks
• Named Blocks
Anonymous Block:
A PL/SQL block without any name is called “Anonymous Block”.
Named Block:
A PL/SQL block with name is called “Named Block”.
Ex: Procedure, Function, Package, Trigger
DECLARE
<declare the variables> --DECLARATION PART
BEGIN
<Statements> --EXECUTION PART
END;
/
Dbms_output.put_line():
“Dbms_output” is a package. It provides put_line() procedure. Put_line()
procedure is used to print the messages on output.
Example: dbms_output.put_line(‘hello’); --prints hello
Execution Process:
• Type above program in Notepad / Edit Plus or any other text editor.
• Save it in d: drive oracle7am folder with the name “hello.sql”.
• Open SQL Command Prompt and type as following:
SQL>@d:\oracle7am/hello.sql
--Above compiles & runs “hello.sql” program.
BFILE
BLOB
Declaring a Variable:
Syntax:
<variable> <data_type>;
Example:
x Number(4);
d Date;
a varchar2(20);
Syntax:
<variable> := <value>;
Example:
x := 20;
d := ’12-AUG-2021’;
a := ‘Raju’;
z := x+y;
dbms_output.put_line('sum=' || z);
dbms_output.put_line('sum of ' || x || ' and ' || y || ' is ' || z);
END;
/
Output:
sum=50
sum of 20 and 30 is 50
z := x+y;
dbms_output.put_line('quotient=' || z);
dbms_output.put_line('sum of ' || x || ' and ' || y || ' is ' || z);
END;
/
Output:
Enter value for x: 20
old 6: x := &x;
new 6: x := 20;
Enter value for y: 30
old 7: y := &y;
new 7: y := 30;
quotient=50
sum of 20 and 30 is 50
To avoid old and new when we read data from output, execute the
following command:
SQL> SET VERIFY OFF
Output:
Enter value for x: 15-aug-1947
Friday
Control Structures
IF…THEN:
The statement in ‘IF’ block get executed when the condition is TRUE. It
skips the statements when the condition is FALSE.
Syntax:
If <condition> Then
//Statements
End If;
IF age>=18 THEN
dbms_output.put_line('Eligible to vote');
END IF;
END;
/
Output:
Enter value for age: 25
Eligible to vote
If-Then-Else:
The statements in ‘If’ block get executed when the condition is TRUE. The
statements in ‘Else’ block get executed when the condition is FALSE.
Syntax:
If <condition> Then
//Statements
Else
//Statements
End If;
IF mod(n,2)=0 THEN
dbms_output.put_line('EVEN');
ELSE
dbms_output.put_line('ODD');
END IF;
END;
/
Output:
Enter value for n: 7
ODD
If..Then..Elsif:
It is used to execute the statements based on any one of the multiple
conditions. The statements in “If..Then..Elsif” get executed when
corresponding condition is TRUE. When all conditions are FALSE, it
executes Else block statements. Writing “Else” block is optional.
Syntax:
If <condition-1> Then
//Statements
Elsif <condition-2> Then
//Statements
.
.
Else
//Statements
End If;
IF n>0 THEN
dbms_output.put_line('POSITIVE');
ELSIF n<0 THEN
dbms_output.put_line('NEGATIVE');
ELSE
dbms_output.put_line('ZERO');
END IF;
END;
/
Output:
Enter value for n: 8
POSITIVE
Neste If:
Writing ‘IF’ block in another ‘IF’ Block is called “Nested If”. First ouer
condition is tested. If outer condition is TRUE, inner condition will be
tested. If inner condition is also TRUE, it executes the statements in Inner
If. If Outer Condition is False, it comes out of Outer If.
Syntax:
If <condition-1> Then
If <condition-2> Then
//Statements
End If;
End If;
IF x>y THEN
IF x>z THEN
dbms_output.put_line('x is big');
ELSE
dbms_output.put_line('z is big');
END If;
ELSE
IF y>z THEN
dbms_output.put_line('y is big');
ELSE
dbms_output.put_line('z is big');
END IF;
END IF;
END;
/
Output:
Enter value for x: 100
Enter value for y: 200
Enter value for z: 150
y is big
Case:
“Case” can be used in two ways. They are:
• Simple Case
• Searched Case
Simple Case:
“Simple Case” can check equality condition only.
Syntax:
Case <expression>
When <value> Then
<Statements>;
When <value> Then
<Statements>;
When <value> Then
<Statements>;
.
.
Else
<Statements>
End Case;
CASE mod(n,2)
WHEN 0 THEN
dbms_output.put_line('EVEN');
WHEN 1 THEN
dbms_output.put_line('ODD');
END CASE;
END;
/
Output:
Enter value for n: 8
EVEN
Searched Case:
It can check non-equality conditions also.
Syntax:
Case
When <value> Then
<Statements>;
When <value> Then
<Statements>;
When <value> Then
<Statements>;
.
.
Else
<Statements>
End Case;
Output:
Enter value for n: -4
NEGATIVE
Simple Loop:
Syntax:
Loop
//Statements;
Exit when <condition>;
End Loop;
While Loop:
Syntax:
While <Condition>
Loop
//Statements;
End Loop;
Output:
Enter value for n: 5
1
2
3
4
5
For Loop:
Syntax:
for <variable> in [reverse] <lower> .. <upper>
Loop
//Statements
End Loop;
Output:
1
2
3
4
5
6
7
8
9
10
Output:
5
4
3
2
1
Output:
1
2
3
4
All DML and TCL Commands syntax is same as SQL. But DQL command i.e
Select command syntax is different from SQL.
Example:
Select ename,sal into x,y
from emp
where empno=7369;
x = SMITH, y=800
END;
/
Output:
Enter value for empno: 7499
ALLEN 1600
<variable_name> <table_name>.<column_name>%type;
Example:
v_ename emp.ename%type;
%rowtype:
• It is used to hold entire row of a table.
• It can hold one record only at a time.
Advantages:
o It decreases number of variables
o It reduces complexity.
Example:
v_emprec emp%rowtype;
In the above example, v_emprec is variable of row type. It can hold
record of emp table.
v_exp := (sysdate-v_hiredate)/365;
v_exp := (sysdate-v_hiredate)/365;
IF v_exp>40 THEN
DELETE FROM emp WHERE empno=v_empno;
COMMIT ;
dbms_output.put_line(v_empno || ' employee record deleted');
END IF ;
END ;
/
Output:
Enter value for empno: 7499
emp exprience is:41 years
7499 employee record deleted
BEGIN
v_empno := &empno;
v_amount := &amount;
IF v_sal>5000 THEN
Rollback;
dbms_output.put_line('Rolled back successfully..');
ELSE
COMMIT ;
dbms_output.put_line('committed successfully...');
END IF ;
END ;
/
Ouptut:
Enter value for empno: 7369
Enter value for amount: 2000
committed successfully...
v_exp := (sysdate-v_hiredate)/365;
IF v_exp>=40 THEN
v_per := 0.2;
ELSE
v_per := 0.1;
END IF ;
Output:
Enter value for empno: 7900
emp exprience is:40 years
7900employee record updated....
.2 on sal increased
DECLARE
v_empno emp.empno%type;
v_job emp.job%type;
v_per float;
BEGIN
v_empno := &empno;
IF v_job='MANAGER' THEN
v_per := 0.2;
elsif v_job='CLERK' THEN
v_per := 0.15;
ELSE
v_per := 0.1;
END IF ;
END ;
/
Output:
Enter value for empno: 7369
Salary Updated.......15
DECLARE
v_sid std.sid%type;
v_stdrec std%rowtype;
v_resrec result%rowtype;
BEGIN
v_sid := &sid;
Cursors
Example:
Cursor c1 Is Select empno,ename,sal from emp;
Example:
Open c1;
Example:
Fetch c1 into x,y,z;
• Above statement fetches records and copies into x,y and z variables.
• One fetch statement can fetch one record only.
• To fetch multiple records, write fetch statement in loop.
Example:
Close c1;
Cursor Attributes:
Cursor attributes are:
• %found
• %notfound
• %rowcount
• %isopen
%found:
• It returns Boolean value true or false.
• If fetch is successful, it returns true.
• If fetch is unsuccessful, it returns false.
%notfound:
• It returns Boolean value true or false.
• It returns true when fetch is unsuccessful.
• It returns false when fetch is successful.
%RowCount:
• It returns number of rows fetched successfully.
%isopen:
• It returns Boolean value true or false.
• It returns true when cursor is open.
• It returns false when cursor is closed.
END ;
/
Output:
ALLEN 1600
WARD 1250
JONES 2975
MARTIN 1250
Loop
FETCH c1 INTO r;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line(r.empno || ' ' || r.ename || ' ' || r.job
|| ' ' || r.sal);
END Loop;
CLOSE c1;
END ;
/
Output:
7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
loop
FETCH c1 INTO v_sal;
EXIT WHEN c1%notfound;
v_sum := v_sum+v_sal;
end loop;
dbms_output.put_line('sum of salries=' || v_sum);
CLOSE c1;
END ;
/
Output:
sum of salries=32225
Program to find sum of salaries of all employees using cursor for loop:
DECLARE
CURSOR c1 IS SELECT sal FROM emp;
v_sum INT := 0;
BEGIN
FOR r IN c1
loop
v_sum := v_sum+r.sal;
end loop;
dbms_output.put_line('sum of salries=' || v_sum);
END ;
/
Output:
sum of salries=32225
Program to display emp name & salary using cursor for loop:
DECLARE
CURSOR c1 IS SELECT ename, sal FROM emp;
BEGIN
FOR r IN c1
Loop
dbms_output.put_line(r.ename || ' ' || r.sal);
END Loop;
END ;
/
Output:
ALLEN 1600
WARD 1250
JONES 2975
MARTIN 1250
FOR r IN c1
Loop
s := s || r.ename || ', ';
END Loop;
dbms_output.put_line(RTRIM(s,', '));
END ;
/
Output:
ALLEN, WARD, JONES, MARTIN
DECLARE
CURSOR c1 IS SELECT * FROM raise_Sal;
r raise_sal%rowtype;
BEGIN
OPEN c1;
Loop
FETCH c1 INTO r;
EXIT WHEN c1%NotFound;
UPDATE emp1 SET sal=sal+(sal*r.per/100) WHERE
empno=r.empno;
END Loop;
dbms_output.put_ line(c1%ROWCOUNT || ' records
updated...');
CLOSE c1;
END ;
/
Output:
14 records updated...
DECLARE
CURSOR c1 IS SELECT * FROM std;
sr std%rowtype;
rr result%rowtype;
BEGIN
OPEN c1;
Loop
FETCH c1 INTO sr;
EXIT WHEN c1%notfound ;
rr.tot := sr.m1+sr.m2+sr.m3;
rr.avrg := rr.tot/3;
IF sr.m1>=40 AND sr.m2>=40 AND sr.m3>=40 THEN
rr.result := 'PASS';
ELSE
rr.result := 'FAIL';
END IF ;
END LOOP;
dbms_output.put_line(c1%ROWCOUNT || ' rows inserted...');
CLOSE c1;
END ;
/
Output:
2 rows inserted...
Ref Cursor:
• Using Ref Cursor, select statement can de changed during program
execution.
• Normal Cursor Select Statement is static. We cannot change it.
Whereas Ref Cursor Select statement is dynamic. We can change it
during program execution.
• To declare Ref Cursor variable, we use sys_refcursor data type.
• We can use it as procedure parameter.
Advantages:
• Ref Cursor can be used for multiple select statements.
• It can be used as procedure parameter.
Syntax:
<variable_name> sys_refcursor;
Example:
c1 sys_refcursor;
Assigning Cursor:
Syntax:
Example:
Open c1 for Select * from emp;
…..
…..
Open c1 for Select * from Dept;
….
….
Open c1 for Select * from salgrade;
….
Program to display emp table records and dept table records using ref
cursor:
DECLARE
c1 sys_refcursor;
r1 emp%rowtype;
r2 dept%rowtype;
BEGIN
OPEN c1 FOR SELECT * FROM emp;
Loop
FETCH c1 INTO r1;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line(r1.ename || ' ' || r1.sal);
END Loop;
CLOSE c1;
Output:
JONES 4975
CLARK 4450
SCOTT 5000
KING 7000
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Types of Cursor:
There are 2 types of cursors. They are:
• Implicit Cursor
• Explicit Cursor
Implicit Cursor:
• The cursor created implicitly to process SELECT or DML
Statements.
• Implicit Cursor name is => SQL
Explicit Cursor:
The cursor is declared and defined by developer.
Exception Handling
Types of Errors:
There are 3 types of errors. They are:
• Compile Time Errors
• Logical Errors
• Run-Time Errors
Logical Errors:
The errors occur due to mistakes in logic is called “Logical Error”. It will not
be checked by the Oracle. Developer is responsible to write the correct
logic. Otherwise, we get wrong results.
Example:
For Depositing amount logic is add amount to balance. If we subtract, it is
logic error.
Run-Time Errors:
The errors occur at run-time are called “Run-Time errors”. Run-Time errors
are very dangerous. When run-time error occurs, application will be
terminated abnormally in the middle of execution. It will not execute
remaining code.
Example:
Divide with zero
Record not found in table
Inserting duplicate value in primary key field
Exception Handling:
Exception means Run-Time Error. The mechanism of handling run-time
errors is called “Exception Handling”.
Advantages:
• It avoids abnormal termination.
• Executes remaining code.
DECLARE
<declaration_part>
BEGIN
<execution_part>
EXCEPTION
When <Exception_Name> Then
--Handling Code
When <Exception_Name> Then
--Handling Code
.
.
When Others Then
--Handling Code
End;
/
Types of Exceptions:
There are 2 types of exceptions. They are:
• System-Defined Exceptions
• User-Defined Exceptions
System-Defined Exceptions:
The exception raised implicitly by the Oracle is called “System-Defined
Exception”.
Examples:
ZERO_DIVIDE
VALUE_ERROR
NO_DATA_FOUND
DUP_VAL_ON_INDEX
TOO_MANY_ROWS
ZERO_DIVIDE:
This exception will be raised when we try to divide with zero.
VALUE_ERROR:
This exception will be raised when size is exceeded, or data type is
mismatched.
NO_DATA_FOUND:
This exception will be raised when data is not found in the table.
DUP_VAL_ON_INDEX:
This exception will be raised when we try to insert duplicate value in
primary key column.
TOO_MANY_ROWS:
This exception will be raised when select query returns multiple rows.
User-Defined Exceptions:
The exception declared and raised by the user is called "User-Defined
Exception".
Examples:
abc
xyz
comm_is_null
one_divide
Syntax:
Exception_name Exception;
Example:
abc Exception;
one_divide Exception;
Syntax:
Raise Exception_Name;
Example:
Raise abc;
Raise one_divide;
RAISE_Application_Error:
In PL/SQL we can raise user-defined exception in 2 ways. They are:
• Using RAISE keyword
• Using RAISE_APPLICATION_ERROR
Syntax:
Raise_Application_Error(<Error_Code>, <Error_Message>);
Example:
Raise_Application_Error(-20050,‘u cannot divide with one’);
pragma exception_init:
There are 2 types in system-defined exceptions. They are:
• Named Exceptions
• Unnamed Exceptions
Named Exceptions:
The exceptions which are having names are called “Named Exceptions”.
Example:
o No_DATA_FOUND
o ZERO_DIVIDE
o DUP_VAL_ON_INDEX
o VALUE_ERROR
o TOO_MANY_ROWS
Unnamed Exceptions:
The errors which are not having any names are called “Unnamed
Exceptions”. Error code & messages are there but name is not there for
unnamed exceptions.
Example:
Check Constraint
Syntax:
pragma exception_init(<exception_name>, <error code>);
Example:
abc Exception;
pragma exception_init(abc,-2990);
Program-1:
Program to demonstrate ‘ZERO_DIVIDE’ Exception:
DECLARE
x number(4);
y number(4);
z FLOAT ;
BEGIN
x := &x;
y := &y;
z := x/y;
dbms_output.put_line('quotient=' || z);
EXCEPTION
WHEN zero_divide THEN
dbms_output.put_line('u cannot divide with zero');
WHEN value_error THEN
dbms_output.put_line('check the input. size or data type
mistake');
WHEN others THEN
dbms_output.put_line('run time error occured');
END ;
/
Output:
Case-1:
Enter value for x: 10
Enter value for y: 2
quotient=5
Case-2:
Enter value for x: 10
Enter value for y: 0
u cannot divide with zero
Case-3:
Enter value for x: 10
Enter value for y: 'ravi'
check the input. size or data type mistake
Program-2:
Program to demonstrate ‘NO_DATA_FOUND’ Exception:
DECLARE
v_empno emp.empno%type;
v_ename emp.ename%type;
v_sal emp.sal%type;
BEGIN
v_empno := &empno;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('this employee record not
available');
WHEN others THEN
dbms_output.put_line('run time error occured');
END ;
/
Output:
Case-1:
Enter value for empno: 7369
SMITH 18996.16
Case-2:
Enter value for empno: 9001
this employee record not available
Program-3:
Program to demonstrate DUP_VAL_ON_INDEX Exception:
Create a table with the name t1 with the field f1 as number type & set it as
primary key:
Create table t1(f1 number(4) primary key);
DECLARE
v_f1 t1.f1%type;
BEGIN
v_f1 := &f1;
INSERT INTO t1 VALUES(v_f1);
COMMIT ;
dbms_output.put_line('row inserted');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
dbms_output.put_line('PK should not accept
duplicate values');
END ;
/
Output:
Case-1:
Enter value for f1: 1001
row inserted
Case-2:
Enter value for f1: 1001
PK should not accept duplicate values
Program-4:
Program to demonstrate TOO_MANY_ROWS Exception:
DECLARE
v_job varchar2(10) ;
v_ename varchar2(100) ;
v_sal FLOAT ;
BEGIN
v_job := '&job';
EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('multiple rows selected..!');
END ;
/
Output:
Case-1:
Enter value for job: CLERK
SMITH 18996.16
Case-2:
Enter value for job: MANAGER
multiple rows selected..!
Program-5:
Program to demonstrate User-Defined Exception:
DECLARE
x INT ;
y INT ;
z FLOAT ;
one_divide Exception;
BEGIN
x := &x;
y := &y;
IF y=1 THEN
raise one_divide;
ELSE
z := x/y;
dbms_output.put_line('quotient=' || z);
END IF ;
EXCEPTION
WHEN one_divide THEN
dbms_output.put_line('u cannot divide with 1');
WHEN zero_divide THEN
dbms_output.put_line('u cannot divide with
zero');
END ;
/
Output:
Case-1:
Enter value for x: 10
Enter value for y: 2
quotient=5
Case-2:
Enter value for x: 10
Enter value for y: 1
u cannot divide with 1
Case-3:
Enter value for x: 10
Enter value for y: 0
u cannot divide with zero
Program-6:
Program to update salary of given empno. If employee commission is null
don’t update the salary and raise the exception.
DECLARE
v_empno emp.empno%type;
v_comm emp.comm%type;
comm_is_null Exception;
BEGIN
v_empno := &empno;
dbms_output.put_line('record updated..');
END IF ;
EXCEPTION
WHEN comm_is_null THEN
dbms_output.put_line('record not updated. because
comm is null');
END ;
/
Output:
Case-1:
Enter value for empno: 7521
record updated..
Case-2:
Enter value for empno: 7369
record not updated. because comm is null
Program-7:
Program to demonstrate RAISE_APPLICATION_ERROR:
DECLARE
v_empno emp.empno%type;
v_comm emp.comm%type;
comm_is_null Exception;
BEGIN
v_empno := &empno;
Output:
Case-1:
Enter value for empno: 7369
DECLARE
*
ERROR at line 1:
ORA-20050: COMM IS NULL. cannot update..!
ORA-06512: at line 12
Case-2:
Enter value for empno: 7521
record updated..!
Program-8:
Program to not to allow the user update on Sunday. If user tries to update
on Sunday then Raise the error using RAISE_APPLICATION_ERROR:
DECLARE
v_empno emp.empno%type;
BEGIN
v_empno := &empno;
IF to_char(sysdate,'dy')='sun' THEN
raise_Application_error(-20070,'Sunday updation not
allowed..!');
ELSE
UPDATE emp SET sal=sal+2000 WHERE empno=v_empno;
COMMIT ;
dbms_output.put_line('record updated..!');
END IF ;
END ;
/
Output:
Case-1 [On Sunday]:
Enter value for empno: 7369
DECLARE
*
ERROR at line 1:
ORA-20070: Sunday updation not allowed..!
ORA-06512: at line 6
Program-9:
Program to demonstrate PRAGMA EXCEPTION_INIT:
Create a table with the name t1 as following:
T1
Sid => Primary Key
Sname => Not Null
M1 => Check(M1>=0 and M1<=100)
Create table t1
(
Sid number(4) Primary Key,
Sname Varchar2(10) Not Null,
M1 Number(3) Check(M1>=0 and M1<=100)
);
DECLARE
v_sid t1.sid%type;
v_sname t1.sname%type;
v_m1 t1.m1%type;
check_violate EXCEPTION;
pragma exception_init(check_violate,-2290);
BEGIN
v_sid := &stdid;
v_sname := '&sname';
v_m1 := &m1;
Exception
WHEN dup_val_on_index THEN
END ;
/
Output:
Case-1:
Enter value for stdid: 1001
Enter value for sname: Ravi
Enter value for m1: 50
row inserted..!
Case-2:
Enter value for stdid: 1001
Enter value for sname: Kiran
Enter value for m1: 75
dup values not allowed in PK..!
Case-3:
Enter value for stdid: 1002
Enter value for sname: Sai
Enter value for m1: 123
check constraint violated..!
Stored Procedures
Types of Procedures:
There are 2 types of procedures. They are:
• Stored Procedures
• Packaged Procedures
Stored Procedure:
A procedure which is defined in schema[user] is called “Stored
Procedure”.
Packaged Procedure:
A procedure which is defined in package is called “Packaged
Procedure”.
Types of Parameters:
The local variable which is declared in procedure header is called
“Parameter”. It can be also called as “Argument”.
Example:
x IN Number
y OUT Number
z IN OUT Number
IN parameter:
• It is default one.
• It is used to get value into procedure from out of the procedure.
• It is READ-ONLY Parameter. We cannot change this parameter value
in the procedure.
• ‘IN’ keyword is used to define it.
• It can be variable or constant value from the procedure call.
OUT Parameter:
• It is used to send the value out of the procedure.
• We must use ‘OUT’ keyword to define it.
• It must be variable from the procedure call. It cannot be constant.
IN OUT Parameter:
• It is used to get value into procedure & same variable can be used
to send value out of the procedure.
• We must use ‘IN OUT’ keyword to define it.
• It must be variable from the procedure call. It cannot be constant.
Positional Notation:
In this, parameters are mapped based on the positions.
Named Notation:
In this, parameters are mapped based on the names.
Mixed Notation:
In this, parameters are mapped based on positions and names. A positional
parameter cannot be followed by named parameter.
Example:
CREATE OR REPLACE PROCEDURE addnum(x number,y number, z number)
IS
a number;
BEGIN
a:=x+y+z;
dbms_output.put_line('sum=' || a);
END;
/
Positional Notation:
SQL> execute addnum(10,20,30);
Output:
sum=60
Named Notation:
SQL> execute addnum(y=>10,z=>20,x=>30);
Output:
sum=60
Mixed Notation:
SQL> execute addnum(10,z=>20,y=>30);
Output:
sum=60
Note:
SQL> execute addnum(z=>20,30,x=>10);
Output:
ERROR at line 1:
ORA-06550: line 1, column 20:
PLS-00312: a positional parameter association may not follow a named
association
--MAIN Program:
DECLARE
a number;
b number;
BEGIN
a:=&a;
b:=&b;
addition(a,b); --calling from main program
END ;
/
Output:
Enter value for a: 20
Enter value for b: 30
sum=50
Program-2:
Procedure to add two number & send result out of the procedure:
CREATE OR REPLACE PROCEDURE
addnum(
x IN number,
y IN number,
z OUT number)
IS
BEGIN
z := x+y;
END ;
/
--MAIN Program:
DECLARE
a number;
b number;
c number;
BEGIN
a := &a;
b := &b;
addnum(a,b,c); --calling from main program
dbms_output.put_line('sum=' || c);
END ;
/
Output:
Enter value for a: 50
Enter value for b: 40
sum=90
SQL> print z
Z
----------
9
Program-3:
Procedure to find biggest in two different numbers & send biggest
number out of the procedure:
CREATE OR REPLACE PROCEDURE
bigin2(
x IN number,
y IN number,
big OUT number)
IS
BEGIN
IF x>y THEN
big := x;
ELSE
big := y;
END IF ;
END;
/
BIG
----------
20
Program-4:
Procedure to insert a record into table & return status:
Exception
WHEN others THEN
p_msg:=SQLERRM;
END ;
/
SQL> print s
S
--------------------------------------------------------------------------------
Record Inserted
SQL> print s
S
--------------------------------------------------------------------------------
ORA-00001: unique constraint (C##RAJU.SYS_C008461) violated
Program-5:
Procedure to update salary of an employee with specific amount:
CREATE OR REPLACE PROCEDURE
salary_increment(p_empno emp.empno%type, p_amt number)
IS
BEGIN
UPDATE emp SET sal=sal+p_amt WHERE empno=p_empno;
COMMIT ;
dbms_output.put_line('salary incremented..!');
END;
/
--MAIN Program:
DECLARE
v_empno emp.empno%type;
v_amt number;
BEGIN
v_empno:=&empno;
v_amt:=&amount;
salary_increment(v_empno,v_amt);
END ;
/
Output:
Enter value for empno: 7876
Enter value for amount: 1000
salary incremented..!
Program-6:
Procedure to update salary of an employee with specific amount & send
updated salary out of the procedure:
CREATE OR REPLACE PROCEDURE
salary_increment(p_empno emp.empno%type, p_amt number,
p_sal OUT emp.sal%type)
IS
BEGIN
UPDATE emp SET sal=sal+p_amt WHERE empno=p_empno;
COMMIT ;
--MAIN Program:
DECLARE
v_empno emp.empno%type;
v_amt number;
v_sal emp.sal%type;
BEGIN
v_empno:=&empno;
v_amt:=&amount;
salary_increment(v_empno,v_amt,v_sal);
dbms_output.put_line('updated salary is:' || v_Sal);
END ;
/
Output:
Enter value for empno: 7369
Enter value for amount: 2000
updated salary is:17996.16
SAL
----------
15517.08
Program-7:
Procedure to deposit the amount in account:
Create Table & Insert records as following:
Create Table Account
(
Acno Number(4),
Name Varchar2(10),
Balance Number(8,2)
);
Procedure:
CREATE OR REPLACE PROCEDURE
deposit(p_acno account.acno%type, p_amt number,
p_balance OUT account.balance%type)
IS
BEGIN
UPDATE account SET balance=balance+p_amt
WHERE acno=p_acno;
COMMIT ;
dbms_output.put_line('Deposit is successful..!');
BAL
----------
125000
Program-8:
Procedure to withdraw the amount from account:
Create Or Replace Procedure
withdraw(p_acno account.acno%type,
p_amt number,
p_balance OUT account.balance%type)
IS
BEGIN
Select balance into p_balance from ACCOUNT where acno=p_acno;
if p_amt>p_balance then
RAISE_APPLICATION_ERROR(-20050,'Insufficient Balance');
else
Update account set balance=balance-p_amt
where acno=p_acno;
COMMIT ;
dbms_output.put_line('Successful withdrawl..!');
end if ;
END ;
/
BAL
----------
120000
Program-9:
Procedure to demonstrate pragma autonomous_transaction:
CREATE OR REPLACE PROCEDURE
salary_increment(p_empno emp.empno%type, p_amt number)
IS
pragma autonomous_transaction;
BEGIN
UPDATE emp SET sal=sal+p_amt
WHERE empno=p_empno;
ROLLBACK ;
dbms_output.put_line('rolled back');
END ;
/
--MAIN Program:
BEGIN
UPDATE emp SET sal=sal+2000 WHERE empno=1234;
salary_increment(7499,1000);
COMMIT ;
END ;
/
Output:
rolled back
Note:
Above program rollbacks 7499 emp salary updating. Commits 1234 emp
salary updating. Two different transactions are created for procedure and
main program because of “pragma autonomous_transaction”.
Stored Functions
Types of Functions:
There are 2 types of functions. They are:
• Stored Functions
• Packaged Functions
Stored Function:
A function which is defined in schema[user] is called “Stored
Function”.
Packaged Function:
A function which is defined in package is called “Packaged Function”.
Program-1:
Define a Function to perform Arithmetic Operations:
Create or Replace Function calc(x number,y number, op char)
Return Number
IS
begin
IF op='+' THEN
RETURN (x+y);
elsif op='-' THEN
RETURN (x-y);
elsif op='*' THEN
RETURN (x*y);
ELSif op='/' THEN
RETURN (x/y);
END IF ;
end ;
/
--MAIN Program:
DECLARE
a number;
b number;
op char ;
r number;
BEGIN
a:=&a;
b:=&b;
op:='&op';
r:=calc(a,b,op);
dbms_output.put_line( r );
END ;
/
Output:
Case-1:
Enter value for a: 10
Enter value for b: 2
Enter value for op: +
12
Case-2:
Enter value for a: 10
Enter value for b: 2
Enter value for op: -
8
Case-3:
Enter value for a: 10
Enter value for b: 2
Enter value for op: *
20
Case-4:
Enter value for a: 10
Enter value for b: 2
Enter value for op: /
5
Program-2:
Define a function to get the balance of an account number:
Create Or Replace Function
Check_Balance(p_acno account.acno%type)
Return Number
IS
v_bal account.balance%type;
BEGIN
Select balance into v_bal from Account
where acno=p_acno;
return v_bal;
END ;
/
CHECK_BALANCE(1001)
-------------------
120000
Program-3:
Define a function to get experience of an employee:
Create or Replace Function experience(p_empno emp.empno%type)
Return Number
IS
v_hiredate date;
BEGIN
Select hiredate into v_hiredate from emp where empno=p_empno;
return trunc((sysdate-v_hiredate)/365);
END ;
/
Output:
EXPERIENCE(7369)
----------------
41
Program-4:
Define a function to display employees of a dept:
Create or Replace Function
getdeptemps(p_deptno emp.deptno%type)
Return sys_refcursor
IS
c1 sys_refcursor;
Begin
Open c1 for select * from emp where deptno=p_deptno;
Return c1;
End;
/
Output:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7782 CLARK MANAGER 7839 09-JUN-81 18424 10
7839 KING PRESIDENT 17-NOV-81 21987.75 10
Program-5:
Define a function to display top n employees as per salary:
CREATE OR REPLACE FUNCTION
gettopn(n number) RETURN sys_refcursor
IS
c1 sys_refcursor;
BEGIN
OPEN c1 FOR SELECT * FROM emp
RETURN c1;
END ;
/
Output:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- - -----------
7521 WARD SALESMAN 7698 22-FEB-81 33549.06 500 30
7369 SMITH CLERK 7902 17-DEC-80 22996.16 20
7839 KING PRESIDENT 17-NOV-81 21987.75 10
Program-6:
Define a Function to check an year is leap or not:
Create or Replace Function
isleap(y number) return varchar2
IS
d Date;
BEGIN
d := '29-FEB-' || y; --29-feb-2020
return 'Leap Year';
Exception
when others then
return 'Not Leap Year';
End ;
/
Program-7:
Define a function to calculate totalamount of an order:
Create Table & Insert records as following:
Orders o
oid pid qty
1001 2001 3
1001 2002 5
1002 2001 6
1002 2002 8
Products p
pid pname price
2001 A 500
2002 B 200
t:=t+r.qty*r.price;
End Loop;
Return t;
END;
/
ORDER_AMOUNT(1001)
------------------
2500
ORDER_AMOUNT(1002)
------------------
4200
Packages
Example:
Package Bank
opening_Account procedure
closing_Account procedure
deposit procedure
withdraw procedure
checkbal function
transaction_statement function
Advantages:
• We can group related procedures & functions.
• We can declare global variables. A global variable can be accessed
anywhere.
• It provides better maintenance.
• It provides better performance.
• We can overload the functions & procedures in a package.
• It provides Reusability.
Creating a Package:
Package Specification:
In this we declare the procedures and functions.
Package Body:
In this we define body of procedures and functions.
Program-1:
Define a package with following procedures and functions:
• Hiring an employee
• Firing an employee
• Updating Salary
• Getting Experience
• Getting top-n salaried employees
BEGIN
UPDATE emp SET sal=sal+p_amt
WHERE empno=p_empno;
COMMIT ;
dbms_output.put_line('record updated..!');
END salary_increment;
Output:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7521 WARD SALESMAN 7698 22-FEB-81 33549.06 500 30
7369 SMITH CLERK 7902 17-DEC-80 22996.16 20
Output:
HR.GETEXP(7369)
---------------
41
Output:
record inserted..!
Output:
record updated..!
Output:
record deleted..!
Program-2:
Create a package with the name ‘BANK’ with following procedures and
functions:
--creating package specification
CREATE OR REPLACE package BANK
IS
PROCEDURE deposit(p_acno account.acno%type, p_amt number);
PROCEDURE withdraw(p_acno account.acno%type, p_amt number);
FUNCTION checkbalance(p_acno account.acno%type) RETURN
number;
END ;
/
Output:
amount deposited...
Output:
amount withdrawn...!
Program-3:
Program to demonstrate Overloading:
END ;
/
Output:
P1.ADDN(10,20)
----------------
30
Output:
P1.ADDN(10,20,30)
-------------------
60
Triggers
Types of Triggers:
There are 3 types of Triggers. They are:
• Table Level Triggers
• Schema Level Triggers
• Database Level Triggers
Syntax:
Before Trigger:
o Before Trigger gets executed before performing DML
operation.
o First trigger gets executed.
o Then DML operation will be performed.
After Trigger:
o After Trigger gets executed after performing DML operation.
o First DML operation will be performed.
o Then trigger gets executed.
Syntax:
Create or Replace Trigger <Trigger_Name>
Before / After <trigger_event>
On <User_name>.schema
Declare
--variable declaration
Begin
--Statements
End ;
/
Syntax:
Create or Replace Trigger <Trigger_Name>
Before / After <trigger_event>
On Database
Declare
--variable declaration
Begin
--Statements
End ;
/
Compound Trigger:
• It is introduced in Oracle 11g.
• It is a set of triggers.
• It is used to define multiple actions in one trigger.
• Instead of defining multiple different triggers on one table, we can
define multiple actions in one trigger.
System Variables:
System Variable Purpose
ora_dict_obj_type returns object type like TABLE, VIEW, INDEX ..etc
ora_dict_obj_name returns object name like EMP, DEPT ..etc
ora_login_user returns user name
ora_sysevent returns the action CREATE, DROP, TRUNCATE
Program-1:
Define a Trigger not to allow the user to update emp data on sunday:
CREATE OR REPLACE TRIGGER t1
Before INSERT OR UPDATE OR DELETE
ON emp
BEGIN
IF to_char(sysdate,'dy')='sun' THEN
raise_application_error(-20050,'sunday updation not
allowed');
END IF ;
END ;
/
Output:
update emp set sal=sal+2000 where empno=7369
*
ERROR at line 1:
ORA-20050: sunday updation not allowed
ORA-06512: at "C##RAJU.T1", line 3
ORA-04088: error during execution of trigger 'C##RAJU.T1'
Program-2:
Define a Trigger to allow the user to update emp data as following:
From Monday to Friday => between 10 to 4 only
On Saturday => between 10 to 2 only
On Sunday => don’t allow for updation
CREATE OR REPLACE TRIGGER t2
Before INSERT OR DELETE OR UPDATE
ON emp
DECLARE
wd INT ;
h INT ;
BEGIN
wd := to_char(sysdate,'d');
h := to_char(sysdate,'hh24');
Output:
update emp set sal=sal+1000 where empno=7369
*
ERROR at line 1:
ORA-20070: u can update b/w 10 to 2 only on sat
ORA-06512: at "C##RAJU.T2", line 11
ORA-04088: error during execution of trigger 'C##RAJU.T2'
Program-3:
Define a trigger not to allow the user to update the empno:
Create Or Replace Trigger t3
Before Update of empno
On Emp
Begin
raise_Application_error(-20050,'u cannot update empno');
End;
/
Testing:
SQL> update emp set empno=1001 where empno=7369;
Output:
update emp set empno=1001 where empno=7369
*
ERROR at line 1:
ORA-20050: u cannot update empno
ORA-06512: at "C##RAJU.T3", line 2
ORA-04088: error during execution of trigger 'C##RAJU.T3'
Program-4:
Define a trigger to maintain deleted employee records in ‘emp_resign’
table:
Create Or Replace Trigger t4
AFTER Delete
On emp
For Each Row
Begin
insert into emp_resign(empno,ename,job,sal)
values(:OLD.empno,:OLD.ename,:OLD.job,:OLD.sal);
End;
/
Testing:
SQL> delete from emp where empno=7876;
Output:
deleted record stored in emp_resign table
Program-5:
Define a trigger to audit emp table:
END If;
INSERT INTO emp_audit
VALUES(user,op,systimestamp,:new.empno,:new.ename,
:new.sal,:old.empno,:old.ename,:old.sal);
END ;
/
Testing:
SQL> select * from emp_audit;
Output:
no rows selected
Output:
rec stored in emp_Audit
1 row created.
Output:
rec stored in emp_Audit
1 row updated.
Output:
rec stored in emp_Audit
1 row deleted.
Program-6:
Define a trigger not to allow the user to decrease the salary:
CREATE OR REPLACE TRIGGER t6
Before UPDATE
ON emp
FOR each row
BEGIN
IF :new.sal < :old.sal THEN
raise_application_error(-20050,'u cannnot decrease the
sal..!');
END IF ;
END ;
/
Testing:
SQL> update emp set sal=sal-1000 where empno=7369;
Output:
update emp set sal=sal-1000 where empno=7369
ERROR at line 1:
ORA-20050: u cannnot decrease the sal..!
ORA-06512: at "C##RAJU.T6", line 3
ORA-04088: error during execution of trigger 'C##RAJU.T6'
Program-7:
[Program to demonstrate schema level trigger]
Define a trigger not to allow c##raju user to drop the table:
Create Or Replace Trigger t7
Before Drop
On c##oracle11am.schema
BEGIN
IF ora_dict_obj_type = 'TABLE' Then
Raise_Application_Error(-20080,'u cannot drop the db object');
END If;
End;
/
Testing:
SQL> drop table emp;
Output:
drop table emp
*
ERROR at line 1:
ORA-04088: error during execution of trigger 'C##RAJU.T7'
ORA-00604: error occurred at recursive SQL level 1
ORA-20080: u cannot drop the db object
ORA-06512: at line 3
Program-8:
[Program to demonstrate Database Level Trigger]
Define a trigger not to allow many users to drop the table:
CREATE OR REPLACE TRIGGER t8
Before DROP
ON DATABASE
BEGIN
IF ora_login_user IN('C##ORACLE11AM','C##ORACLE6PM',
'C##ORACLE7AM') AND ora_dict_obj_type = 'TABLE' THEN
raise_application_error(-20050,'u cannot drop the table..!');
END IF ;
END ;
/
Testing:
SQL> conn c##oracle7am/nareshit
Output:
Connected.
Output:
drop table emp
*
ERROR at line 1:
ORA-04088: error during execution of trigger 'C##RAJU.T8'
ORA-00604: error occurred at recursive SQL level 1
ORA-20050: u cannot drop the table..!
ORA-06512: at line 4
Program-9:
Define a trigger to perform auditing on DDL commands:
Create a table as following:
Create table ddl_audit
(
Uname varchar2(10),
Date_time timestamp,
Action varchar2(10),
Obj_name varchar2(10),
Obj_Type varchar2(10)
);
Testing:
SQL> drop table student;
Output:
Table dropped.
Program-10:
Program to demonstrate Compound Trigger:
CREATE OR REPLACE TRIGGER t10
FOR UPDATE ON emp
compound TRIGGER
BEFORE STATEMENT IS
BEGIN
dbms_output.put_line('before statement');
END BEFORE STATEMENT;
AFTER STATEMENT IS
BEGIN
dbms_output.put_line('after statement');
END AFTER STATEMENT;
END ;
/
Testing:
SQL> update emp set sal=sal+1000 where job='MANAGER';
Output:
before statement
before each row
after each row
before each row
after each row
before each row
after each row
after statement
3 rows updated.
Dynamic SQL
Program-1:
Define a procedure to drop the table:
CREATE OR REPLACE PROCEDURE
drop_table(n varchar2)
IS
BEGIN
EXECUTE immediate 'drop table ' || n;
dbms_output.put_line(n || ' table dropped..!');
END ;
/
Program-2:
Define a procedure to drop any kind of database object:
Create Or Replace Procedure
Program-3:
Define a procedure to drop all views:
Create Or Replace Procedure
drop_All_views
Is
Cursor c1 Is Select view_name from user_views;
Begin
for n in c1
Loop
execute immediate 'Drop view ' || n.view_name;
dbms_output.put_line('All views dropped..!');
End Loop;
End;
/
Program-4:
Define a procedure to display table wise no of rows:
Create or Replace Procedure
no_of_rows_in_tables
IS
Program-5:
Define a procedure to add a column:
Create Or Replace Procedure
add_column(tn varchar2,fn varchar2,dt varchar2)
Is
Begin
execute immediate 'Alter Table ' || tn || ' add ' || fn || ' ' || dt;
dbms_output.put_line('column added..!');
End ;
/