Oracle
Oracle
Database :-
A Database is a collection of Information that is Organized so that it can be easily accessed ,updated
And deleted
DB
DBMS :-
A Database management system (DBMS) can be a set of software programs that controls the storage and
retrieval of data in a database. It also controls the security and integrity of the database. The DBMS accepts
requests for data from the application program and instructs the operating system to transfer the
appropriate data.
Data security prevents unauthorised users from viewing or updating the database. Using passwords, users
are allowed access to the entire database or subsets of the database, For example, an employee database
can contain all the data about an individual employee, but one group of users may be authorised to view
only payroll data, while others are allowed access to only work history and medical data. The DBMS can
maintain the integrity of the database by not allowing more than one user to update the same record at
the same time. Organisations may use one kind of DBMS for daily transaction processing and then move
the detail onto another computer that uses another DBMS better suited for analysis.
Advantages :-
Disadvantages:-
Naresh it Technologies
ORACLE 12c
Development of DBMS :-
1. DBMS developers - These are the people that design and build the DBMS product, and the only ones
who touch its code. They are typically the employees of a DBMS vendor (e.g., Oracle, IBM, Microsoft)
2. Application developers and Database administrators - These are the people that design and build a
database-based application that uses the DBMS. The latter group members design the needed
database and maintain it.
3. Application's end-users :- These people know the application and its end-user interfaces, but need
neither to know nor to understand the underlying DBMS.
ER MODEL :
Entities
Naresh it Technologies
ORACLE 12c
Attributes
Relationships
Entity :-
An entity may be a physical object such as a house or a car, an event such as a house sale or a car service,
or a concept such as a customer transaction or order.Entities can be thought of as nouns. Examples: a
computer, an employee, a vehicle
Entity Set :-
Collection of entities that share common characterstics is called entity set. In ERD entity set is represented
by using symbol rectangle.
Attributes :-
Entity properties are called attributes , for example Properties of employee entity includes
Empno,Ename,Job,Sal etc.
Relationship :-
Types of relationships:-
One-to-one (1:1)
One-to-many(1:m)
Many-to-Many(m:n)
One-to-one relationship :-
If one entity of an entity set associated with one entity of another entity set then it is called
one-to-one relationship.
One-to-one relationship :-
Naresh it Technologies
ORACLE 12c
If one entity of an entity set associated with many entity of another entity set then it is
called one-to-many relationship.
many-to-many relationship :-
If many entities of an entity set associated with many entities of another entity set then it is
called one-to-many relationship.
RDBMS:-
The concept of a relational database was first developed by E.FCODD. The relation, which is a two-
dimensional table, is the primary unit of storage in a relational database. A relational database can contain
one or more of these tables, with each table consisting of a unique set of rows and columns. A record
stored in a table is called row, also known as a tuple, while attributes of the data are defined in columns, or
fields, in the table. The characteristics of the data, or the column, relates one record to another. Each
column has a unique name and the content within it must be of the same type.
Dr. Codd defined thirteen standards which must be met before a database can be considered to be
relational database:
0. A relational DBMS must be able to manage databases entirely through its relational capabilities.
3. Systematic null value support–The DBMS provides systematic support for the treatment of null values
(unknown or inapplicable data), distinct from default values, and independent of any domain.
4. Active, online relational catalog–The description of the database and its contents is represented at the
logical level as tables and can therefore be queried using the database language.
5. Comprehensive data sublanguage–At least one supported language must have a well-defined syntax
and be comprehensive. It must support data definition, manipulation, integrity rules, authorization, and
transactions.
6. View updating rule–All views that are theoretically updatable can be updated through the system.
7. Set-level insertion, update, and deletion — The DBMS supports not only setlevel retrievals but also set-
level inserts, updates, and deletes.
8. Physical data independence–Application programs and ad hoc programs are logically unaffected when
physical access methods or storage structures are altered.
9. Logical data independence–Application programs and ad hoc programs are logically unaffected, to the
extent possible, when changes are made to the table structures.
Naresh it Technologies
ORACLE 12c
10. Integrity independence–The database language must be capable of defining integrity rules. They must
be stored in the online catalog, and they cannot be bypassed.
11. Distribution independence–Application programs and ad hoc requests are logically unaffected when
data is first distributed or when it is redistributed.
12. Nonsubversion–It must not be possible to bypass the integrity rules defined through the database
language by using lower-level languages.
In RDBMS :-
ORACLE 11g
Oracle provides a flexible RDBMS called Oracle11g. Using its features, you can store and manage
data with all the advantages of a relational structure plus PL/SQL, an engine that provides you with the
ability to store and execute program units. Oracle11g also supports Java and XML.
The Oracle server offers the options of retrieving data based on optimization techniques. It includes
security features that control how a database is accessed and used. Other features include consistency
and protection of data through locking mechanisms.
Oracle versions :-
Table partitioning
Naresh it Technologies
ORACLE 12c
SQL
Structured Query Language (SQL) is the set of statements with which all programs and users access data in
an Oracle database.
The language, Structured English Query Language ("SEQUEL") was developed by IBM Corporation, Inc.
SEQUEL later became SQL (still pronounced "sequel").
All major relational database management systems support SQL,so you can transfer all skills you have
gained with SQL from one database to another. In addition, all programs written in SQL are portable. They
can often be moved from one database to another with very little modification.
Efficient
Easy to learn and use
With SQL, you can define, retrieve, and manipulate data in the tables
Naresh it Technologies
ORACLE 12c
SQL Standards:-
Oracle SQL complies with industry-accepted standards.. Industry-accepted committees are the American
National Standards Institute (ANSI) and the International Standards Organization (ISO). Both ANSI and ISO
have accepted SQL as the standard language for relational databases.
Writing SQL Statements
Using the following simple rules and guidelines, you can construct valid statements that are both easy to
read and easy to edit:
SQL*Plus :-
SQL*Plus is an Oracle tool that recognizes and submits SQL statements to the Oracle server for execution
and contains its own command language.
• Execute SQL statements to retrieve, modify, add, and remove data from the database
• Format, perform calculations on, store, and print query results in the form of reports
• Create script files to store SQL statements for repetitive use in the future
Naresh it Technologies
ORACLE 12c
SQL vs SQL*PLUS :-
Schema :- a user in oracle db is called schema and objects created by user are called schema objects
Logging In to sql*plus :-
Open sql*plus
Enter username & password
Enter host string
Datatypes :-
When you create a table or cluster, you must specify a datatype for each of its columns. When you create a
procedure or stored function, you must specify a datatype for each of its arguments. These datatypes
define the domain of values that each column can contain or each argument can have. For example, DATE
columns cannot accept the value February 29 (except for a leap year) or the values 2 or ’SHOE’. Each value
Naresh it Technologies
ORACLE 12c
subsequently placed in a column assumes the column’s datatype. For example, if you insert ’01-JAN-98’
into a DATE column, Oracle treats the ’01-JAN-98’ character string as a DATE value after verifying that it
translates to a valid date.
CHAR(size) :-
Fixed-length character data of length size bytes.Maximum size is 2000 bytes. Default and minimum size is
1 byte.
VARCHAR2(size) :-
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000
bytes, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2.
NCHAR(size) :-
Fixed-length character data of length size characters or bytes, depending on the choice of national
character set. Maximum size is determined by the number of bytes required to store each character, with
an upper limit of 2000 bytes. Default and minimum size is 1 character or 1 byte, depending on the
character set.
NVARCHAR2(size) :-
Variable-length character string having maximum length size characters or bytes, depending on the choice
of national character set. Maximum size is determined by the number of bytes required to store each
character, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2.
NUMBER(p,s) :-
Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from
-84 to 127
LONG :-
DATE :-
Allows date & time but Time is optional if not entered by user then oracle inserts 12:00AM.Valid date
range from January 1, 4712 BC to December 31, 9999 AD.a Date field occupies 7 bytes of memory
TIMESTAMP (fractional_seconds_precision) :-
Year, month, and day values of date, as well as hour, minute, and second values of time, where
fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field.
Accepted values of fractional_seconds_precision are 0 to 9. The default is 6.
Naresh it Technologies
ORACLE 12c
All values of TIMESTAMP as well as time zone displacement value, where fractional_seconds_precision is
the number of digits in the fractional part of the SECOND datetime field.Accepted values are 0 to 9. The
default is 6.a The codes listed for the datatypes are used internally by Oracle. The datatype code of a
column or object attribute is returned by the DUMP function.
All values of TIMESTAMP WITH TIME ZONE, with the following exceptions and Data is normalized to the
database time zone When it is stored in the database. When the data is retrieved, users see the data in the
session time zone.
Stores a period of time in years and months, whereyear_precision is the number of digits in the YEAR
datetime field. Accepted values are 0 to 9. The default is 2.
Stores a period of time in days, hours, minutes, and seconds, where day_precision is the maximum
number of digits in the DAY datetime field. Accepted values are 0 to 9. The default is 2.and
fractional_seconds_precision is the number of digits in the fractional part of the SECOND field. Accepted
values are 0 to 9. The default is 6
RAW(size) :-
Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value.
LONG RAW :-
ROWID :-
Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for
values returned by the ROWID pseudocolumn.
UROWID [(size)] :-
Hexadecimal string representing the logical address of a row of an index-organized table. The optional size
is the size of a column of type UROWID. The maximum size and default is 4000 bytes.
CLOB :-
A character large object containing single-byte characters. Both fixed-width and variable-width character
sets are supported, both using the CHAR database character set. Maximum size is 4 gigabytes.
NCLOB :-
Naresh it Technologies
ORACLE 12c
A character large object containing unicode characters. Both fixed-width and variable-width character sets
are supported, both using the NCHAR database character set. Maximum size is 4 gigabytes. Stores national
character set data.
BLOB :-
BFILE :-
Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to
external LOBs residing on the database server. Maximum size is 4 gigabytes.
BINARY_FLOAT :-
32-bit single precision floating point number datatype. Binary float equires 5 bytes including a length byte.
BINARY_DOUBLE:-
64-bit double precision floating point number datatype. Binary double requires 9 bytes including a length
byte.
OCA question :-
1 Which three statements are true regarding the data types in Oracle Database 10g/11g?
2 You need to create a table for a banking application. One of the columns in the table has the
following requirements:
1) You want a column in the table to store the duration of the credit period.
2) The data in the column should be stored in a format such that it can be easily added and subtracted with
DATE data type without using conversion functions.
3) The maximum period of the credit provision in the application is 30 days.
4) The interest has to be calculated for the number of days an individual has taken a credit for.
Which data type would you use for such a column in the table?
Naresh it Technologies
ORACLE 12c
OPERATORS IN ORACLE :-
ARTHMETIC OPERATORS :-
+ - * /
Operator precedence:-
RELATIONAL OPERATORS :-
Used for comparision , different relational operators supported by oracle
Operator Description
LOGICAL OPERATORS :-
SPECIAL OPERATORS :-
||
BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT
Naresh it Technologies
ORACLE 12c
Creating table :-
Standard tables
Partitioned tables
Clustered tables
Index organized tables
External tables
Global temporary tables
Standard Table :-
Syntax:-
Example:-
OCA Question :-
Syntax:-
Naresh it Technologies
ORACLE 12c
Example :-
NOTE:-
Order of values in the INSERT command should match with order of columns declared in table.to insert
values in different order then we need to specify the order.
Absent
Unknown
Not Applicable
NULL is not equal to 0 and not equal to space
NULL values can be inserted in two ways.
EXPLICITLY
IMPLICITLY
Example :-
Naresh it Technologies
ORACLE 12c
These variables are prefixed with &. Values assigned to these variables exists upto the command , once
command execution is completed values assigned to these variables are erased.
Example:-
Instead of inserting TZH (time zone hour), we can also insert TZR (time zone region) as follows
Naresh it Technologies
ORACLE 12c
You can add or subtract one INTERVAL YEAR TO MONTH literal to or from another to yield another
INTERVAL YEAR TO MONTH literal.
For example:-
INTERVAL '5-3' YEAR TO MONTH + INTERVAL'20' MONTH = INTERVAL '6-11' YEAR TO MONTH
INTERVAL '4 5:12:10.222' DAY TO SECOND(3) 4 days, 5 hours, 12 minutes, 10.222 seconds
INTERVAL '4 5:12' DAY TO MINUTE 4 days, 5 hours and 12 minutes.
INTERVAL '400 5' DAY(3) TO HOUR 400 days 5 hours.
INTERVAL '400' DAY(3) 400 days.
INTERVAL '11:12:10.22' HOUR TO SECOND(7) 11 hours, 12 minutes, and 10.2222222 seconds.
INTERVAL '11:20' HOUR TO MINUTE 11 hours and 20 minutes.
Naresh it Technologies
ORACLE 12c
You can add or subtract one DAY TO SECOND interval literal from another DAY TO SECOND literal. For
example.
Virtual Columns :-
When queried, virtual columns appear to be normal table columns, but their values are derived rather than
being stored on disc. The syntax for defining a virtual column is listed below.
If the datatype is omitted, it is determined based on the result of the expression. The GENERATED ALWAYS
and VIRTUAL keywords are provided for clarity only.
Example :-
SQL>CREATE TABLE employees (
id NUMBER,
first_name VARCHAR2(10),
last_name VARCHAR2(10),
salary NUMBER(9,2),
comm NUMBER(3),
hra NUMBER GENERATED ALWAYS AS (SAL*0.3) VIRTUAL,
CONSTRAINT employees_pk PRIMARY KEY (id)
);
Querying the table shows the inserted data plus the derived hra
Naresh it Technologies
ORACLE 12c
Note:-
Indexes defined against virtual columns are equivalent to function-based indexes.
Virtual columns can be referenced in the WHERE clause of updates and deletes, but they cannot be
manipulated by DML.
Limitations :-
A virtual column can only be of scalar datatype . It can’t be a user defined type, LOB or RAW.
All columns mentioned as part of the virtual column expression should belong to the same table.
No DMLs are allowed on the virtual columns.
The virtual column expression can’t reference any other virtual column.
Virtual columns can only be created on ordinary tables. They can’t be created on index-organized,
external, object, cluster or temporary tables.
SQL statements may contain literal single quotes in them, such as when a possessive form of a noun is used
(e.g., 'Robert's Bike'). Prior to Oracle 10g, the literal quotes had to be double quoted to make it clear to the
SQL or PL/SQL engine that they were literal (e.g., Robert''s Bike). This can make the code much less
readable and can cause errors that be difficult to find.
Oracle 10g introduces a solution to this problem in the form of user-specified quote character assignment.
With this new functionality, the ' symbol can be replaced by just about any single- or multibyte delimiter or
the character pairs [ ], { }, ( ), or < >.
The delimiter is defined by using the quote operator, q, followed by a quote and then the assigned
replacement quote delimiter to be used. Here is an example that uses the bracket pair ([ ]) as quote
delimiters:
SQL> INSERT INTO record VALUES (q'[Robert's book is good isn't it?]');
SQL> SELECT * FROM record
WHERE the_value=q'XRobert's book is good isn't it?X';
THE_VALUE
Naresh it Technologies
ORACLE 12c
--------------------------------------------------
Robert's book is good isn't it?
In this example, a record was inserted into the RECORD table. A bracket set was used as the delimiter.
Then, the same record was queried, this time using the letter X as the delimiter. In both cases, there are
single quotes at the beginning after the q operator, and at the very end after the final delimiter.
Data Retrieval :-
SELECT statement can be used to retrieve data from database.
• Selection:- You can use the selection capability in SQL to choose the rows in a table that you .
You can use various criteria to restrict the rows that you see.
• Joining: You can use the join capability in SQL to bring together data that is stored in different
tables by creating a link between them.
Syntax :-
In the syntax :-
Naresh it Technologies
ORACLE 12c
NOTE:-
Naresh it Technologies
ORACLE 12c
Arthmetic Expressions :-
an arithmetic expression contain column names,constant numeric values and athmetic operator.
Example :-
Operator precedence :-
The above example displays the ename, sal, and annual sal of employees. It calculates the annual sal as 12
multiplied by the monthly salary, plus a one-time bonus of 100. Notice that multiplication is performed
before addition.
Concatenation Operator:-
Example :-
Literals in ORACLE:-
A Literal is a Constant
Types of Literals :-
String constant
Numeric constant
Date constant
Naresh it Technologies
ORACLE 12c
Example :-
SQL>SELECT ename || ‘ EARNS ‘|| sal*12 ||’ PER YEAR’ FROM emp;
OCA question :-
Evaluate the following query:
Declaring Alias:-
An Alias is an another name or alternative name, aliases in Oracle are of two types.
Column Alias
Table Alias
Column Alias :-
Alias declared for column is called column alias.
Syntax :-
COLNAME / EXPR [AS] ALIAS
If alias contains spaces or special characters then alias must be enclosed in “ “
Example :-
Display ename,sal,comm and in report display sal as basic and comm as bonus ?
SQL>SELECT ename,sal AS basic,comm AS bonus FROM emp;
Display ename , annual salary ?
SQL>SELECT ename,sal*12 AS “ANNUAL SALARY” FROM emp;
Display ename,sal,hra,da,tax,totsal ?
SQL>SELECT ename,sal,sal*0.3 AS hra,sal*0.2 AS da, sal*0.1 AS tax ,
Naresh it Technologies
ORACLE 12c
OCA question :-
. You need to produce a report where each customer's credit limit has been incremented by $1000. In the
output, the customer's last name should have the heading Name and the incremented credit limit should
be labeled New Credit Limit. The column headings should have only the first letter of each word in
uppercase .
Clauses in ORACLE :-
WHERE
ORDER BY
DISTINCT
GROUP BY
HAVING
ON
USING
START WITH
CONNECT BY
WITH
RETURNING
FOLLOWS
MODEL
You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause contains a
condition that must be met, and it directly follows the FROM clause. If the condition is true, the row
meeting the condition is returned.
syntax:
Naresh it Technologies
ORACLE 12c
• Column name
• Comparison operator
• Column name, constant, or list of values
Examples :-
Display employee record whose empno=7844 ?
SQL>SELECT * FROM emp WHERE empno=7844 ;
BETWEEN operator:-
You can display rows based on a range of values using the BETWEEN operator. The range that you
specify contains a lowerlimit and an upperlimit . Values specified with the BETWEEN condition are
inclusive. You must specify the lower limit first.
Example :-
Naresh it Technologies
ORACLE 12c
Example :-
OCA question :-
IN operator :-
To test for values in a specified list of values, use IN operator. The IN operator can be used with any data
type. If characters or dates are used in the list, they must be enclosed in single quotation marks (’’).
Syntax:-
IN (V1,V2,V3------------);
Example :-
Note :-
LIKE operator:-
You may not always know the exact value to search for. You can select rows that match a character pattern
by using the LIKE operator. The character pattern-matching operation is referred as wildcard search.
Syntax:-
LIKE ‘pattern’
NOT LIKE ‘pattern’
Pattern consists of alphabets,digits and metacharacters. The different meta characters in ORACLE
% denotes zero or many characters.
_ denotes one character.
Naresh it Technologies
ORACLE 12c
OCA question :-
You need to extract details of those products in the SALES table where the PROD_ID column contains the
string '_D123'. ?
Which WHERE clause could be used in the SELECT statement to get the required output?
IS operator :
The IS operator tests for nulls. A null value means the value is unavailable, unassigned,unknown, or
inapplicable. Therefore, you cannot test with = because a null cannot be equal or unequal to any value.
Syntax :-
IS NULL
IS NOT NULL
Example:-
Display employee records whose comm. Is null ?
Operator Precedence :-
1 Arithmetic Operator
2 Concatenation Operator
3 Comparison Operator
4 IS [NOT] NULL ,LIKE , [NOT] IN
5 [NOT] BETWEEN
6 NOT logical condition
7 AND logical condition
8 OR logical condition
Naresh it Technologies
ORACLE 12c
ORDER BY Clause :-
The order of rows returned in a query result is undefined. The ORDER BY clause can be used to sort the
rows. If you use the ORDER BY clause, it must be the last clause of the SQL statement. You can specify an
expression, or an alias, or column position in ORDER BY clause.
Syntax:-
In the syntax:
ORDER BY specifies the order in which the retrieved rows are displayed.
ASC orders the rows in ascending order ( default order)
DESC orders the rows in descending order
Numeric values are displayed with the lowest values firs for example 1–999.
Date values are displayed with the earliest value first for example 01-JAN-92 before 01-JAN-95.
Character values are displayed in alphabetical order—for example, A first and Z last.
Null values are displayed last for ascending sequences and first for descending sequences.
Examples :-
Arrange employee records in ascending order of their sal ?
Display employee records working for 10th dept and arrange the result in ascending order of their sal ?
Arrange employee records in ascending of their deptno and with in dept arrange records in descending
order of their sal ?
In ORDER BY clause we can use column name or column position , for example
In the above example records are sorted based on the fifth column in emp table.
Naresh it Technologies
ORACLE 12c
Arrange employee records in descending order of their comm. If comm. Is null then arrange those records
last ?
OCA :-
1 Which two statements are true regarding the ORDER BY clause? (Choose two.)
2 Which statement is true regarding the default behavior of the ORDER BY clause?
DISTINCT clause :-
Syntax :-
DISTINCT collist / *
OCA question :-
Using the CUSTOMERS table, you need to generate a report that shows 50% of each credit amount in
each income level. The report should NOT show any repeated credit amounts in each income level. Which
query would give the required result?
Naresh it Technologies
ORACLE 12c
D. SELECT cust_income_level ||' '|| cust_credit_limit * 0.50 AS "50% Credit Limit" FROM customers;
DML commands :-
INSERT
UPDATE
DELETE
INSERT ALL
MERGE
Syntax:-
Example :-
SQL>INSERT INTO emp_temp
SELECT * FROM emp;
In the above example first SELECT statement gets data from EMP table and inserts data into EMP_TEMP
table and command will be successful only if both tables structure is same.
UPDATE command :-
Update command is used to modify data in a table.
Syntax:-
Examples :-
Update all employees commission to 500 ?
Increment employee salary by 10% and comm. By 20% Those who are working as SALESMAN ?
Naresh it Technologies
ORACLE 12c
Returning Clause:-
DELETE command :-
Syntax:-
INSERT ALL command used to insert data into multiple tables.Using INSERT ALL command we can extract
data from one or more tables and insert data into multiple tables.
INSERT ALL
INTO <TAB1> VALUES (VALUE LIST)
INTO <TAB2> VALUES(VALUE LIST)
Naresh it Technologies
ORACLE 12c
SELECT STATEMENT ;
Example :-
Create table two tables as follows
Emp1(empno,ename,sal)
Emp2(empno,ename,sal)
Copy data from emp to emp1,emp2
SQL>INSERT ALL
INTO emp1 VALUES(empno,ename,sal)
INTO emp2 VALUES(empno,ename,sal)
SELECT empno,ename,sal FROM emp;
scenario :-
Suppose we have sales table with the following structure.
Sales
Prodid Prodname Mon_Amt Tue_Amt Wed_Amt Thu_Amt Fri_Amt Sat_Amt
101 AIWA 2000 2500 2230 2900 3000 2100
102 AKAI 1900 2100 2130 3100 2800 2120
Now we want to add the rows from SALES table Weekly_Sales Table in the following
Structure.
To achieve the above we can give a multi table INSERT statement given below
SQL>Insert all
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Mon’,mon_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Tue’,tue_amt)
Naresh it Technologies
ORACLE 12c
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Wed’,wed_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Thu’,thu_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Fri’,fri_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Sat’,sat_amt)
Select prodid,prodname,mon_amt,tue_amt,wed_amt,thu_amt,Fri_amt,sat_amt from sales;
Syntax :-
INSERT ALL
WHEN COND1 THEN
INTO <TAB1> VALUES (VALUE LIST)
WHEN COND2 THEN
INTO <TAB2> VALUES (VALUE LIST)
SELECT STATEMENT ;
Example :-
Copy data from emp to emp1 , emp2 based on the following conditions
SQL>INSERT ALL
WHEN job=’CLERK’ THEN
INTO emp1 VALUES(empno,ename,sal)
WHEN job=’MANAGER’ THEN
INTO emp2 VALUES(empno,ename,sal)
SELECT empno,ename,sal FROM emp;
MERGE Statement:-
the new MERGE SQL command (sometimes referred to as "UPSERT") is a DML command that enables us to
optionally update or insert data into a target table, depending on whether matching records already exist.
In versions prior to 9i, we would have to code this scenario either in separate bulk SQL statements or in
PL/SQL.
Syntax :-
MERGE INTO <TARGETTABLE> <ALIAS>
USING <SOURCE TABLE>/QUERY <ALIAS>
ON (CONDITION)
Naresh it Technologies
ORACLE 12c
records that satisfy the ON condition are updated , if condition is not matched then record is inserted.
Example :-
EMPS EMPT
1 A 5000-UPDATE 1 A 2000
2 B 3000 2 B 3000
3 C 4000 3 C 4000
4 D 6000-INSERT
OCA question :-
You need to load information about new customers from the NEW_CUST table into the tables CUST and
CUST_SPECIAL. If a new customer has a credit limit greater than 10,000, then the details have to be
inserted into CUST_SPECIAL. All new customer details have to be inserted into the CUST table. Which
technique should be used to load the data most efficiently?
DDL commands :-
CREATE
ALTER
DROP
TRUNCATE
RENAME
Naresh it Technologies
ORACLE 12c
Syntax :-
Example :-
Create table emp11 from table emp ?
After executing above command a new table is created called emp11 from the result of SELECT
Statement
Because no record in emp table satisfies condition 1=2 , so no record is copied to EMP12 only the
structure is copied.
ALTER command :-
ALTER command is used to modify data definition of a table.ALTER command is used to do following
operations.
ADD A COLUMN(S)
DROP A COLUMN(S)
TO RENAME A COLUMN
MODIFY A COLUMN
INCR/DECR FIELD SIZE
CHANGING DATATYPE
CHANGING FROM NULL TO NOT NULL
CHANGING FROM NOT NULL TO NULL.
TO MAKE TABLE READ ONLY
Adding a Column:-
Syntax :-
Naresh it Technologies
ORACLE 12c
Example:-
SQL>ALTER TABLE emp ADD (dob DATE);
Droping a Column:-
Syntax :-
ALTER TABLE <TABNAME> DROP COLUMN COLNAME ;
Example :-
SQL>ALTER TABLE emp DROP COLUMN dob;
SQL>ALTER TABLE emp DROP (ename,sal);
NOTE :- all columns in a table cannot be dropped , because the table should contain atleast one column.
Renaming a Column :-
Syntax:-
ALTER TABLE <tabname> RENAME COLUMN <oldname> to <newname> ;
SQL>ALTER TABLE emp RENAME COLUMN sal TO salary ;
Modifying a Column:-
Syntax :-
ALTER TABLE <TABNAME>
MODIFY(COLNAME DATATYPE(SIZE) ,-----------)
Changing Datatype:-
NOTE :-
Naresh it Technologies
ORACLE 12c
From ORACLE 11g we can make the table as read only , prior to ORACLE 11g we can do this through view.
A read only table doesn’t allow DML operations.
TRUNCATE command :-
DELETE TRUNCATE
RENAME command :-
Syntax :-
Naresh it Technologies
ORACLE 12c
Example :-
OCA question :-
Integrity Constraints
Integrity constraints are the rules in real life, which are to be imposed on the data. If the data is not
satisfying the constraints then it is considered as inconsistent. These rules are to be enforced on data
because of the presence of these rules in real life. These rules are called integrity constraints. Every DBMS
software must enforce integrity constraints, otherwise inconsistent data is generated.
Naresh it Technologies
ORACLE 12c
Unique Constraint
Primary Constraint
Refrential Integrity :-
A refrential integrity constraint states that the values of the foreign key value should match with values
of primary key/unique Column of another or same table. Foreign key constraint establishes relationship
between tables.
If a foreign key in one table refers primary key/unique column of the same table then it is called self
refrential Integrity.
Domain constraints:-
A domain means a set of values assigned to a column. Domain constraints are handled by
The above said constraints are implemented in oracle with the help of
NOT NULL
UNIQUE
PRIMARY KEY
CHECK
FOREIGN KEY
The above constraints can be declared at
Column level
Table level
Column level :-
Table level :-
Syntax :-
Columnname Datatype(size) NOT NULL
Example :-
SQL> CREATE TABLE emp(
Empno NUMBER(4),
Ename VARCHAR2(20) NOT NULL,
Job VARCHAR2(20) ,
Naresh it Technologies
ORACLE 12c
Mgr NUMBER(4),
Hiredate DATE,
Sal NUMBER(7,2),
Comm NUMBER(7,2),
Deptno NUMBER(2) );
1 row created
UNIQUE constraint :-
Columns declared with UNIQUE constraint does not accept duplicate values.
One table can have a number of unique keys.
By default UNIQUE columns accept null values unless declared with NOT NULL constraint
Oracle automatically creates UNIQUE index on the column declared with UNIQUE constraint
UNIQUE constraint can be declared at column level and table level.
Syntax :-
Example :-
Syntax :-
Colname Datatype(size) PRIMARY KEY
Example :-
SQL> CREATE TABLE dept(deptno NUMBER(4) CONSTRAINT pk_dept PRIMARY KEY,
dname VARCHAR2(20) ,
loc VARCHAR2(20) );
Naresh it Technologies
ORACLE 12c
Example :-
1000 10 100
1000 11 50
1001 10 20
1001 11 50
In the above example values of OrderId are repeated ,so it cannot be taken as primary key. And the values
of ProdId are also repeated , so it cannot be taken as primary key . when it is not possible with single
column to uniquely identify the records then take combination of columns. In the above example
combination or OrdId & ProdId is not repeated so this combination can be taken as PRIMARY KEY.if
combination uniquely identifies the records then it is called composite primary key.
CHECK Constraint :-
Check constraint validates data based on a condition .
Value entered in the column should not violate the condition.
Check constraint allows null values.
Check constraint can be declared at table level or column level.
Limitations :-
Conditions should not contain pseudo columns like ROWNUM,SYSDATE etc.
Condition should not access columns of another table
Declaring Check Constraint Column level :-
Syntax :-
Example :-
Naresh it Technologies
ORACLE 12c
Table :- Managers
Foreign key is a column in one table that refers primary key/unique columns of
another or same table.
Values of foreign key should match with values of primary key/unique or foreign key
can be null.
Foreign key column allows null values unless it is declared with NOT NULL.
To establish 1:1 relationship between two tables declare foreign key with unique
constraint
Composite foreign key must refer composite primary key or Composite unique key.
Naresh it Technologies
ORACLE 12c
Syntax :-
Colname datatype(size) [constraint <name>] REFERENCES tabname(colname)
Example :-
Creating Parent table :-
SQL> CREATE TABLE dept
(deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY,
dname VARCHAR2(20) ,
loc VARCHAR2(20)) ;
Example :-
Constraints can be also be added to an existing table with the help of ALTER command
Syntax :-
Naresh it Technologies
ORACLE 12c
Note:- primary key constraint cannot be added to a column that already contains duplicates or NULL
values.
NOVALIDATE option :-
If constraint added with NOVALIDATE option then oracle doesn’t validate existing data and validates only
future DML operations.
Droping Constraints :-
Syntax :-
ALTER TABLE <TABNAME> DROP CONSTRAINT <NAME>
Example :-
SQL>ALTER TABLE emp55 DROP CONSTRAINT pk_emp55;
SQL>ALTER TABLE emp55 DROP CONSTRAINT ck_sal_emp55
Note :-
Naresh it Technologies
ORACLE 12c
Enabling/Disabling a Constraint:
If the constraints are present, then for each DML operation constraints are checked by executing certain
codes internally. It may slow down the DML operation marginally. For massive DML operations, such as
transferring data from one table to another because of the presence of constraint, the speed will be
considered slower. To improve the speed in such cases, the following methods are adopted:
Disable constraint
Performing the DML operation DML operation
Enable constraint
Disabling Constraint:-
Syntax :-
ALTER TABLE <tabname> DISABLE CONSTRAINT <constraint_name> ;
Example :-
SQL>ALTER TABLE emp DISABLE CONSTRAINT ck_sal_emp ;
SQL>ALTER TABLE dept DISABLE PRIMARY KEY CASCADE;
NOTE:-
If constraint is disabled with CASCADE then PK is disabled with FK.
Enabling Constraint :-
Syntax :-
ALTER TABLE <TABNAME> ENABLE CONSTRAINT <NAME>
Example :-
SQL>ALTER TABLE emp ENABLE CONSTRAINT ck_sal_emp;
Reporting Constraint Exceptions:-
If exceptions exist when a constraint is validated, an error is returned and the integrity constraint remains
novalidated. When a statement is not successfully executed because integrity constraint exceptions exist,
the statement is rolled back.
To determine which rows violate the integrity constraint, issue the ALTER TABLE statement with the
EXCEPTIONS option in the ENABLE clause. The EXCEPTIONS option places the rowid, table owner, table
name, and constraint name of all exception rows into a specified table.
Example :-
Naresh it Technologies
ORACLE 12c
A more informative query would be to join the rows in an exception report table and the master table to
list the actual rows that violate a specific constraint.
SQL>SELECT deptno, dname, loc FROM dept, EXCEPTIONS
WHERE EXCEPTIONS.constraint = 'SYS_C00610'
AND
dept.rowid = EXCEPTIONS.row_id;
DEPTNO DNAME LOC
---------- -------------- -----------
10 ACCOUNTING NEW YORK
10 RESEARCH DALLAS
Example :-
Naresh it Technologies
ORACLE 12c
2 3 4
2 2 0
2 6 0
the clause deferrable causes postponing of the enforcement of constraint checking. Therefore, no error is
issued even though second and third row violates the constraint. If you issue commit, the whole
transaction is rolled back and you will not get all the rows that are inserted prior to it. If initially deferred is
specified then that constraint is checked at the end of the transaction.If the rows that are manipulated by
the transaction do not satisfy the constraint, then the whole transaction is rolled back. When initially
immediate is specified, which is also the default setting then the constraints are enforced at the end of
every DML statement.
When the clause deferrable is used, the behavior of constraint can be changed in the transaction by using
the set constraint command.
ON DELETE NO ACTION :-
If foreign key declared with ON DELETE NO ACTION then parent record cannot be deleted if any child
records exists.
ON DELETE CASCADE :-
If foreign key declared with ON DELETE CASCADE then if any parent record is deleted then dependent child
records also deleted automatically.
Naresh it Technologies
ORACLE 12c
UPDATE RULE :-
Update rules specifies that value of PK cannot be updated if it referenced by any FK.
USER_CONSTRAINTS
USER_CONS_COLUMNS
ALL_CONSTRAINTS
DBA_CONSTRAINTS
Example :-
CONSTRAINT_NAME CONSTRAINT_TYPE
PK_EMP P
Naresh it Technologies
ORACLE 12c
SYS_C004455 C
CK_SAL_EMP C
FK_DNO_EMP R
Oracle gives same code for CHECK and NOT NULL constraint , to know whether constraint is CHECK or NOT
NULL use SEARCH_CONDITION as given below.
Display which columns are declared with what constraints in EMP table ?
SQL>SELECT constraint_name , column_name FROM user_constraints WHERE table_name=’EMP’;
OCA question :-
The above command fails when executed. What could be the reason?
A. SYSDATE cannot be used with the CHECK constraint.
B. The BETWEEN clause cannot be used for the CHECK constraint.
C. The CHECK constraint cannot be placed on columns having the DATE data type.
D. ORD_NO and ITEM_NO cannot be used as a composite primary key because ORD_NO is also the
FOREIGN KEY.
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
Built-in Functions
functions are a very powerful feature of SQL and can be used to do the following:-
Naresh it Technologies
ORACLE 12c
Character functions:-
These functions mainly operate on character data.
Syntax:- UPPER(string)
Example:-
HELLO
Syntax:- LOWER(string)
Example:-
hello
Naresh it Technologies
ORACLE 12c
Syntax:- INITCAP(string)
Example :-
Hello Welcome
Syntax :- LENGTH(string)
Example :-
Example:-
ello
lcom
Display employee records whose name starts with and ends with same character ?
Display employee records whose name starts between ‘A’ AND ‘P’ ?
Naresh it Technologies
ORACLE 12c
Example:-
Scenario :-
1 CUSTOMER TABLE :-
from the above email addresses display only the first part ?
2 CUSTOMER_TABLE :-
CNAME
Rahuld dravid
Virendra sehwag
Sachin ramesh tendulkar
Sourav ganguly
Mahindra singh dhoni
From the above customer names display only those names that contains 3 parts ?
SQL>SELECT * FROM customer WHERE INSTR(cname,’ ‘,1,2) > 0;
Example:-
HELLO
HELLO
Example:-
HELLO
HELLO
HELLO
HELLO
Syntax :- LPAD(string1,length,string2)
*****hello
Naresh it Technologies
ORACLE 12c
ENAME HIREDATE
SMITH 17-DEC-80
ALLEN 20-FEB-81
WARD 22-FEB-81
USERID
Smi17DEC80
All20FEB81
War22FEB81
Syntax:- TRANSLATE(string1,string2,string3)
Example:-
Syntax :- CONCAT(str1,str2)
Example :-
Example :-
Example :-
SQL>SELECT ASCII(‘A’) FROM DUAL ;
65
CHR :- returns character for a given ASCII value
Syntax :- CHR(ascii value)
Example :-
SQL>SELECT CHR(65) FROM DUAL ;
A
Date Functions:-
Naresh it Technologies
ORACLE 12c
Syntax:- ADD_MONTHS(DATE,MONTHS)
Example:-
Display ename,sal,hiredate and date of retirement , assume that date of retiment is 30 years after date of
join ?
Example:-
31-MAY-12
Syntax:- MONTHS_BETWEEN(date1,date2)
Example:-
12
Example :-
27-MAY-12
Mathematical Functions:-
Naresh it Technologies
ORACLE 12c
Syntax:- ABS(number)
Example:-
10
SIGN :-
Syntax :- SIGN(expr)
Syntax :- POWER(M,N)
Example :-
Syntax :- SQRT(N)
Example:-
Syntax:- MOD(m,n)
Example:-
Naresh it Technologies
ORACLE 12c
Example:-
10
Syntax:- FLOOR(number)
Example:-
Example:-
Naresh it Technologies
ORACLE 12c
Syntax:- TRUN(m,n)
Example :-
3.45
01-JAN-2012
Conversion Functions :-
These functions are used to convert from one datatype to another datatype
implicit conversion
explicit conversion
Implicit Conversion:-
For assignments, the oracle server can automatically convert the following.
FROM TO
VARCHAR2 NUMBER
VARCHAR2 DATE
NUMBER VARCHAR2
DATE VARCHAR2
For expression evaluation , the oracle server can automatically convert the following .
FROM TO
Naresh it Technologies
ORACLE 12c
VARCHAR2 NUMBER
VARCHAR2 DATE
2000
Explicit Conversion:-
if conversion is performed by user then it is called explicit conversion.The following functions are used to
do explicit conversion
1 TO_CHAR
2 TO_DATE
3 TO_NUMBER
TO_CHAR :-
This function is used to convert DATE / NUMBER to CHAR type
Century formats :-
Year Formats :-
Naresh it Technologies
ORACLE 12c
Example :-
Quarter :-
Example :-
Month :-
MM Month Number 1
Naresh it Technologies
ORACLE 12c
Example :-
Day :-
Example :-
Week :-
Time :-
HH hour in 12-format 12
HH24 hour in 24-format 23
MI minute 20
SS second 30
AM/PM AM/PM as appropriate
Example :-
Display sysdate as follows ?
25 january 2012 , Monday 10:00:00 AM
Naresh it Technologies
ORACLE 12c
Example :-
SQL>SELECT TO_CHAR(SYSDATE,’J’) FROM DUAL;
2439892
The above number representes number of days passed since 01 JAN 4712BC to SYSDATE.
To change default DATE format during the session execute following command
When above query is executed then HIREDATEs are displayed in MM/DD/YY format.
OCA question :-
You need to display the date 11-oct-2007 in words as 'Eleventh of October, Two Thousand Seven'.
Which SQL statement would give the required result?
Format Description
Naresh it Technologies
ORACLE 12c
Example :-
TO_DATE :-
Used to convert string to datetime. You can provide an optional format to indicate the format of string.if
you omit format , the date must be in the default format usually (DD-MON-YYYY ,DD-MON-YY).
Example :-
The above statement returns ORACLE error INVALID NUMBER , because 26-AUG-2012 is treated as string ,
so to do the calculation conversion is required.
Example :-
You need to insert date & time into dob column , but by default DATE datatype accepts only DATE but not
time. To insert date along with time conversion is required.
But TIMESTAMP datatype allows both date and time without conversion.
Naresh it Technologies
ORACLE 12c
To insert time into DATE column conversion is required , but to insert time into TIMESTAMP column
conversion is not required.
Difference between two DATES returns days , but difference between two TIMESTAMPS returns
days,hours,min,sec,milli secs.
TO_NUMBER() :-
2000
Special Functions :-
DECODE Function :-
Decode functions works like if-then-else
Syntax :-
DECODE(expr,value1,return expr1,
Value2, return expr2,
---------------,
[default expr])
Example :-
SQL>SELECT ename,sal,
DECODE(job, ’CLERK’,’WORKER’,
‘MANAGER’,’BOSS’,
‘PRESIDENT’,’BIG BOSS’,
‘EMPLOYEE’) AS JOB FROM emp;
SQL>UPDATE emp
SET sal = DECODE(deptno,10, DECODE(job,’CLERK’,SAL*1.1,
‘MANAGER’,SAL*1.15,
SAL*1.05) ,
20, DECODE(JOB,’CLERK’,SAL*1.15,
‘MANAGER’,SAL*1.2,
SAL*1.05) ,
SAL) ;
NVL:-
Syntax :-
NVL(expr1,expr2)
If expr1 is NULL then NVL function returns expr2 otherwise returns expr1 only.
Example :-
Naresh it Technologies
ORACLE 12c
NVL2 :-
Syntax :-
NVL2(expr1,expr2,expr3)
Example :-
GREATEST :-
Syntax :- GREATEST(expr1,expr2,expr4,----)
Example :-
LEAST :-
Syntax: LEAST(expr1,expr2,expr3)
Example:-
NULLIF :-
Syntax:- NULLIF(expr1,expr2)
COALESCE:-
The Oracle COALESCE function returns the first non-NULL expression in the list. If all expressions in the list
evaluate to NULL, then the COALESCE function will return NULL. The database evaluates each expression's
Naresh it Technologies
ORACLE 12c
value and determines whether it is NULL, rather than evaluating all of the expressions before determining
if any of them are NULL.
Syntax:-
The following example uses the sample product_information table to organize a clearance sale of products.
It gives a 10% discount to all products with a list price. If there is no list price, then the sale price is the
minimum price. If there is no minimum price, then the sale price is "5":
OCA question :-
1 Which two statements are true regarding single row functions? (Choose two.)
2 Generate a report showing the total compensation paid to each employee to till date.
SQL>SELECT ename ||' joined on ' hiredate || ', the total compensation paid is '||
ROUND(ROUND(SYSDATE-hiredate)/365) *12* sal + NVL(comm,0)) “Until Date “
FROM emp;
3 Which tasks can be performed using SQL functions built into Oracle Database ? (Choose three.)
PROD_ID PROD_LIST_PRICE
123456 152525.99
Naresh it Technologies
ORACLE 12c
A. 152526 ****
B. **152525.99
C. 152525** **
D. an error message
CUST_NAME
Renske Ladwig
Jason Mallin
Samuel McCain
Allan MCEwen
Irene Mikkilineni
You need to display customers' second names where the second name starts with "Mc" or "MC."
Which query gives the required output?
6 Which SQL statements would display the value 1890.55 as $1,890.55? (Choose three .)
7 In the CUSTOMERS table, the CUST_CITY column contains the value 'Paris' for the
CUST_FIRST_NAME 'ABIGAIL'.
Naresh it Technologies
ORACLE 12c
A. Abigail PA
B. Abigail Pa
C. Abigail IS
D. an error message
8 Which statements are true regarding data type conversion in expressions used in queries? (Choose
all that apply.)
9 You need to calculate the number of days from 1st January 2007 till date.
Dates are stored in the default format of dd-mon-rr.
Which SQL statements would give the required output? (Choose two .)
Multi-Row functions:-
These functions will process group of rows and Returns one value from that group.
MAX :-
Syntax:- MAX(expr)
Example :-
Naresh it Technologies
ORACLE 12c
MIN:-
Syntax :- MIN(EXPR)
Example:-
SUM :-
Syntax:- SUM(expr)
Example:-
Scenario :-
? ? ?
AVG :-
Returns avg value of a given expression.
Syntax:- AVG(expr)
Example:-
COUNT :-
Naresh it Technologies
ORACLE 12c
Syntax :- COUNT(expr)
Example:-
COUNT(*):-
Returns no of records
Example :-
? ? ?
Which two statements are true regarding the COUNT function? (Choose two.)
A. The COUNT function can be used only for CHAR, VARCHAR2, and NUMBER data types.
B. COUNT(*) returns the number of rows including duplicate rows and rows containing NULL
value in any of the columns.
C. COUNT(cust_id) returns the number of rows including rows with duplicate customer IDs and
NULL value in the CUST_ID column
D. COUNT(DISTINCT inv_amt)returns the number of rows excluding rows containing duplicates and
NULL values in the INV_AMT column.
E. A SELECT statement using the COUNT function with a DISTINCT keyword cannot have a WHERE
clause.
CASE Statement :-
Naresh it Technologies
ORACLE 12c
Simple case.
Searched case .
Syntax :-
CASE search_expression
WHEN expression1 THEN result1
WHEN expression2 THEN result2
…………………….
WHEN expression THEN result
ELSE default_result
END ;
result1, result2,………….., result are the returned results(one for each possible expression). If expression1
evaluates to search_expression, results is returned, and similarly for the other expressions.
Example :-
SQL>SELECT ename,sal, CASE job
WHEN ‘CLERK’ THEN ‘WORKER’
WHEN ‘MANAGER’ THEN ‘BOSS’
WHEN ‘PRESIDENT’ THEN ‘BIG BOSS’
ELSE
‘EMPLOYEE’
END AS JOB
FROM emp ;
Syntax :-
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
………………..
WHEN condition THEN result
Naresh it Technologies
ORACLE 12c
ELSE
default_result
END;
Where,
condition1, condition2,…….. conditionN are expressions to be evaluated.
result1, result2,…………resultN are the returned results(one for each possible condition). If condition is
true, result1 is returned, and similarly for the other expressions.
Example :-
OCA question :-
PROMO_BEGIN _DATE
04-jan-00
10-jan-00
15-dec-99
18-oct-98
You want to display the number of promotions started in 1999 and 2000.
D SELECT
COUNT(DECODE(SUBSTR(TO_CHAR(promo_begin_date,'yyyy'), 8), '1999', 1, 0)) "1999",
COUNT(DECODE(SUBSTR(TO_CHAR(promo_begin_date,'yyyy'), 8),'2000', 1,0)) "2000"
FROM promotions;
Naresh it Technologies
ORACLE 12c
GROUP BY clause:-
GROUP BY clause is used to group or categorize data. In other words it divide the rows in a table into
smaller groups. You can then use the group functions to return summary information for each group.if
GROUP BY clause is not specified then default grouping is entire result set.When query executes and data
is fetched , it is grouped based on GROUP BY clause and the group function is applied.
Syntax :-
For Example to find total salary for each department manually first we group records based on the basis of
department .
Examples :-
SQL>SELECT
EXTRACT(YEAR FROM hiredate) AS YEAR, COUNT(*) AS EMPS
FROM emp
GROUP BY EXTRACT(YEAR FROM hiredate);
Naresh it Technologies
ORACLE 12c
HAVING clause :-
In the same way that you use the WHERE clause to restrict the rows that you select, you can use the
HAVING clause to restrict groups.
find the maximum salary of each department, but show only the depts. that have a maximum salary more
than 10,000, you need to do the following:
2. Restrict the groups to those departments with a maximum salary greater than 10,000.
The Oracle server performs the following steps when you use the HAVING clause:
Deptno SUM(SAL)
20 10875
WHERE Vs HAVING :-
WHERE HAVING
Use where clause if cond doesn’t Use Having clasue if conditions doesn’t
Contains group function contain group functions
NOTE:- in condition if there is no group function then use WHERE clause , if condition contains group
function use HAVING clause.
Using WHERE , GROUP BY ,HAVING clauses Together :-
You can use WHERE,GROUP BY, and HAVING clauses together in the same query. When you do this the
WHERE clause first filters the rows, the GROUP BY clause then groups the remaining rows and finally
HAVING clause filters the groups.
Naresh it Technologies
ORACLE 12c
Example :-
SQL>SELECT deptno,sum(sal) FROM emp
WHERE deptno IN (10,20)
GROUP BY deptno
HAVING SUM(sal) > 10000 ;
Calcuate total salaries department wise and within department job wise ?
Example :-
SQL>SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY deptno,job;
SQL>BREAK ON deptno
SQL> /
GROUP BY TO_CHAR(hiredate,’YYYY’) ,
TO_CHAR(hiredate,’Mon’) ,
TO_CHAR(hiredate,’Dy’)
ORDER BY Year,Month,Day ;
Cross Tabulation:-
10 1300 2450
20 1900 2975
30 95 2850 5600
Cross tabulation is simplified in ORACLE 11g with the help of PIVOT operator.
SQL>SELECT * FROM
(SELECT DEPTNO,SAL,JOB FROM EMP)
PIVOT
(
SUM(SAL) FOR JOB IN (‘CLERK’,’MANAGER’,’SALESMAN’)
)
ORDER BY DEPTNO;
UNPIVOT operator :-
The UNPIVOT operator converts column-based data into separate rows. To see the UNPIVOT operator in
action we need to create a test table.
SQL>INSERT INTO unpivot_test VALUES (1, 101, 10, 20, 30, NULL);
SQL>INSERT INTO unpivot_test VALUES (2, 102, 40, NULL, 50, NULL);
SQL>INSERT INTO unpivot_test VALUES (3, 103, 60, 70, 80, 90);
Naresh it Technologies
ORACLE 12c
SQL>INSERT INTO unpivot_test VALUES (4, 104, 100, NULL, NULL, NULL);
SQL>COMMIT;
1 101 10 20 30
2 102 40 50
3 103 60 70 80 90
4 104 100
The UNPIVOT operator converts this column-based data into individual rows.
SQL>SELECT *
FROM unpivot_test
UNPIVOT (quantity FOR product_code IN (product_code_a AS 'A', product_code_b AS 'B',
product_code_c AS 'C', product_code_d AS 'D'));
ID CUSTOMER_ID P QUANTITY
---------- ----------- - ----------
1 101 A 10
1 101 B 20
1 101 C 30
2 102 A 40
2 102 C 50
3 103 A 60
3 103 B 70
3 103 C 80
3 103 D 90
4 104 A 100
SQL> desc t1
NAME VARCHAR2(10)
YEAR NUMBER(4)
VALUE NUMBER(4)
SQL>SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY ROLLUP(deptno,job)
ORDER BY deptno,job ;
Naresh it Technologies
ORACLE 12c
CUBE :-
Cube returns rows containing a subtotal for all combinations of columns, plus a row containing the grand
total.
Example : -
SQL>SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY CUBE(deptno,job)
ORDER BY deptno,job ;
Naresh it Technologies
ORACLE 12c
GROUPING function:-
It can be quite easy to visually identify subtotals generated by rollups and cubes, but to do it
programatically you really need something more accurate than the presence of null values in the grouping
columns. This is where the GROUPING function comes in. It accepts a single column as a parameter and
returns "1" if the column contains a null value generated as part of a subtotal by a ROLLUP or CUBE
operation or "0" for any other value The following query demonstrates the usage of GROUPING function.
Example :-
Naresh it Technologies
ORACLE 12c
GROUPING_ID function :-
The GROUPING_ID function provides an alternate and more compact way to identify subtotal rows. Passing
the GROUP BY columns as arguments, it returns a number indicating the GROUP BY level.
GROUPING SETS :-
Calculating all possible subtotals in a cube, especially those with many columns, can be quite an intensive
process. If you don't need all the subtotals, this can represent a considerable amount of wasted effort. if
cube applied on three columns then it gives 8 levels of subtotals.
If we only need a few of these levels of subtotaling we can use the GROUPING SETS expression and
specify exactly which ones we need, saving us having to calculate the whole cube.
Naresh it Technologies
ORACLE 12c
OCA questions :-
1 Evaluate the following SQL statement:
The above query generates an error on execution. Which clause in the above SQL statement causes the
error?
A. WHERE
B. SELECT
C. GROUP BY
D. ORDER B
2 Which statement would display the highest credit limit available in each income level in each city in the
CUSTOMERS table?
Naresh it Technologies
ORACLE 12c
Joins
In OLTP db tables are normalized and data organized in more than one table. For example sales DB is
organized in customer,product,supplier tables etc. JOIN is an operation that combines rows from two or
more tables or view.
ORACLE performs JOIN operation when more than one table is listed in FROM clause.
Types of JOINS :-
Join Condition :-
Child.fk = parent.pk ( if relationship exists)
Oracle performs INNER JOIN by comparing fk value with pk value by using = operator.
INNER JOIN is also called EQUI JOIN because join cond is based on = operator.
INNER JOIN returns all rows from both tables that satisfies the JOIN CONDITION.
No of JOIN CONDS depends on number of tables to be joined .
To join N tables , min N-1 JOIN CONDS are required.
Guidelines:-
When writing a SELECT statement that joins tables, precede the column name with the table name or table
alias for faster access and to avoid ambiguity.
Naresh it Technologies
ORACLE 12c
Example:-
Display EMPNO,ENAME,DEPTNO,DNAME,LOC ?
SQL>SELECT e.ename
FROM emp e, dept d
WHERE e.deptno = d.deptno
AND
d.loc=’NEW YORK’ ;
Display ENAME of the employees working at NEW YORK location and earning more than 2000 ?
SQL>SELECT e.ename
FROM emp e,dept d
WHERE e.deptno=d.deptno
AND
d.loc=’NEW YORK’ and e.sal > 2000;
Naresh it Technologies
ORACLE 12c
SQL>SELECT
e.first_name,e.salary,j.job_title,d.department_name,l.city,l.street_address,l.state_province,
c.country_name,r.region_name
FROM employees e,
jobs j,
departments d,
locations l,
countries c,
regions r
WHERE e.job_id = j.job_id
AND
e.department_id = d.department_id
AND
d.location_id = l.location_id
AND
l.country_id = c.country_id
AND
c.region_id = r.region_id ;
ANSI Style :-
Oracle 9i now supports the ANSI/ISO SQL: 1999 standards. This allows easier product migration, but there
is no performance increase compared to the existing syntax.
Example :-
Using ON clause :-
SQL>SELECT e.empno,e.ename,e.sal,d.dname,d.loc
FROM emp e JOIN dept d
ON (e.deptno = d.deptno) ;
SQL>SELECT e.empno,e.ename,e.sal,d.dname,d.loc
FROM emp e JOIN dept d
USING (DEPTNO) ;
HINT :- In USING clause common column name should not be prefixed with table alias.
Naresh it Technologies
ORACLE 12c
NOTE :- A join order is the order in which tables are accessed and joined together. For example, in a join
order of table1, table2, and table3, table table1 is accessed first. Next, table2 is accessed, and its data is
joined to table1. Finally, table3 is accessed, and its data is joined to the result of the join between table1
and table2.
When the Join Cond is based on equality operator, the join is said to be an equi join. When the join
condition based on otherthan equality operator , the join is said to be a non-equi join.
Syntax:-
Select col1,col2,…….
From <table 1>,<table 2>
Where <join cond> [AND <join cond> AND <cond> ----]
In NON-EQUI JOIN JOIN COND is not based on = operator. It is based on other than = operator
usually BETWEEN or > or < operators.
Example:-
Display EMPNO,ENAME,SAL,GRADE ?
Display EMPNO,ENAME,SAL,DNAME,LOC,GRADE ?
SQL>SELECT e.empno,e.ename,e.sal,d.dname,d.loc,s.grade
FROM emp e,dept d,salgrade s
WHERE e.deptno = d.deptno
AND
e.sal between g.losal AND g.hisal ;
ANSI Style :-
Display EMPNO,ENAME,SAL,GRADE ?
SQL>SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e JOIN salgrade g
ON ( e.sal BETWEEN g.losal AND g.hisal) ;
Display EMPNO,ENAME,SAL,DNAME,LOC,GRADE ?
SQL>SELECT e.empno,e.ename,e.sal,d.dname,d.loc,s.grade
FROM emp e JOIN dept d
USING(deptno)
JOIN salgrade s
ON (e.sal BETWEEN g.losal and g.hisal) ;
Naresh it Technologies
ORACLE 12c
Self Join :-
Joining a table to itself is called Self Join.
Self Join is performed when tables having self refrential integrity.
To perform Self Join same table must be listed twice with different alias.
Self Join is Equi Join within the table.
Syntax :-
SQl>SELECT <collist>
From Table1 T1, Table1 T2
Where T1.Column1=T2.Column2;
Example:-
Display EMPNO,ENAME,SAL,MGRNAME ?
SQL>SELECT e.empno,e.ename,e.sal,m.ename
FROM emp e, emp m
WHERE e.mgr = m.empno ;
ANSI Style:-
Display EMPNO,ENAME,SAL,MGRNAME ?
Display EMPNO,ENAME,SAL,DNAME,LOC,GRADE,MGRNAME ?
SQL>SELECT e.empno,e.ename,e.sal,d.dname,d.loc,,s.grade,m.ename
FROM emp e JOIN dept d
USING(deptno)
JOIN salgrade s
ON (e.sal BETWEEN g.losal AND g.hisal)
JOIN emp m
ON ( e.mgr = m.empno) ;
Outer Join:-
Equi join returns only matching records from both the tables but not unmatched record, an outer join
retrieves a row even when one of the column in the join contains a null value. For example there are two
tables one is CUSTOMER that stores customer information and another ORDERS table that stores orders
placed by customers , INNER JOIN returns only the list of customer who placed orders,but OUTER JOIN also
returns customer who did not placed any order. Outer join is 3 types.
Naresh it Technologies
ORACLE 12c
LEFT OUTER JOIN returns all rows(matched and unmatched) from LEFT SIDE table and matching records
from RIGHT SIDE table. To perform LEFT OUTER JOIN (+) should be on RIGHT SIDE.
Syntax :-
Example :-
Display EMPNO,ENAME,DNAME,LOC and also display employee list who are not assigned to any dept?
ANSI Style :-
In SQL/92 standard use keyword LEFT OUTER JOIN instead of using operator (+) .
Display EMPNO,ENAME,DNAME,LOC and also display employee list who are not assigned to any dept?
RIGHT OUTER JOIN returns all rows(matched and unmatched) from RIGHT SIDE table and matching records
from LEFT SIDE table. To perform RIGHT OUTER JOIN use (+) on LEFT SIDE.
Syntax :-
SELECT <collist> FROM <tablist>
WHERE t1.commoncolumn(+) = t2.commoncolumn
Example :-
Display EMPNO,ENAME,DNAME,LOC and also display department which are empty ?
ANSI Style :-
In SQL/92 standard use keyword RIGHT OUTER JOIN instead of using operator (+) .
Naresh it Technologies
ORACLE 12c
CROSS JOIN :-
Example:-
TABLE TABLE
ORDERS DISCOUNT
ORDAMT DIS
100000 5
7
12
ANSI Style :-
Naresh it Technologies
ORACLE 12c
Natural Join :-
Example :-
SQL>SELECT e.empno,e.ename,e.sal,d.dname,d.loc
FROM emp e NATURAL JOIN dept d ;
Above query performs JOIN operation on DEPTNO.
OCA question :-
The statement fails when executed. Which change fixes the error?
2 In which two cases would you use an outer join? (Choose two.)
3 Which two statements are true regarding the USING and ON clauses in table joins? (Choose two.)
A. Both USING and ON clauses can be used for equijoins and nonequijoins.
B. A maximum of one pair of columns can be joined between two tables using the ON clause.
Naresh it Technologies
ORACLE 12c
C. The ON clause can be used to join tables on columns that have different names but
compatible data types.
D. The WHERE clause can be used to apply additional conditions in SELECT statements containing
the ON or the USING clause.
4 Evaluate the following SQL statement:
A. It gives the details of promos for which there have been sales.
B. It gives the details of promos for which there have been no sales.
C. It gives details of all promos irrespective of whether they have resulted in a sale or not.
D It gives details of promoids that have been sold irrespective of whether they had a promo or not.
You need to generate a report that gives details of the customer's last name, name of the product, and the
quantity sold for all customers in 'Tokyo'.
Naresh it Technologies
ORACLE 12c
Set Operators :-
Set operators are used to join the results of two (or more) SELECT statements.The
SET operators available in Oracle 12c are UNION,UNION ALL,INTERSECT,and MINUS.
Points to remember –
Data types of the column list must be compatible/implicitly convertible by oracle. Oracle
will not perform implicit type conversion if corresponding columns in the component
queries belong to different data type groups.For example, if a column in the first
component query is of data type DATE, and the corresponding column in the second
component query is of data type CHAR,Oracle will not perform implicit conversion, but
raise ORA-01790 error.
Performance wise, UNION ALL shows better performance as compared to UNION because
resources are not wasted in filtering duplicates and sorting the result set.
Set operators can't be used in SELECT statements containing TABLE collection expressions.
The LONG, BLOB, CLOB, BFILE, VARRAY,or nested table are not permitted for use in Set
operators.For update clause is not allowed with the set operators.
Set Operators:
Union
Union all
Intersect
Minus
SYNTAX :-
Naresh it Technologies
ORACLE 12c
HOME_LOANS
LOANID AMOUNT ACCNO
1 20 100
2 30 101
3 15 102
CAR_LOANS
LOANID AMOUNT ACCNO
1 10 100
2 7 101
4 5 103
UNION :-
Example :-
OUTPUT :-
100
101
102
103
Naresh it Technologies
ORACLE 12c
UNION ALL :-
Example :-
OUTPUT :-
100
101
102
100
101
103
INTERSECT :-
Naresh it Technologies
ORACLE 12c
Example :-
OUTPUT :-
100
101
MINUS :-
MINUS returns the difference between the first and second SELECT statement. It is the one
where we need to be careful which statement will be put first, cause we will get only those
results that are in the first SELECT statement and not in the second.
Example :-
OUTPUT :-
102
Both joins and unions can be used to combine data from one or more tables into a single result.
They both go about this in different ways. Whereas a join is used to combine columns from
different tables, the union is used to combine rows. UNION combines data horizontally whereas
join combines data vertically.
Naresh it Technologies
ORACLE 12c
Scenario :-
EMP_US EMP_IND
EMPNO ENAME DNO EMPNO ENAME DNO
100 A 10 200 X 10
101 B 20 201 Y 20
DEPT:-
SELECT E.*,D.*
FROM EMP_US E ,DEPT D
WHERE E.DNO = D.DNO;
SELECT E.*,D.*
FROM EMP_US E ,DEPT D
WHERE E.DNO = D.DNO;
UNION
SELECT E.*,D.*
FROM EMP_IND E ,DEPT D
WHERE E.DNO = D.DNO;
OCA questions :-
Which ORDER BY clauses are valid for the above query? (Choose all that apply.)
Naresh it Technologies
ORACLE 12c
A. ORDER BY 2,1
B. ORDER BY CUST_NO
C. ORDER BY 2,cust_id
D. ORDER BY "CUST_NO"
E. ORDER BY "Last Name"
Psuedo Columns
Pseudo columns are not actual columns in a table but they behave like columns, these columns doesn’t
really exist in DB but available for use. you can select values from a pseudo column but you cannot insert,
update ,delete the pseudo column values. Pseudo columns are assigned with values by ORACLE like a
normal db column but not stored on disk.
SQL and PL/SQL recognizes following pseudo columns which return specific data
ROWID
ROWNUM
USER
LEVEL
CURRVAL and NEXTVAL
SYSDATE
SYSTIMESTAMP
ORA_ROWSCAN
UID USER
50 SCOTT
Naresh it Technologies
ORACLE 12c
ROWID :-
ROWID returns physical address of a row in a database table and it is the fastest way to retrieve a
row. Faster than index even.
since ROWID represents physical location of a row no two rows within in the same table will have
the same ROWIDs.
Because ROWID represent physical location of a row , the ROWID will change every time the record
is physically moved.
In table records are arranged based on their ROWIDs i.e first record ROWID is always minimum and
last record is always maximum.
ROWNUM :-
ROWNUM represents the sequential order in which ORACLE has retrieved the row and it will
change from query to query .
Naresh it Technologies
ORACLE 12c
In the above result the ROWNUM generated for KING record is 6, So ROWNUM changes from query to
query.
We can also retrieve records based on their record number. For example to display 1st record ?
NOTE :- Because ROWNUM is generated after retrieving record. So with ROWNUM we cannot use > , >=
operators.
ORA_ROWSCAN :-
ORA_ROWSCN returns the system change number (SCN) of the last change inside the block containing a
row. It can return the last modification for the row if the table is created with the option
ROWDEPENDENCIES (default is NOROWDEPENDENCIES). The function SCN_TO_TIMESTAMP allows you to
convert SCN to timestamp.
Naresh it Technologies
ORACLE 12c
Subqueries
Subquery:-
AND
(SELECT MAX(sal) FROM emp WHERE deptno=30) ;
SQL>UPDATE emp SET sal = (SELECT MAX(sal) FROM emp) WHERE EMPNO=7369 ;
if inner query returns more than one row then it is called multi row subquery.
Syntax :-
Displaye employee records whose job equals to job of SMITH or job of BLAKE ?
Displaye employee records who are earning minimum and maximum salaries ?
ANY operator:-
Compares a value to each value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=.
Evaluates to FALSE if the query returns no rows.
Example:-
Example:-
Nested Queries:-
A subquery embedded in another subquery is called NESTED QUERY.
Queries can be nested upto 255 level.
Example :-
Naresh it Technologies
ORACLE 12c
Example :-
Example :-
Naresh it Technologies
ORACLE 12c
If inner query returns at least one record then EXISTS returns TRUE otherwise returns FALSE.
ORACLE recommends EXISTS and NOT EXISTS operators instead of IN and NOT IN.
2 Which three statements are true about multiple-row subqueries? (Choose three.)
3 Which two statements are true regarding the execution of the correlated subqueries? (Choose two.)
A. The nested query executes after the outer query returns the row.
B. The nested query executes first and then the outer query executes.
C. The outer query executes only once for the result returned by the inner query.
Naresh it Technologies
ORACLE 12c
D. Each row returned by the outer query is evaluated for the results returned by the inner query.
Which statement is true regarding the above query if one of the values generated by the subquery
is NULL?
A. It produces an error.
B. It executes but returns no rows.
C. It generates output for NULL as well as the other values produced by the subquery.
D. It ignores the NULL value and generates output for the other values produced by the subquery.
6 You want to update the CUST_INCOME_LEVEL and CUST_CREDIT_LIMIT columns for the customer with
the CUST_ID 2360. You want the value for the CUST_INCOME_LEVEL to have the same value as that of the
customer with the CUST_ID 2560 and the CUST_CREDIT_LIMIT to have the same value as that of the
customer with CUST_ID 2566.
A. UPDATE customers
SET cust_income_level = (SELECT cust_income_level
FROM customers
WHERE cust_id = 2560),
cust_credit_limit = (SELECT cust_credit_limit
FROM customers
WHERE cust_id = 2566)
WHERE cust_id=2360;
B. UPDATE customers
SET (cust_income_level,cust_credit_limit) = (SELECT cust_income_level, cust_credit_limit
FROM customers
WHERE cust_id=2560 OR cust_id=2566)
WHERE cust_id=2360;
C. UPDATE customers
SET (cust_income_level,cust_credit_limit) = (SELECT cust_income_level, cust_credit_limit
FROM customers
WHERE cust_id IN(2560, 2566) )
WHERE cust_id=2360;
Naresh it Technologies
ORACLE 12c
D. UPDATE customers
SET (cust_income_level,cust_credit_limit) = (SELECT cust_income_level, cust_credit_limit
FROM customers
WHERE cust_id=2560 AND cust_id=2566)
WHERE cust_id=2360;
In-line Views :-
The inline view is a construct in Oracle SQL Where you can place a query in the SQL FROM clause, just as if
the query was a tablename. A common use of in-line views is to simplify complex queries by removing join
operations and converting separate queries into single query.
Syntax :-
Example :-
Display records M thru N from table. the general form of this is as follows ?
SQL>SELECT * FROM
(SELECT a.*, ROWNUM rn
Naresh it Technologies
ORACLE 12c
SQL>SELECT * FROM
(SELECT a.*, ROWNUM rn FROM
(SELECT * FROM emp) a
WHERE ROWNUM <= 6)
WHERE rn >= 2;
SQL>SELECT d.dname,e.maxsal
FROM dept d , (SELECT deptno,MAX(sal) maxsal FROM emp
GROUP BY deptno) e
WHERE e.deptno = d.deptno ;
The WITH clause, or subquery factoring clause, is part of the SQL-99 standard and was added into the
Oracle SQL syntax in Oracle 9.2. The WITH clause may be processed as an inline view or resolved as a
temporary table. The advantage of the latter is that repeated references to the subquery may be more
efficient as the data is easily retrieved from the temporary table, rather than being requeried by each
reference. You should assess the performance implications of the WITH clause on a case-by-case basis.
example shows how the WITH clause can be used to reduce repetition and simplify complex SQL
statements.
for each employee we want to know how many other people are in their department. Using an inline view
we might do the following.
SQL>WITH dept_count AS (
Naresh it Technologies
ORACLE 12c
What if we also want to pull back each employees manager name and the number of people in the
managers department? Using the inline view it now looks like this.
Using the WITH clause this would look like the following.
SQL>WITH dept_count AS (
SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno)
SELECT e.ename AS employee_name,
dc1.dept_count AS emp_dept_count,
m.ename AS manager_name,
dc2.dept_count AS mgr_dept_count
FROM emp e,
dept_count dc1,
emp m,
dept_count dc2
WHERE e.deptno = dc1.deptno
AND e.mgr = m.empno
AND m.deptno = dc2.deptno;
Naresh it Technologies
ORACLE 12c
So we don't need to redefine the same subquery multiple times. Instead we just use the query name
defined in the WITH clause, making the query much easier to read.
the WITH clause can simplify complex queries, like the following example that lists those departments with
above average wages.
SQL>WITH
dept_costs AS (
SELECT dname, SUM(sal) dept_total
FROM emp e, dept d
WHERE e.deptno = d.deptno
GROUP BY dname),
avg_cost AS (
SELECT SUM(dept_total)/COUNT(*) avg
FROM dept_costs)
SELECT *
FROM dept_costs
WHERE dept_total > (SELECT avg FROM avg_cost)
ORDER BY dname;
Subqueries can also follow SELECT clause. These subqueries returns one value per row.
Syntax :-
Example :-
EMP DEPT
14 4
Naresh it Technologies
ORACLE 12c
Database Transactions
A database transaction is a group of SQL statements that perform a logical unit of work. Whose results
should be made permanent in the database as a whole or undone as a whole .
An example of a database transaction is a transfer of money from one bank account to another. One
UPDATE statement would subtract from the total amount of money from one account, and another
UPDATE would add money to the other account. Both the subtraction and the addition must be
permanently recorded in the database, otherwise, money will be lost. If there is a problem with the money
transfer, then the subtraction and addition must both be undone.
If transaction ends with COMMIT then it is called successful transaction and the operations are made
permanent.
If transaction ends with ROLLBACK then it is called aborted transaction and operations are undone.
Naresh it Technologies
ORACLE 12c
Savepoints:
You can also set a savepoint at any point with in a transaction. These allow you to roll back changes that
savepoint. Savepoints can be useful to break up very long transactions, because, if you make a mistake
after you’ve set a savepoint, you don’t have to roll back the transaction all the way to the start.
Scenario:-
PRODUCT_ID PRICE
4 13.95
5 49.99
The price for product #4 is $13.95, and the price for product #5 is $49.99.
The following UPDATE increases the price of product #4 by 20 percent:
SQL>UPDATE products
SET price = price *1.20
WHERE product_id =4;
1 row updated.
The following statement sets a savepoint named save1:
SQL>SAVEPOINT save1;
Savepoint created.
Any DML statements run after this point can be rolled back to the savepoint, and the change made to
product #4 will be kept.
SQL>UPDATE products
SET price = price *1.30
WHERE product_id = 5;
1 row updated.
SQL>ROLLBACK TO save1;
Rollback complete.
This has undone the price change for product #5, but left the price change for product #4 intact.
Every transaction has to support following four properties called ACID properties.
Naresh it Technologies
ORACLE 12c
Atomic: Transactions are atomic, meaning that the SQL statements contained in a transaction make up a
single unit of work.
Consistent: Transactions ensure that the database state remains consistent, meaning that the database is
in a consistent state when a transaction begins and that it ends in another consistent state when the
transaction finishes.
Durable: Once a transaction has been committed, the database changes are preserved, even if the
machine on which the database software is running crashes later.
The Oracle database software handles these ACID properties and has extensive recovery facilities for
restoring databases after system crashes.
Concurrent Transactions:
The Oracle database software supports many users interacting with a databse, and each user can run their
own transaction at the same time. These transactions are known as concurrent transactions.If users are
running transactions that affect the same table, the effects of those transactions are separated from each
other until a COMMIT is performed. The following sequence of events, based on two transactions named
T1 and T2 that access the customers table, illustrates the separation of transactions:
1. T1 and T2 perform a SELECT that retrieves all the rows from the customer table.
2. T1 performs an INSERT to add a row in the customers table, but T1 doesn’t perform a COMMIT.
3.T2 performs another SELECT and retrieves the same rows as those in step1. T2 doesn’t “see” the new
row added by T1 in step2.
4. T1 finally performs a COMMIT to permanently record the new row added in step2.
5. T2 performs another SELECT and finally “sees” the new row added by T1.
To summarize: T2 doesn’t see the changes made by T1 until T1 commits its changes.
Transactions Locking:
To support concurrent transactions, the Oracle database software must ensure that the data in the tables
remain valid. It does this through the use of locks. Consider the following example in which two
transactions named T1 and T2 attempt to modify customer #1 in the customer table:
Naresh it Technologies
ORACLE 12c
1. T1 performs an UPDATE to modify customer #1, but T1 doesn’t perform a COMMIT. T1 is said to have
“locked” the row.
2. T2 also attempts to perform an UPDATE to modify customer #1, but since this row is already locked by
T1,T2 is prevented from getting a lock on the row. T2’s UPDATE statement has to wait until T1 ends and
frees the lock on the row.
4. T2 gets the lock on the row and the UPDATE is performed.T2 holds the lock on the row until T2 ends.
To summarize: A transaction cannot get a lock on a row while another transaction already holds the lock
on that row.
Transaction 1 T1 Transaction 2 T2
(customers_id, first_name,last_name)
WHERE customer_id = 2;
T1 in step 3 and 4.
The transaction isolation level is the degree to which the changes made by one transaction are separated
from other transactions running concurrently. Before you see the various transaction isolation levels
available, you need to understand the types of problems that may occur when current transactions
attempt to access the same rows in a table.
In the following list, you’ll see examples of two concurrent transactions named T1 and T2 that are
accessing the same rows; listed are the three types of potential transaction processing problems.
Phantom reads:-
T1 reads a set of rows returned by a specified WHERE clause. T2 then inserts a new row, which also
happens to satisfy the WHERE clause of the query previously used by T1. T1 then reads the rows again
using the same query, but now sees the additional row just inserted by T2. This new row is known as a
“phantom” because to T1 this row seems to have magically appeared.
Nonrepeatable reads:-
T1 reads a row, and T2 updates the same row just read by T1. T1 then reads the same row again and
discovers that the row is read earlier is now different. This is known as a “non repeatable” read, because
the row originally read by T1 has been changed.
Dirty reads:-
T1 updates a row, but doesn’t commit the update T2 then reads the updated row.T1 then performs a
rollback, Undoing the previous update. Now the row just read by T2 is no longer valid (it’s “dirty”) because
the update made by T1 wasn’t committed when the row was read by T2. To deal with these potential
problems, database implement various levels of transaction isolation to prevent concurrent transactions
from interfering with each other. The SQL standard defines the following transaction isolation levels,
READ UNCOMMITTED:- Phantom reads, nonrepeatable reads, and dirty reads are permitted.
READ COMMITTED:- Phantom reads and nonrepeatable reads are permitted, but dirty reads are not.
REPEATABLE READ:- Phantom reads are permitted, but Non repeatable and dirty reads are not.
SERIALIZABLE: Phantom reads, non repeatable reads, and dirty reads are not permitted.
The Oracle database software supports the READ COMMITTED and SERIALIZABLE transaction isolation
levels. It doesn’t support READ UNCOMMITTED or REPEATABLE READ levels.The default transaction
isolation level defined by the SQL standard is SERIALIZABLE, but the default used by the Oracle database is
READ COMMITTED, which is acceptable for nearly all applications.
Naresh it Technologies
ORACLE 12c
OCA question:-
When does a transaction complete? (Choose all that apply.)
Naresh it Technologies
ORACLE 12c
Database Security
Creating a user/schema/account in oracle DB :-
To create a user in the database, you use the CREATE USER statement. The simplified syntax for the
CREATE USER statement is as follows:
Syntax :-
The following example creates a user called VIJAY with password ORACLE
SQL>CONNECT system/manager
The next example creates a user named VIJAY and specifies a default and temporary tablespace:
SQL>CONNECT system/manager
Naresh it Technologies
ORACLE 12c
Privileges :-
1 System privileges
2 Object privileges
System Privileges:-
A system privilege allows a user to perform certain actions within the database, such as executing DDL
statements. For example, CREATE TABLE allows a user to create a table in their schema. Some of the
commonly used system privileges are shown in the table:
You use GRANT to grant system privilege to a user. The following example grants some system privilege to
vijay (assuming you’re still connected to the database as system):
Example :-
Naresh it Technologies
ORACLE 12c
You can also use WITH ADMIN OPTION to allow a user to grant a privilege to another user. The following
example grants the EXECUTE ANY PROCEDURE privilege with the ADMIN option to VIJAY.
EXECUTE ANY PROCEDURE can then be granted to another user by VIJAY. The following example connects
as VIJAY and grants EXECUTE ANY PROCEDURE to KUMAR
SQL>CONNECT VIJAY/oracle11g
SQL>GRANT EXECUTE ANY PROCEDURE TO KUMAR;
You can grant a privilege to all users by granting to PUBLIC.
SQL>CONNECT system/manager
SQL>GRANT EXECUTE ANY PROCEDURE TO PUBLIC;
Every user in the database now has the EXECUTE ANY PROCEDURE privilege.
Checking System Privilege Granted to a User:-
You can check which system privileges a user has , by querying USER_SYS_PRIVS
You revoke system privileges from a user using REVOKE. The following example connects as system and
revokes the CREATE TABLE privilege from VIJAY.
SQL>CONNECT system/manager
Object Privileges:-
An object privilege allows a user to perform certain actions on database objects, such as executing DML
statements on tables. some of the commonly used objects privileges are shown in the table:
SQL>CONNECT SCOTT/TIGER;
SQL>GRANT SELECT, INSERT, UPDATE ON PRODUCTS TO VIJAY;
The next example grants the UPDATE privilege on the last_name and salary columns to VIJAY
You can also use the GRANT option to enable a user to grant a privilege to another user. The following
example grants the SELECT privilege on the customers table with the GRANT option to VIJAY
The SELECT ON customers privilege can then be granted to another user by VIJAY. The following example
connects as VIJAY and grants this privilege to RAJU.
SQL>CONNECT vijay/oracle11g ;
You can check which table object privileges a user has made to other users by querying
USER_TAB_PRIVS_MADE
You can check which object privileges on a table a user has retrieved by querying the
USER_TAB_PRIVS_RECD table.
You revoke object privileges using REVOKE. The following example connects as SCOTT and revokes the
INSERT privilege on the products table from VIJAY.
Naresh it Technologies
ORACLE 12c
SQL>CONNECT SCOTT/TIGER;
The next example revokes the SELECT privilege on the customers table from VIJAY
When you revoke SELECT ON customers from VIJAY who has already passed this privilege to RAJUl also
loses the privilege.
Roles:-
A role is a group of privileges that you can assign to a user or to another role. The following points
summarize the benefits and features of roles:
Rather than assigning privileges one at a time directly to a user, you can create a role, assign privileges to
that role, and then grant that role to multiple users and roles.
When you add or delete a privilege from a role, all users and roles assigned that role automatically
receive or lose that privilege.
As you can see from these points, roles can help you manage multiple privileges assigned to multiple
users.
You create a role using the CREATE ROLE statement. The following statements connects as store and create
the three roles shown in table:
SQL>CONNECT scott/tiger
The following example grants the required privileges to the product_manager and hr_manager roles and
grants these two roles to overall_manager:
You grant a role to the user using GRANT. The following example grants the overall_manager role to VIJAY.
you can check which roles have been granted to a user querying USER_ROLE_PRIVS.
SQL>CONNECT VIJAY/ORACLE11G ;
You can check which system privileges have been granted to a role by querying ROLE_SYS_PRIVS.
Naresh it Technologies
ORACLE 12c
You can check which object privileges have been granted to a role by querying ROLE_TAB_PRIVS
Revoking a Role:-
You revoke a role using REVOKE. The following example revokes the overall_manager role from VIJAY
Dropping a Role:-
Naresh it Technologies
ORACLE 12c
Schema Objects
TABLES
SEQUENCES
VIEWS
MATERIALIZED VIEWS
SYNONYMS
TYPES
INDEXES
CLUSTERS
PROCEDURES
FUNCTIONS
PACKAGE
DB TRIGGER
SEQUENCE
The SEQUENCE Values are often used for PRIMARY KEY’S and UNIQUE KEY’S.
CREATING SEQUENCES:-
Syntax:-
[INCREMENT BY n]
[START WITH n]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE]
ORDER/NORDER;
Increment By :-
Minvalue:-
Naresh it Technologies
ORACLE 12c
NoMinvalue
Specifies a minimum value of 1 for an ascending sequence and –(10)^26) for a descending sequence.
Maxvalue:-
NoMaxvalue:-
Specifies a maximum value of 10^27 for an ascending sequence and -1 for a descending sequence.
Start With:-
Cycle:-
Specifies whether the sequence contains to generate values after reaching its maximum or minimum
value.
NoCycle:-
Specifies the SEQUENCE cannot general more values after the targeted limit.
Cache:-
Specifies how many values the Oracle Server Preallocates and keep in memory.
NoCache:-
If the above parameters are not specified by default 20 values are cached.
Order:-
NoOrder:-
Naresh it Technologies
ORACLE 12c
Test Table:-
1 CURRVAL
2 NEXTVAL
CURRVAL returns current value of the sequence .
NEXTVAL returns next value of the sequence.
SEQ1.CURRVAL
SEQ1.NEXTVAL
Example :-
SQL>INSERT INTO customers
VALUES(SEQ1.Nextval,’sachin’,’mumbai’);
Creating A Sequence with CYCLE:-
Naresh it Technologies
ORACLE 12c
Modifying a Sequence:-
The ALTER command can be used to change the present status of a SEQUENCE.
Increment Value
Maximum Value
Minimum Value
Cycle Option
Cache Option
Syntax:-
Example :-
SQL>ALTER SEQUENCE SEQ1 MAXVALUE 500
You must be the owner or have the ALTER privilege for the sequence modify it.
Only future sequence numbers are affected by the ALTER SEQUENCE statement.
The sequence must be dropped and re-created in order to restart the sequence at a different number.
Removing a Sequence:-
USER_SEQUENCE
ALL_SEQUENCES
DBA_SEQUENCES
SQL>SELECT sequence_name,min_value,max_value,increment_by,last_number
FROM user_Sequences
WHERE sequence_Name= ‘SEQ1’;
Naresh it Technologies
ORACLE 12c
OCA question :-
1 Which two statements are true about sequences created in a single instance database? (Choose
two.)
A. The numbers generated by a sequence can be used only for one table.
B. DELETE <sequencename> would remove a sequence from the database.
C. CURRVAL is used to refer to the last sequence number that has been generated.
D. When the MAXVALUE limit for a sequence is reached, you can increase the MAXVALUE limit by using
the ALTER SEQUENCE statement.
E. When a database instance shuts down abnormally, the sequence numbers that have been cached
but not used would be available once again when the database instance is restarted.
The command to create a table fails. Identify the reason for the SQL statement failure? (Choose all that
apply.)
The SEQ1 sequence has generated numbers up to the maximum limit of 200. You issue the following
SQL stmt :-
SELECT seq1.nextval FROM dual;
What is displayed by the SELECT statement?
A. 1
B. 10
C. 100
D. an error
Naresh it Technologies
ORACLE 12c
VIEWS
Data abstraction is usually required after a table is created and populated with data. Data held by some
tables might require restricted access to prevent all users from accessing all columns of a table, for data
security reasons. Such a security issue can be solved by creating several tables with appropriate columns
and assigning specific users to each such table, as required. This answers data security requirements very
well but gives rise to a great deal of redundant data being resident in tables, in the database.To reduce
redundant data to the minimum possible, Oracle provides Virtual tables which are Views.
View Definition :-
The most basic purpose of a view is restricting access to specific column/rows from a table thus allowing
different users to see only certain rows or columns of a table.
Composition Of View:-
A view is composed of rows and columns, very similar to table. The fields in a view are fields from one or
more database tables in the database.
SQL functions, WHERE clauses and JOIN statements can be applied to a view in the same manner as they
are applied to a table.
View storage:-
Oracle does not store the view data. It recreates the data, using the view’s SELECT statement, every time
a user queries a view.
When a reference is made to a view, its definition is scanned, the base table is opened and the view is
created on top of the base table.This, therefore, means that a view never holds data, until a specific call to
the view is made. This reduces redundant data on the HDD to a very large extent.
Advantages Of View:-
Security:- Each user can be given permission to access only a set of views that contain specific data.
Query simplicity:- A view can drawn from several different tables and present it as a single table turning
multiple table queries into single table queries against the view.
Data Integrity:- If data is accessed and entered through a view, the DBMS can automatically check the data
to ensure that it meets specified integrity constraints.
Disadvantage of View:-
Performance:- Views only create the appearance of the table but the RDBMS must still translate queries
against the views into the queries against the underlined source tables. If the view is defined on a complex
multiple table query then even a simple query against the view becomes a complicated join and takes a
long time to execute.
Naresh it Technologies
ORACLE 12c
Types of Views :-
Simple Views
Complex Views
Simple Views :-
a View based on single table is called simple view.
Syntax:-
CREATE VIEW <View Name>
AS
SELECT<ColumnName1>,<ColumnName2>
FROM <TableName>
[WHERE <COND>]
[WITH CHECK OPTION]
[WITH READ ONLY]
Example :-
Views can also be used for manipulating the data that is available in the base tables[i.e. the user can
perform the Insert, Update and Delete operations through view.
Views on which data manipulation can be done are called Updateable Views.
If an Insert, Update or Delete SQL statement is fired on a view, modifications to data in the view are
passed to the underlying base table.
If the user wants to INSERT records with the help of a view, then the PRIMARY KEY column(s) and all
the NOT NULL columns must be included in the view.
Naresh it Technologies
ORACLE 12c
If VIEW created with WITH CHECK OPTION then any DML operation through that view violates where
condition then that DML operation returns error.
Example :-
SQL>CREATE VIEW V2
AS
SELECT empno,ename,sal,deptno FROM emp
WHERE deptno=10
WITH CHECK OPTION ;
Complex views are not updatable i.e. we cannot perform insert or update or delete operations on base
table through complex views.
Example 2 :-
SQL>CREATE VIEW V2
AS
SELECT deptno,SUM(sal) AS sumsal
FROM EMP
GROUP BY deptno;
Naresh it Technologies
ORACLE 12c
Destroying a View:-
The DROP VIEW command is used to destroy a view from the database.
Syntax:-
DROP VIEW<viewName>
Example :-
SQL>DROP VIEW emp_v;
Querying VIEWS information :-
USER_VIEWS
ALL_VIEWS
DBA_VIEWS
OCA questions :-
A.A subquery that defines a view cannot include the GROUP BY clause.
B.A view that is created with the subquery having the DISTINCT keyword can be updated.
C.A view that is created with the subquery having the pseudo column ROWNUM keyword cannot be
updated.
D.A data manipulation language (DML) operation can be performed on a view that is created with the
subquery having all the NOT NULL columns of a table.
2 You want to create a SALE_PROD view by executing the following SQL statement:
CREATE VIEW sale_prod
AS SELECT p.prod_id, cust_id, SUM(quantity_sold) "Quantity", SUM(prod_list_price) "Price"
FROM products p, sales s
WHERE p.prod_id=s.prod_id
GROUP BY p.prod_id, cust_id;
Naresh it Technologies
ORACLE 12c
You issue the following command to create a view that displays the IDs and last names of the sales staff in
the organization:
Which two statements are true regarding the above view? (Choose two.)
A. It allows you to insert rows into the EMPLOYEES table.
B. It allows you to delete details of the existing sales staff from the EMPLOYEES table.
C. It allows you to update job IDs of the existing sales staff to any other job ID in the EMPLOYEES table.
D. It allows you to insert IDs, last names, and job IDs of the sales staff from the view if it is used in
multitable INSERT statements.
Synonyms
A synonym is another name or alternative name for a table.
Synonyms are created
If tablename is lengthy.
To provide local transparency for remote objects.
Syntax:-
Example :-
After creating synonym , now EMPLOYEE_INFORMATION table can be accessed by using name
EMP. For Example
NOTE:- difference between synonym and table alias is , the scope of the table alias is upto that query only
but synonym can be used any query.
VIEWS vs SYNONYMS:-
VIEWS SYNONYMS
Subset of a table mirror of a table
Can be based on more than one table based on only one table
Naresh it Technologies
ORACLE 12c
Public Synonyms:-
You can also create a public synonym for a table. When you do this , all users can see the synonym.
SQL>CONNECT system/manager
SQL>GRANT CREATE PUBLIC SYNONYM TO scott;
SQL>CONNECT scott/tiger
SQL>CREATE PUBLIC SYNONYM products FOR SCOTT.products;
If you connect as vijay, who has the SELECT privilege on SCOTT.products, you can now retrieve rows from
SCOTT.products through the products public synonym:
SQL>CONNECT vijay/vijay;
SQL>SELECT * FROM products;
OCA question :-
1 The ORDERS table belongs to the user OE. OE has granted the SELECT privilege on the ORDERS table to the
user HR. Which statement would create a synonym ORD so that HR can execute the following query successfully?
Naresh it Technologies
ORACLE 12c
Indexes
When looking for a particular topic in a book, you either scan the whole book, or you can use the index to
find the location. An index for a database table is similar in concept to a book index, except that database
indexes are used to find specific rows in a table.
Table Scan
Index Scan
Table Scan :-
In table scan oracle scans the entire table to locate the desired information.
Index Scan :-
In index scan oracle uses index to locate the place that holds the required data and then jumps to that
place to get required data. This is much faster than table scan.
When an index is created on a table, oracle internally forms a two dimensional matrix that contains
Data extracted from the column on which index is created and Physical Address of the record
(rowid) .
When an SQL query that has a WHERE clause based on the column on which index is fired , oracle
finds the value in index and locates the record in the table using ROWID .
TYPES OF INDEXES :-
B-tree Indexes
Simple Index
Composite Index
Unique Index
Function based Index
Bitmap Indexes
B-TREE INDEXES :-
When to use BTREE Indexes:-
Naresh it Technologies
ORACLE 12c
Syntax:-
A SELECT query with a WHERE clause spceicifed on column on which index is created
A SELECT query with ORDER BY clause specified on column on which index is created
SELECT query is fired with WHERE clause specified on the column on which index is not defined
SELECT query is fired with ORDER BY clause specified on the column on which index is not defined.
Composite Index :-
Example :-
Oracle server uses above index when SELECT query with WHERE clause is based on leading column of
index is fired.
Naresh it Technologies
ORACLE 12c
Example :-
Unique Index :-
UNIQUE index doesn’t allow duplicate values into the column on which INDEX is created.
Example :-
NOTE:-
PRIMARY KEY columns and UNIQUE columns are automatically indexed by ORACLE.
There are times when even though an index exists, oracle doesn’t use it and instead follows table scan.
This is usually happens when index created on a column, but the SQL query reference that column with a
function or arithmetic expression.
For example , an index is created on the City column of the Customers table and the following query is
fired to retrieve all those row who belong to MUMBAI.
Above query reference the City column along with UPPER function and hence oracle doesn’t use the index.
In addition, the database administrator must set the initialization parameter QUERY_REWRITE_ENABLED to
true (the default is false) in order to take advantage of function – based indexes.
SQL>CONNECT system/manager
Reverse Index:-
In the index leaf block , Oracle stores the index key value and ROWID.
Assume that there is an unique index on custid , suppose 3 individuals concurrently hit the database to
insert rows with customer numbers 101,102,103 then index entries are stored in same leaft block , which
causes buffer busy waits.
If the index is reverse unique index then the entries will be stored in different leaft block
Naresh it Technologies
ORACLE 12c
Example :-
NOTE :-
BITMAP INDEXES :-
Example :-
Modifying an Index:-
Example :-
DROPPING INDEX :-
SYNTAX :-
Example:-
USER_INDEXES
USER_IND_COLUMNS
ALL_INDEXES
DBA_INDEXES
OCA question :-
Which statements are correct regarding indexes? (Choose all that apply.)
Naresh it Technologies
ORACLE 12c
Clusters
A cluster is a data structure that improves retrieval performance. A cluster, like an index, does not affect
the logical view of the table. A cluster is a way of storing related data values together on disk. Oracle reads
data a block at a time, so storing related values together reduces the number of I/O operations needed to
retrieve related values, since a single data block will contain only related rows.
A cluster is composed of one or more tables. The cluster includes a cluster index, which stores all the
values for the corresponding cluster key. Each value in the cluster index points to a data block that contains
only rows with the same value for the cluster key.
If a cluster contains multiple tables, the tables should be joined together and the cluster index should
contain the values that form the basis of the join. Because the value of the cluster key controls the
placement of the rows that relate to the key, changing a value in that key can cause Oracle to change the
location of rows associated with that key value.
Clusters may not be appropriate for tables that regularly require full table scans, in which a query requires
the Oracle database to iterate through all the rows of the table. Because you access a cluster table through
the cluster index, which then points to a data block, full table scans on clustered tables can actually require
more I/O operations, lowering overall performance.
The following statement creates a cluster named personnel with the cluster key column department, a
cluster size of 512 bytes, and storage parameter values:
The following statement creates the cluster index on the cluster key of personnel:
After creating the cluster index, you can add tables to the index and perform DML operations on those
tables.
Naresh it Technologies
ORACLE 12c
The following statements create some tables and add them to the personnel cluster created in the earlier
example:
USER_CLUSTERS
ALL_CLUSTERS
DBA_CLUSTERS
Materialized Views
A materialized view is a database object that contains the results of a query unlike normal views that
only contains the query definition and not the results.Materialized views are usually a choice to maintain
local copy for remote db object and creating summary tables on aggregate of a table’s data
A materialized takes a different approach in which the query result is cached as a concrete table that
may be updated from the original base tables from time to time.
Materialized view does not contain up-to-the–minute information. When an ordinary view is queried,
the data retrieved includes changes made up to the last committed transaction.However, when an
materialized view is queried the data retrieved would be at a state when the view was created or last
refreshed.
Syntax:-
Naresh it Technologies
ORACLE 12c
REFRESH:-
Since the materialized view is built on underlying data that is periodically changed, specify how and when
to refresh the data in the view. The following keywords in the REFRESH clause can also be used to create a
schedule for recurring refresh operations.
FAST: - Updates only the values in the materialized view, assuming that some preconditions are met.
FORCE: - Does a FAST refresh if possible and a COMPLETE refresh if the preconditions for a FAST refresh are
not available.
ON COMMIT:- Causes a refresh to occur whenever the underlying data is changed and the changes are
committed.
START WITH DATE:- Indicates the date and interval at which the materialized view is to be refreshed
NEXT DATE:- Indicates the time and interval at which the materialized view is to be refreshed next
WITH PRIMARY KEY: - Indicates whether the materialized view is based on Primary Key
Example :-
Naresh it Technologies
ORACLE 12c
ON DEMAND :-
USER_MVIEWS
ALL_MVIEWS
DBA_MVIEWS
Advanced Features:-
Table Partitioning
As the number of rows in your table grows, the management and performance impacts will increase.
Backups will take longer, recoveries will take longer and queries on that will take longer.
Administrative and performance issues can be simplified by seperating rows of a single table into
multiple parts.
Dividing a table’s data in this manner is called partitioning the table, and table is called partitioned table
and parts are called partitions.
Partitioning is based on particular column , the column on which table is partitioned is called partition
key.
Advantages :-
The performance of queries against the table may improve.
The tables may be easier to manage.
Backup and recover operations may perform better.
Improves availability.
a table can be partitioned in different ways
1. RANGE PARTITION
2. LIST PARTITION
3. HASH PARTITION
RANGE partition :-
Which records are assigned to which partition depends on range of the partition key.
Naresh it Technologies
ORACLE 12c
Example :-
SQL>CREATE TABLE emp_range
(empno NUMBER(4) ,
ename VARCHAR2(20) ,
sal NUMBER(7,2))
PARTITION BY RANGE(sal)
(
PARTITION P1 VALUES LESS THAN(2000) ,
PARTITION P2 VALUES LESS THAN(4000),
PARTITION P3 VALUES LESS THAN(MAXVALUE)
);
Employee whose salaries less than 2000 all those records are assinged to partition P1.
Employee whose salaries less than 4000 all those records are assinged to partition P2 .
MAXVALUE is a keyword , any data that could not be stored in earlier partitions are assigned to partition
P3.
The above query displays only the records assigned to partition P1.
Managing Partitions:-
Partitions can be dropped , new partitions can be added , and two partitions can be merged.
Droping Partition:-
When partition is dropped then records assigned to that partition are also dropped.
Naresh it Technologies
ORACLE 12c
LIST partition:-
Which record is assinged to which partition depends on value of partition key value.
HASH Partition:-
A Hash paritition determines the physical placement of data by applying hash function on partition key .
We can create subpartitions that is, paritions of partitions. You can use subpartitions to combine all types
of partitions like range partitions, hash partitions,list partitions.
(
PARTITION janfeb_2000 VALUES LESS THAN (TO_DATE('1-MAR-2000','DD-MON-YYYY')),
PARTITION marapr_2000 VALUES LESS THAN (TO_DATE('1-MAY-2000','DD-MON-YYYY')),
PARTITION mayjun_2000 VALUES LESS THAN (TO_DATE('1-JUL-2000','DD-MON-YYYY'))
);
Naresh it Technologies
ORACLE 12c
Object-Relational Features :-
Naresh it Technologies
ORACLE 12c
Inheritance :-
Inherit attributes and behavior of the pre-existing classes , hence ease of definition and programming
Defining an object type does not allocate any storage. The body of method is defined in a separate
CREATE--TYPE BODY statement, written in PL/SQL
Oracle Objects :-
Actual instance of the defined object type. Storages are allocated to an object and values are assigned to
the attributes of an object
SQL>CREATE TABLE customers (
cust_details person_type,
phone number(10) );
Naresh it Technologies
ORACLE 12c
Invoking method :-
SQL>SELECT c.cust_details.get_age() FROM customers c ;
Collection Types :-
Oracle provides two collection types: nested tables and varying arrays or
VARRAYS. A collection is an ordered group of elements of the same type. Each
element from the group can be accessed using a unique subscript. The
element types of a collection can be either built-in datatypes, user-defined
types or references (REFs) to object types.
Nested Tables :-
An ordered group of items of type TABLE are called nested tables. Nested
tables can contain multiple columns and can be used as variables, parameters,
results, attributes, and columns. They can be thought of as one column
database tables. Rows of a nested table are not stored in any particular order.
The size of a nested table can increase dynamically, i.e., nested tables are
unbounded. Elements in a nested table initially have consecutive subscripts,
but as elements are deleted, they can have non-consecutive subscripts.
Nested tables can be fully manipulated using SQL, PL/SQL. The range of values
for nested table subscripts is 1..2147483647. To extend a nested table, the
built-in procedure EXTEND must be used. To delete elements, the built-in
procedure DELETE must be used.
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
The following example shows how to update the CUSTOMER HNO where cid
column has value 100:
VARRAY :-
Varrays are ordered groups of items of type VARRAY. Varrays can be used to
associate a single identifier with an entire collection. This allows manipulation
of the collection as a whole and easy reference of individual elements.
The maximum size of a varray needs to be specified in its type definition. The
range of values for the index of a varray is from 1 to the maximum specified in
its type definition. If no elements are in the array, then the array is atomically
null. The main use of a varray is to group small or uniform-sized collections of
objects.
Naresh it Technologies
ORACLE 12c
MANF_DATE DATE);
/
The following example shows how to insert two rows into the MED_STORE
table:
Naresh it Technologies
ORACLE 12c
When stored in the database, nested tables do not retain their ordering and
subscripts, whereas varrays do.
Naresh it Technologies
ORACLE 12c
Hierarchical Queries
A hierarchical query presents data in a inverted tree structure.
Each node is connected to one parent node. The top most node is the Root Node that has no
parent.
Nodes that do not have child nodes are called Leaf Nodes.
Syntax :-
CONNECT BY PRIOR :-
used to specify relationship between Parent and child rows. This clause cannot be used to perform Join
operation.
Example :-
Example :-
Naresh it Technologies
ORACLE 12c
SYS_CONNECT_BY_PATH :-
Returns child node along with path
Example :-
CONNECT_BY_ISLEAF :-
Returns whether the node is leaf node or not , If node is leaf node then it returns 1 otherwise returns 0.
Naresh it Technologies
ORACLE 12c
Flashback Queries
Most of the times an application crashes only because of Human errors. A human error could result in
data corruption Due to which the application simply halts.The most human errors that causes an
application to go down are Accidental deletion of valuable Data , droping the table.
Oracle offers a solution called Flashbacking to recover data Due to human errors.
A flashback allows reverting mistakenly committed changes by viewing the records before the commit
was executed.
Flashbacking Data :-
Naresh it Technologies
ORACLE 12c
When the above procedure is executed it enables flashback mode and any query runs after this it display
data that exists before 2 days
Example :-
SQL>EXECUTE DBMS_FLASHBACK.DISABLE() ;
Flashback Table :-
Oracle flashback feature allows recovering a table after drop.When a table is dropped oracle moves it to
the recyclebin rather than actually droping it.
A Recycle Bin is logical collection of dropped objects. The contents of Recycle Bin is viewed by using
SHOW RECYCLEBIN command.
Flashback command is introduced in ORACLE 10g , which is used to restore a table after drop.
Example :-
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
CREATE TABLE t1 (
description VARCHAR2(30)
);
ID DESCRIPTION
---------- - -----------------------------
1 DESCRIPTION only
1 rows selected.
In previous releases of the Oracle database, there was no direct equivalent of the AutoNumber or
Identity functionality of other database engines. Instead, this behaviour had to be implemented
using a combination of sequences and triggers. Oracle 12c introduces two alternatives to this by
providing identity columns and the ability to use sequence pseudocolumns as default values. This
article will focus on the use of identity columns.
12c database introduces the ability define an identity clause against a table column defined using a
numeric type. The syntax is show below.
GENERATED
AS IDENTITY [ ( identity_options ) ]
Naresh it Technologies
ORACLE 12c
Ignoring the identity_options, which match those of the CREATE SEQUENCE statement,
this syntax allows us to use three variations on the identity functionality.
Before we can look at some examples, you need to make sure your test user has the
CREATE SEQUENCE privilege. Without it, attempts to define an identity column will
produce a "ORA-01031: insufficient privileges" error.
CONN / AS SYSDBA
CONN test/test@pdb1
Using ALWAYS forces the use of the identity. If an insert statement references the
identity column, even to specify a NULL value, an error is produced.
description VARCHAR2(30)
);
1 row created.
SQL> INSERT INTO identity_test_tab (id, description) VALUES (NULL, 'ID=NULL and
DESCRIPTION');
ERROR at line 1:
SQL> INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and
DESCRIPTION');
INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and DESCRIPTION')
ERROR at line 1:
Naresh it Technologies
ORACLE 12c
Using BY DEFAULT allows you to use the identity if the column isn't referenced in the
insert statement, but if the column is referenced, the specified value will be used in
place of the identity. Attempting to specify the value NULL in this case results in an
error, since identity columns are always NOT NULL.
description VARCHAR2(30)
);
1 row created.
SQL> INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and
DESCRIPTION');
1 row created.
SQL> INSERT INTO identity_test_tab (id, description) VALUES (NULL, 'ID=NULL and
DESCRIPTION');
ERROR at line 1:
Using BY DEFAULT ON NULL allows the identity to be used if the identity column is
referenced, but a value of NULL is specified.
description VARCHAR2(30)
);
Naresh it Technologies
ORACLE 12c
1 row created.
SQL> INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and
DESCRIPTION');
1 row created.
SQL> INSERT INTO identity_test_tab (id, description) VALUES (NULL, 'ID=NULL and
DESCRIPTION');
1 row created.
ID DESCRIPTION
---------- ------------------------------
1 Just DESCRIPTION
Top –N Queries :-
Top-N query is used to retrieve the top or bottom N rows from an ordered set. Combining two Top-N
queries gives you the ability to page through an ordered set. This concept is not a new one. In fact, Oracle
already provides multiple ways to perform Top-N queries, as discussed here. These methods work fine, but
they look rather complicated compared to the methods provided by other database engines.
To be consistent, we will use the same example table used in the Top-N Queries article.
Naresh it Technologies
ORACLE 12c
val NUMBER
);
INSERT ALL
INTO rownum_order_test
INTO rownum_order_test
SELECT level
FROM dual
CONNECT BY level <= 10;
COMMIT;
SELECT val
FROM rownum_order_test
ORDER BY val;
VAL
----------
1
1
2
2
3
3
4
4
5
5
6
VAL
----------
6
7
7
8
8
9
9
10
10
20 rows selected.
Naresh it Technologies
ORACLE 12c
SQL>
Top-N Queries
The syntax for the row limiting clause looks a little complicated at first glance.
Actually, for the classic Top-N query it is very simple. The example below returns the 5
largest values from an ordered set. Using the ONLY clause limits the number of rows
returned to the exact number requested.
SELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;
VAL
----------
10
10
9
9
8
5 rows selected.
SQL>
Using the WITH TIES clause may result in more rows being returned if multiple rows
match the value of the Nth row. In this case the 5th row has the value "8", but there
are two rows that tie for 5th place, so both are returned.
SELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS WITH TIES;
VAL
----------
10
10
9
Naresh it Technologies
ORACLE 12c
9
8
8
6 rows selected.
SQL>
In addition to limiting by row count, the row limiting clause also allows us to limit by
percentage of rows. The following query returns the bottom 20% of rows.
SELECT val
FROM rownum_order_test
ORDER BY val
FETCH FIRST 20 PERCENT ROWS ONLY;
VAL
----------
1
1
2
2
4 rows selected.
SQL>
Paging through an ordered resultset was a little annoying using the classic Top-N query
approach, as it required two Top-N queries, one nested inside the other. For
example, if we wanted the second block of 4 rows we might do the following.
SELECT val
FROM (SELECT val, rownum AS rnum
FROM (SELECT val
FROM rownum_order_test
ORDER BY val)
WHERE rownum <= 8)
WHERE rnum >= 5;
VAL
----------
3
3
4
Naresh it Technologies
ORACLE 12c
4 rows selected.
SQL>
With the row limiting clause we can achieve the same result using the following query.
SELECT val
FROM rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;
VAL
----------
3
3
4
4
4 rows selected.
SQL>
The OFFSET is always based on a number of rows, but this can be combined with
a FETCH using a PERCENT.
SELECT val
FROM rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 20 PERCENT ROWS ONLY;
VAL
----------
3
3
4
4
4 rows selected.
SQL>
Naresh it Technologies
ORACLE 12c
Not surprisingly, the offset, rowcount and percent can, and probably should, be bind
variables.
BEGIN
:v_offset := 4;
:v_next := 4;
END;
/
SELECT val
FROM rownum_order_test
ORDER BY val
OFFSET :v_offset ROWS FETCH NEXT :v_next ROWS ONLY;
VAL
----------
3
3
4
4
SQL>
Extra Information
The keywords ROW and ROWS can be used interchangeably, as can the FIRST and NEXT keywords.
Pick the ones that scan best when reading the SQL like a sentence.
If the offset is not specified it is assumed to be 0.
Negative values for the offset, rowcount or percent are treated as 0.
Null values for offset, rowcount or percent result in no rows being returned.
Fractional portions of offset, rowcount or percent are truncated.
If the offset is greater than or equal to the total number of rows in the set, no rows are returned.
If the rowcount or percent are greater than the total number of rows after the offset, all rows are
returned.
The row limiting clause can not be used with the FOR
UPDATE clause, CURRVAL and NEXTVAL sequence pseudocolumns or in an fast refresh materialized
view.
SQL*LOADER
SQL*LOADER utility is used to load data from other data source into Oracle. For example, if you have a
table in FOXPRO, ACCESS or SYBASE or any other third party database, you can use SQL Loader to load the
data into Oracle Tables. SQL Loader will only read the data from Flat files. So If you want to load the data
Naresh it Technologies
ORACLE 12c
from Foxpro or any other database, you have to first convert that data into Delimited Format flat file or
Fixed length format flat file, and then use SQL loader to load the data into Oracle.
SQL*Loader:
Has a powerful data parsing engine which puts little limitation on the format of the data in the
datafile.
Can load data from multiple datafiles during the same load session.
Can load data into multiple tables during the same load session.
Can selectively load data (you can load records based on the records' values).
Can manipulate the data before loading it, using SQL functions.
Can use the operating system's file system to access the datafile(s).
SQL*LOADER overview :-
SQL*Loader takes as input a control file, which controls the behavior of SQL*Loader, and one or more
datafiles. Output of the SQL*Loader is an Oracle database (where the data is loaded), a log file, a bad file,
and potentially a discard file.
Naresh it Technologies
ORACLE 12c
SQL*Loader reads data from one or more files (or operating system equivalents of files) specified in the
control file.
INFILE: Specifying Datafiles. From SQL*Loader's perspective, the data in the datafile is organized as
records. A particular datafile can be in fixed record format, variable record format, or stream record
format.
When you specify that a datafile is in variable record format, SQL*Loader expects to find the length of each
record in a character field at the beginning of each record in the datafile.
The control file is a text file written in a language that SQL*Loader understands. The control file describes
the task that the SQL*Loader is to carry out. The control file tells SQL*Loader where to find the data, how
to parse and interpret the data, where to insert the data, and more.
Naresh it Technologies
ORACLE 12c
The first section contains session-wide information, for example: global options such as bindsize, rows,
records to skip, etc. INFILE clauses to specify where the input data is located
The second section consists of one or more "INTO TABLE" blocks. Each of these blocks contains information
about the table into which the data is to be loaded such as the table name and the columns of the table.
Suppose you have a table in MS-ACCESS by name EMP, running under Windows O/S, with the following
structure
EMPNO INTEGER
NAME TEXT(50)
SAL CURRENCY
JDATE DATE
This table contains some 10,000 rows. Now you want to load the data from this table into an Oracle Table.
Oracle Database is running in LINUX O/S.
Steps:-
Start MS-Access and convert the table into comma delimited flat (popularly known as csv) , by clicking on
File/Save As menu. Let the delimited file name be emp.csv
For example:-
C:\>ftp 200.200.100.111
Name: oracle
Password:oracle
FTP>
Now give PUT command to transfer file from current Windows machine to Linux machine.
FTP>put
Local file:C:\>emp.csv
remote-file: /u01/oracle/emp.csv
Naresh it Technologies
ORACLE 12c
FTP>
Now after the file is transferred quit the FTP utility by typing bye command.
FTP>bye
Good-Bye
Now come the Linux Machine and create a table in Oracle with the same structure as in MS-ACCESS by
taking appropriate datatypes. For example, create a table like this
$sqlplus scott/tiger
After creating the table, you have to write a control file describing the actions which SQL Loader should do.
You can use any text editor to write the control file. Now let us write a controlfile for our case study
$vi emp.ctl
LOAD DATA
INFILE ‘/u01/oracle/emp.csv’
BADFILE ‘/u01/oracle/emp.bad’
DISCARDFILE ‘/u01/oracle/emp.dsc’
INSERT INTO TABLE emp
FIELDS TERMINATED BY “,” OPTIONALLY ENCLOSED BY ‘”’ TRAILING NULLCOLS
(empno,name,sal,jdate date ‘mm/dd/yyyy’)
After you have wrote the control file save it and then, call SQL Loader utility by typing the following
command
$sqlldr userid=scott/tiger
control=emp.ctl log=emp.log
After you have executed the above command SQL Loader will shows you the output describing how many
rows it has loaded.
The LOG option of sqlldr specifies where the log file of this sql loader session should be created. The log
file contains all actions which SQL loader has performed i.e. how many rows were loaded, how many were
rejected and how much time is taken to load the rows and etc. You have to view this file for any errors
encountered while running SQL Loader.
CASE STUDY (Loading Data from Fixed Length file into Oracle)
Suppose we have a fixed length format file containing employees data, as shown below, and wants to load
this data into an Oracle table.
Naresh it Technologies
ORACLE 12c
Steps :-
1. First Open the file in a text editor and count the length of fields, for example in our fixed length file,
employee number is from 1st position to 4th position, employee name is from 6th position to 15th
position, Job name is from 17th position to 25th position. Similarly other columns are also located.
2. Create a table in Oracle, by any name, but should match columns specified in fixed length file. In our
case give the following command to create the table.
$vi empfix.ctl
LOAD DATA
INFILE '/u01/oracle/fix.dat'
INTO TABLE emp
( empno POSITION(01:04) INTEGER EXTERNAL,
name POSITION(06:15) CHAR,
job POSITION(17:25) CHAR,
mgr POSITION(27:30) INTEGER EXTERNAL,
sal POSITION(32:39) DECIMAL EXTERNAL,
comm POSITION(41:48) DECIMAL EXTERNAL,
deptno POSITION(50:51) INTEGER EXTERNAL)
Naresh it Technologies
ORACLE 12c
CASE STUDY (Loading Data into Multiple Tables using WHEN condition)
You can simultaneously load data into multiple tables in the same session. You can also use WHEN
condition to load only specified rows which meets a particular condition (only equal to “=” and not equal to
“<>” conditions are allowed).
For example, suppose we have a fixed length file as shown below
Now we want to load all the employees whose deptno is 10 into emp1 table and those employees whose
deptno is not equal to 10 in emp2 table. To do this first create the tables emp1 and emp2 by taking
appropriate columns and datatypes. Then, write a control file as shown below
$vi emp_multi.ctl
Load Data
infile ‘/u01/oracle/empfix.dat’
APPEND into table scott.emp1
WHEN (deptno=’10 ‘)
(empno POSITION(01:04) INTEGER EXTERNAL,
name POSITION(06:15) CHAR,
job POSITION(17:25) CHAR,
mgr POSITION(27:30) INTEGER EXTERNAL,
sal POSITION(32:39) DECIMAL EXTERNAL,
comm POSITION(41:48) DECIMAL EXTERNAL,
deptno POSITION(50:51) INTEGER EXTERNAL)
INTO TABLE scott.emp2
WHEN (deptno<>’10 ‘)
(empno POSITION(01:04) INTEGER EXTERNAL,
name POSITION(06:15) CHAR,
job POSITION(17:25) CHAR,
mgr POSITION(27:30) INTEGER EXTERNAL,
sal POSITION(32:39) DECIMAL EXTERNAL,
comm POSITION(41:48) DECIMAL EXTERNAL,
deptno POSITION(50:51) INTEGER EXTERNAL)
$sqlldr userid=scott/tiger
Naresh it Technologies
ORACLE 12c
control=emp_multi.ctl
LOAD DATA
INFILE *
INTO TABLE emp
FIELDS TERMINATED BY “,”
( emp_num, emp_name, mgr, department_name )
BEGINDATA
7369,SMITH,7902,Accounting
7499,ALLEN,7698,Sales
7521,WARD,7698,Accounting
7566,JONES,7839,Sales
7654,MARTIN,7698,Accounting
TYPE OF LOADING:
INSERT — If the table you are loading is empty, INSERT can be used.
APPEND — If data already exists in the table, SQL*Loader appends the new rows to it. If data doesn’t
already exist, the new rows are simply loaded.
REPLACE — All rows in the table are deleted and the new data is loaded
Naresh it Technologies
ORACLE 12c
External Tables
The external tables feature is a complement to existing SQL*Loader functionality. It enables you to access
data in external sources as if it were in a table in the database. Prior to Oracle Database 10g, external
tables were read-only. However, as of Oracle Database 10g, external tables can also be written to.
External tables are created using the SQL CREATE TABLE...ORGANIZATION EXTERNAL statement. When
you create an external table, you specify the following attributes:
TYPE :- specifies the type of external table. The two available types are the ORACLE_LOADER type and the
ORACLE_DATAPUMP type.
ORACLE_LOADER :- access driver is the default. It can perform only data loads, and the data must come
from text datafiles. Loads from external tables to internal tables are done by reading from the external
tables' text-only datafiles.
ORACLE_DATAPUMP :- access driver can perform both loads and unloads. The data must come from
binary dump files. Loads to internal tables from external tables are done by fetching from the binary dump
files. Unloads from internal tables to external tables are done by populating the external tables' binary
dump files.
DEFAULT DIRECTORY :- specifies the default location of files that are read or written by external tables.
The location is specified with a directory object, not a directory path.
ACCESS PARAMETERS :- describe the external data source and implements the type of external table that
was specified. Each type of external table has its own access driver that provides access parameters unique
to that type of external table.
LOCATION:-- specifies the location of the external data. The location is specified as a list of directory
objects and filenames. If the directory object is not specified, then the default directory object is used as
the file location.
The access driver does not allow you to specify a complete specification for files. This is because the server
may have access to files that you do not, and allowing you to read this data would affect security.
Instead, you are required to specify directory objects as the locations from which to read files and write
files. A directory object maps a name to a directory name on the file system. For example, the following
statement creates a directory object named ext_tab_dir that is mapped to a directory located at
/usr/apps/datafiles.
Directory objects can be created by DBAs or by any user with the CREATE ANY DIRECTORY privilege.
After a directory is created, the user creating the directory object needs to grant READ and WRITE
privileges on the directory to other users.
Naresh it Technologies
ORACLE 12c
Step 4 :- Load the data from the external table emp_load into the table emp:
Step 5 :- Perform the following select operation to verify that the information in the .dat file was loaded
into the emp table:
Naresh it Technologies
ORACLE 12c
Analytical Functions
Analytic Functions are commonly used to compute cumulative, moving, centered and reporting
aggregates.
Oracle provides several analytic functions that help compute an aggregate value based on a group of
rows.
Analytic Functions provided by Oracle open up a whole new way of looking at the data.
It helps remove a lot of procedural code and complex code spec that would have taken a long time to
develop, to achieve the same result.
Whatever an analytic function does, can be done by using SQL, with the help of joins and subqueries.
However, an analytic function always does it faster, when compared to native SQL.
AVG
CORR
COVAR_POP
COVAR_SAMP
COUNT
CUME_DIST
DENSE_RANK
FIRST
FIRST_VALUE
LAG
LAST
LAST_VALUE
LEAD
MAX
MIN
NTILE
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
RANK
RATIO_TO_REPORT
STDDEV
STDDEV_POP
STDDEV_SAMP
SUM
VAR_POP
VAR_SAMP
VARIANCE
Naresh it Technologies
ORACLE 12c
Syntax:-
Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [<window_clause>] )
Where,
The PARTITION BY clause logically breaks a single result set into N groups, according to the criteria set by
the partition expressions.
The words partition and group are used synonymously here.
The analytic functions cane be applied to each group independently.
Order By Clause:
The ORDER BY clause specifies how the data is sorted within each group [partition]. This will definitely
affects the outcome of any analytic function.
Windowing Clause:
The windowing clause allows defining a sliding or anchored window of data, on which the analytic function
will operate, within a group.
Consider the above and its result. The above returns departments and their employee count. Most
importantly it groups the records into departments. As such any non-"group by" column is not allowed in
the select clause.
Naresh it Technologies
ORACLE 12c
Now consider the analytic function query and its result. Note the repeating values of DEPT_COUNT
column.This brings out the main difference between aggregate and analytic functions. Analytical function
returns aggregate data along with detailed data.
Analytic functions are computed after WHERE clause, GROUP BY and HAVING . The ORDER BY clause of
the query operates after the analytic functions. So analytic functions can only appear in the select list and
in the ORDER BY clause of the query.
In absence of any PARTITION or <window_clause> inside the OVER( ) portion, the function acts on entire
record set returned by the where clause.
ROW_NUMBER( ) :-
gives a running serial number to a partition of records. It is very useful in reporting, especially in places
where different partitions have their own serial numbers. In below ecxmple the function ROW_NUMBER( )
is used to give separate sets of running serial to employees of departments 10 and 20 based on their
HIREDATE.
SQL> SELECT empno, deptno, hiredate,ROW_NUMBER( ) OVER (PARTITION BY deptno
ORDER BY hiredate NULLS LAST) SRLNO
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, SRLNO;
Naresh it Technologies
ORACLE 12c
Computes the RANK of a row in an ordered group of rows and returns rank as a number begins with 1.this
function is useful to find top-N & bottom-N records.
Example :-
NOTE :- The difference between RANK & DENSE_RANK is RANK function generates gaps but DENSE_RANK
function doesn’t generate gaps.
RANK() and DENSE_RANK() function can be used to find top-N records as follows :-
Display top 3 maximum salaries in emp table ?
The syntax of LAG is similar except that the offset for LAG goes into the previous rows.below example
Naresh it Technologies
ORACLE 12c
and its result show simple usage of LAG and LEAD function.
The FIRST_VALUE analytic function picks the first record from the partition after doing the ORDER BY. The
<sql_expr> is computed on the columns of this first record and results are returned. The LAST_VALUE
function is used in similar context except that it acts on the last record of the partition.
How many days after the first hire of each department were the next employees hired?
Naresh it Technologies
ORACLE 12c
SQL>SELECT empno,
deptno,
sal,
MIN(sal) KEEP (DENSE_RANK FIRST ORDER BY sal) OVER (PARTITION BY deptno) "Lowest",
MAX(sal) KEEP (DENSE_RANK LAST ORDER BY sal) OVER (PARTITION BY deptno) "Highest"
FROM emp
ORDER BY deptno, sal ;
How each employee's salary compare with the average salary of the first year hires of their
department?
Naresh it Technologies
ORACLE 12c
WINDOW clause :-
Some analytic functions (AVG, COUNT, FIRST_VALUE, LAST_VALUE, MAX, MIN and SUM among the ones
we discussed) can take a window clause to further sub-partition the result and apply the analytic function.
An important feature of the windowing clause is that it is dynamic in nature.
1.UNBOUNDED PECEDING
2.CURRENT ROW
3.<sql_expr> PRECEDING or FOLLOWING.
1.UNBOUNDED FOLLOWING or
2.CURRENT ROW or
3.<sql_expr> PRECEDING or FOLLOWING.
For ROW type windows the definition is in terms of row numbers before or after the current row. So for
ROW type windows <sql_expr> must evaluate to a positive integer.
For RANGE type windows the definition is in terms of values before or after the current ORDER. We will
take this up in details latter.
The ROW or RANGE window cannot appear together in one OVER clause. The window clause is defined in
terms of the current row. But may or may not include the current row. The start point of the window and
the end point of the window can finish before the current row or after the current row. Only start point
cannot come after the end point of the window. In case any point of the window is undefined the default is
UNBOUNDED PRECEDING for <start_expr> and UNBOUNDED FOLLOWING for <end_expr>.
If the end point is the current row, syntax only in terms of the start point can be can be
[ROW or RANGE] [<start_expr> PRECEDING or UNBOUNDED PRECEDING ]
[ROW or RANGE] CURRENT ROW is also allowed but this is redundant. In this case the function behaves as
a single-row function and acts only on the current row.
Naresh it Technologies
ORACLE 12c
For analytic functions with ROW type windows, the general syntax is:
Function( ) OVER (PARTITIN BY <expr1> ORDER BY <expr2,..> ROWS BETWEEN <start_expr> AND
<end_expr>)
or
Function( ) OVER (PARTITON BY <expr1> ORDER BY <expr2,..> ROWS [<start_expr> PRECEDING or
UNBOUNDED PRECEDING]
For ROW type windows the windowing clause is in terms of record numbers.
SQL>SELECT ename,sal,
SUM(sal) over (order by sal ROWS UNBOUNDED PRECEDING)
as cum_sal
from emp ;
Optimizer Hints
Optimizer hints can be used with SQL statements to alter execution plans. This chapter explains how to use
hints to force various approaches.
Hints let you make decisions usually made by the optimizer. As an application designer, you might know
information about your data that the optimizer does not know. For example, you might know that a certain
index is more selective for certain queries. Based on this information, you might be able to choose a more
efficient execution plan than the optimizer. In such a case, use hints to force the optimizer to use the
optimal execution plan.
Hints apply only to the optimization of the statement block in which they appear. A statement block is any
one of the following statements or parts of statements:
Syntax:-
The hints described in this section let you choose between the cost-based and the rule-based optimization
approaches. With the cost-based approach, this also includes the goal of best throughput or best response
time.
In ORACLE 10g rule-based optimization is obselete , but still supports for backward compatability.
ALL_ROWS
FIRST_ROWS(n)
ALL_ROWS :-
The ALL_ROWS hint explicitly chooses the cost-based approach to optimize a statement block with a goal
of best throughput (that is, minimum total resource consumption).
The hints FIRST_ROWS(n) (where n is any positive integer) or FIRST_ROWS instruct Oracle to optimize an
individual SQL statement for fast response. FIRST_ROWS(n) instructs Oracle to choose the plan that
returns the first n rows most efficiently.
In this example each department contains many employees. The user wants the first 10 employees of
department #20 to be displayed as quickly as possible.
The optimizer ignores this hint in DELETE and UPDATE statement blocks and in SELECT statement blocks
that contain any of the following syntax:
Naresh it Technologies
ORACLE 12c
These statements cannot be optimized for best response time, because Oracle must retrieve all rows
accessed by the statement before returning the first row. If you specify this hint in any of these
statements, then the optimizer uses the cost-based approach and optimizes for best throughput.
FULL
ROWID
CLUSTER
HASH
INDEX
INDEX_ASC
INDEX_COMBINE
INDEX_JOIN
INDEX_DESC
INDEX_FFS
NO_INDEX
AND_EQUAL
Specifying one of these hints causes the optimizer to choose the specified access path only if the access
path is available based on the existence of an index or cluster and on the syntactic constructs of the SQL
statement. If a hint specifies an unavailable access path, then the optimizer ignores it.
FULL :-
The FULL hint explicitly chooses a full table scan for the specified table.
Oracle performs a full table scan on the employees table to execute this statement, even if there is an
index on the last_name column that is made available by the condition in the WHERE clause.
INDEX hint:-
The INDEX hint explicitly chooses an index scan for the specified table. You can use the INDEX hint for
domain, B-tree, bitmap, and bitmap join indexes. However, Oracle recommends using INDEX_COMBINE
rather than INDEX for bitmap indexes, because it is a more versatile hint.
If hint specifies a single available index, then the optimizer performs a scan on this index. The optimizer
does not consider a full table scan or a scan on another index on the table.
Naresh it Technologies
ORACLE 12c
If hint specifies a list of available indexes, then the optimizer considers the cost of a scan on each index in
the list and then performs the index scan with the lowest cost.
If hint specifies no indexes, then the optimizer considers the cost of a scan on each available index on the
table and then performs the index scan with the lowest cost.
For example, consider this query that selects the name, job and salary all male employees
If you know that the value in the WHERE clause of the query appears in a very small percentage of the
rows, then you can use the INDEX hint to force the optimizer to choose an index scan. In this statement,
the INDEX hint explicitly chooses an index scan on the sex_index, the index on the sex column:
SELECT /*+ INDEX(patients sex_index) use sex_index because there are few
male patients */ name, height, weight
FROM patients
WHERE sex = 'm';
INDEX_COMBINE hint:-
The INDEX_COMBINE hint explicitly chooses a bitmap access path for the table.
JOIN ORDERS:-
The ORDERED hint causes Oracle to join tables in the order in which they appear in the FROM clause.
If you omit the ORDERED hint from a SQL statement performing a join, then the optimizer chooses the
order in which to join the tables. You might want to use the ORDERED hint to specify a join order if you
know something about the number of rows selected from each table that the optimizer does not. Such
information lets you choose an inner and outer table better than the optimizer could.
Naresh it Technologies
ORACLE 12c
JOIN OPERATIONS:-
USE_NL
USE_MERGE
USE_HASH
DRIVING_SITE
LEADING
HASH_AJ, MERGE_AJ, and NL_AJ
HASH_SJ, MERGE_SJ, and NL_SJ
USE_NL hint :-
The USE_NL hint causes Oracle to join each specified table to another row source with a nested loops join,
using the specified table as the inner table.
For example, consider this statement, which joins the accounts and customers tables. Assume that these
tables are not stored together in a cluster:
Because the default goal of the cost-based approach is best throughput, the optimizer chooses either a
nested loops operation, a sort-merge operation, or a hash operation to join these tables, depending on
which is likely to return all the rows selected by the query more quickly.
However, you might want to optimize the statement for best response time or the minimal elapsed time
necessary to return the first row selected by the query, rather than best throughput. If so, then you can
force the optimizer to choose a nested loops join by using the USE_NL hint. In this statement, the USE_NL
hint explicitly chooses a nested loops join with the customers table as the inner table:
In many cases, a nested loops join returns the first row faster than a sort merge join. A nested loops join
can return the first row after reading the first selected row from one table and the first matching row from
the other and combining them, while a sort merge join cannot return the first row until after reading and
sorting all selected rows of both tables and then combining the first rows of each sorted row source.
In the following statement where a nested loop is forced through a hint, orders is accessed through a full
table scan and the filter condition l.order_id = h.order_id is applied to every row. For every row that meets
the filter condition, order_items is accessed through the index order_id.
Naresh it Technologies
ORACLE 12c
USE_MERGE hint:-
The USE_MERGE hint causes Oracle to join each specified table with another row source, using a sort-
merge join.
USE_HASH hint:-
The USE_HASH hint causes Oracle to join each specified table with another row source, using a hash join.
PARALLEL
The PARALLEL hint lets you specify the desired number of concurrent servers that can be used for a parallel
operation. The hint applies to the SELECT, INSERT, UPDATE, and DELETE portions of a statement, as well as
to the table scan portion.
The number of servers that can be used is twice the value in the PARALLEL hint, if sorting or grouping
operations also take place.If any parallel restrictions are violated, then the hint is ignored.
The PARALLEL hint must use the table alias, if an alias is specified in the query. The hint can then take two
values, separated by commas after the table name. The first value specifies the degree of parallelism for
the given table, and the second value specifies how the table is to be split among the Oracle Real
Application Clusters instances. Specifying DEFAULT or no value signifies that the query coordinator should
examine the settings of the initialization parameters to determine the default degree of parallelism. In the
following example, the PARALLEL hint overrides the degree of parallelism specified in the employees table
definition:
In the next example, the PARALLEL hint overrides the degree of parallelism specified in the employees
table definition and tells the optimizer to use the default degree of parallelism determined by the
initialization parameters. This hint also specifies that the table should be split among all of the available
instances, with the of parallelism on each instance.
Naresh it Technologies
ORACLE 12c
Data Pump
Oracle Data Pump (expdp and impdp) introduced in Oracle Database 10g is faster and more flexible
alternative to the "exp" and "imp" utilities used in previous Oracle versions. In addition to basic import and
export functionality data pump provides a PL/SQL API and support for external tables.
To use DATA PUMP utilities first we must create a directory object . The directory object is only a pointer to
a physical directory, creating it does not actually create the physical directory on the file system.
SQL>CONN SYSTEM/MANAGER
SQL>CREATE OR REPLACE DIRECTORY test_dir AS 'C:\WINDOWS’
SQL>GRANT READ, WRITE ON DIRECTORY test_dir TO scott;
Existing directories can be queried using the ALL_DIRECTORIES view.
Table Exports/Imports :-
The TABLES parameter is used to specify the tables that are to be exported. The following is an example of
the table export and import syntax and command should be executed at command prompt.
Database Exports/Imports
The FULL parameter indicates that a complete database export is required. The following is an example of
the full database export and import syntax.
Naresh it Technologies
ORACLE 12c
The INCLUDE and EXCLUDE parameters can be used to limit the export/import to specific objects. When
the INCLUDE parameter is used, only those objects specified by it will be included in the export/import.
When the EXCLUDE parameter is used, all objects except those specified by it will be included in the
export/import. The two parameters are mutually exclusive, so use the parameter that requires the least
entries to give you the result you require. The basic syntax for both parameters is the same.
Naresh it Technologies
ORACLE 12c
Regular Expressions
The database provides a set of SQL functions that allow you to search and manipulate strings using regular
expressions. You can use these functions on any datatype that holds character data such as CHAR, NCHAR,
CLOB, NCLOB, NVARCHAR2, and VARCHAR2
A regular expression must be enclosed or wrapped between single quotes. Doing so, ensures that the
entire expression is interpreted by the SQL function and can improve the readability of your code.
This function searches a character column for a pattern. Use this function in the WHERE clause of a query
to return rows matching the regular expression you specify.
REGEXP_REPLACE
This function searches for a pattern in a character column and replaces each occurrence of that pattern
with the pattern you specify.
REGEXP_INSTR
This function searches a string for a given occurrence of a regular expression pattern. You specify which
occurrence you want to find and the start position to search from. This function returns an integer
indicating the position in the string where the match is found.
REGEXP_SUBSTR
This function returns the actual substring matching the regular expression pattern you specify.
. Any Character
+ One or More
? Zero or One
* Zero or more
{m} Interval--Exact Count
{m,} Interval--At Least Count
{m,n} Interval--Between Count
[ ... ] Matching Character List
[^ ... ] Non-Matching Character List
| Or
( ... ) Subexpression or Grouping
\n Backreference
\ Escape Character
Naresh it Technologies
ORACLE 12c
The one or more operator '+' matches one or more occurrences of the preceding expression. For example,
to find one or more occurrences of the character 'a', you use the regular expression:
a+
This expression matches all of the following:
a
aa
aaa
The expression does not match:
bbb
Zero or One--Question Mark Operator:-
The question mark matches zero or one--and only one--occurrence of the preceding character or
subexpression. You can think of this operator as specifying an expression that is optional in the source text.
For example, to find--'a', optionally followed by 'b', then followed by 'c'--you use the following regular
expression:
ab?c
This expression matches:
abc
ac
Naresh it Technologies
ORACLE 12c
adc
abbc
Zero or More—Star:-
The zero or more operator '*', matches zero or more occurrences of the preceding character or
subexpression. For example, to find--'a', followed by zero or more occurrences of 'b', then followed by 'c'--
use the regular expression:
ab*c
ac
abc
abbc
abbbbc
adc
Interval--Exact Count:-
The exact-count interval operator is specified with a single digit enclosed in braces. You use this operator
to search for an exact number of occurrences of the preceding character or subexpression.
For example, to find where 'a' occurs exactly 5 times, you specify the regular expression:
a{5}
aaaaa
aaaa
You use the at-least-count interval operator to search for a specified number of occurrences, or more, of
the preceding character or subexpression. For example, to find where 'a' occurs at least 3 times, you use
the regular expression:
Naresh it Technologies
ORACLE 12c
a{3,}
aaa
aaaaa
aa
Interval--Between Count:-
You use the between-count interval operator to search for a number of occurrences within a specified
range. For example, to find where 'a' occurs at least 3 times and no more than 5 times, you use the
following regular expression:
a{3,5}
aaa
aaaa
aaaaa
aa
You use the matching character list to search for an occurrence of any character in a list. For example, to
find either 'a', 'b', or 'c' use the following regular expression:
[abc]
This expression matches the first character in each of the following strings:
at
bet
cot
def
The following regular expression operators are allowed within the character list, any other metacharacters
included in a character list lose their special meaning (are treated as literals):
Naresh it Technologies
ORACLE 12c
[^abc]
As with the matching character list, the following regular expression operators are allowed within the non-
matching character list (any other metacharacters included in a character list are ignored):
For example, the following regular expression excludes any character between 'a' and 'i' from the search
result:
[^a-i]
This expression matches the characters 'j' and 'l' in the following strings:
hijk
lmn
abcdefghi
Or
Use the Or operator '|' to specify an alternate expression. For example to match 'a' or 'b', use the following
regular expression:
a|b
Subexpression:-
You can use the subexpression operator to group characters that you want to find as a string or to create a
complex expression. For example, to find the optional string 'abc', followed by 'def', use the following
regular expression:
Naresh it Technologies
ORACLE 12c
(abc)?def
This expression matches strings 'abcdef' and 'def' in the following strings:
abcdefghi
defghi
ghi
Backreference:-
The backreference lets you search for a repeated expression. You specify a backreference with '\n', where
n is an integer from 1 to 9 indicating the nth preceding subexpression in your regular expression.
For example, to find a repeated occurrence of either string 'abc' or 'def', use the following regular
expression:
(abc|def)\1
abcabc
defdef
abcdef
abc
Escape Character:-
Use the escape character '\' to search for a character that is normally treated as a metacharacter. For
example to search for the '+' character, use the following regular expression:
\+
This expression matches the plus character '+' in the following string:
abc+def
abcdef
Naresh it Technologies
ORACLE 12c
Use the beginning of line anchor ^ to search for an expression that occurs only at the beginning of a line.
For example, to find an occurrence of the string def at the beginning of a line, use the expression:
^def
defghi
abcdef
The end of line anchor metacharacter '$' lets you search for an expression that occurs only at the end of a
line. For example, to find an occurrence of def that occurs at the end of a line, use the following
expression:
def$
abcdef
defghi
Examples:-
Naresh it Technologies
ORACLE 12c
The above example displays enames that start with S and end with T. It may contain anything in between
these two.
If you want to modify the way REGEXP_LIKE compares characters then third parameter, which contains
either 'c' for case sensitive or 'i' for ignore case, can be given as shown below.
Now let us see how REGEXP_SUBSTR is used to extract a substring based on regular expression.
SQL>SELECT regexp_substr('Oracle Database 10g is first grid aware database','[0-9]+') version FROM
DUAL;
SQL>SELECT regexp_substr('Oracle Database 10g is first grid aware database','[0-9]+[a-z]') version FROM
DUAL;
The following query displays the starting position of one or more digits.
SQL>SELECT regexp_instr('Oracle Database 10g is first grid aware database','[0-9]+') position FROM
DUAL;
The following query returns the positon of first non-alphabet in the given string.
SQL>SELECT regexp_instr('Abc123 xyz123','[^[:alpha:]]') FROM DUAL;
The following query places a space between Oracle its version using REGEXP_REPLACE function. For
example, Oracle9i will become Oracle 9i, Oracle10g will become Oracle 10g.
SQL>SELECT regexp_replace('Oracle10g','([[:alpha:]]+)([[:digit:]]+.)','\1 \2') FROM DUAL;
We extract series of alphabets and take them as group 1. Then we are looking for a group of digits
followed by any character and treat it as group 2. Then we replace the original with \1 (group 1) a space
and \2 (group 2).
Naresh it Technologies
ORACLE 12c
XML
the above package contains a function called GETXML that takes SELECT QUERY and displays query result
in XML format.
Example:-
Output :-
<?xml version="1.0"?>
<ROWSET>
<ROW>
<DEPTNO>10</DEPTNO>
<DNAME>ACCOUNTING</DNAME>
<LOC>NEW YORK</LOC>
</ROW>
<ROW>
<DEPTNO>20</DEPTNO>
<DNAME>RESEARCH</DNAME>
<LOC>DALLAS</LOC>
</ROW>
<ROW>
<DEPTNO>30</DEPTNO>
<DNAME>SALES</DNAME>
<LOC>CHICAGO</LOC>
</ROW>
<ROW>
<DEPTNO>40</DEPTNO>
<DNAME>OPERATIONS</DNAME>
<LOC>BOSTON</LOC>
</ROW>
</ROWSET>
Naresh it Technologies
ORACLE 12c
Output :-
<Date>1994-06-07</Date>
SQL>SELECT XMLElement("Date", to_char(hiredate))
FROM emp
WHERE empno=7844 ;
Output :-
<Date>07-JUN-1994</Date>
EMPNO RESULT
7369 <Emp>SMITH</Emp>
7499 <Emp>ALLEN</Emp>
7521 <Emp>WARD</Emp>
7566 <Emp>JONES</Emp>
7654 <Emp>MARTIN</Emp>
7698 <Emp>BLAKE</Emp>
7782 <Emp>CLARK</Emp>
7788 <Emp>SCOTT</Emp>
7839 <Emp>KING</Emp>
7844 <Emp>TURNER</Emp>
7876 <Emp>ADAMS</Emp>
7900 <Emp>JAMES</Emp>
7902 <Emp>FORD</Emp>
7934 <Emp>MILLER</Emp>
Naresh it Technologies
ORACLE 12c
RESULT
<Emp><name>SMITH</name><hiredate>1980-12-17</hiredate></Emp>
<Emp><name>ALLEN</name><hiredate>1981-02-20</hiredate></Emp>
<Emp><name>WARD</name><hiredate>1981-02-22</hiredate></Emp>
<Emp><name>JONES</name><hiredate>1981-04-02</hiredate></Emp>
<Emp><name>MARTIN</name><hiredate>1981-09-28</hiredate></Emp>
<Emp><name>BLAKE</name><hiredate>1981-05-01</hiredate></Emp>
<Emp><name>CLARK</name><hiredate>1981-06-09</hiredate></Emp>
<Emp><name>SCOTT</name><hiredate>1982-12-09</hiredate></Emp>
<Emp><name>KING</name><hiredate>1981-11-17</hiredate></Emp>
<Emp><name>TURNER</name><hiredate>1981-09-08</hiredate></Emp>
<Emp><name>ADAMS</name><hiredate>1983-01-12</hiredate></Emp>
<Emp><name>JAMES</name><hiredate>1981-12-03</hiredate></Emp>
<Emp><name>FORD</name><hiredate>1981-12-03</hiredate></Emp>
<Emp><name>MILLER</name><hiredate>1982-01-23</hiredate></Emp>
Using XMLATTRIBUTES :-
SQL> SELECT XMLElement("Emp",
XMLAttributes( empno as "ID", ename AS "name"))
AS "RESULT"
FROM emp
WHERE empno in (7369,7566,7844,7902);
RESULT :-
Naresh it Technologies
ORACLE 12c
Output :-
<Emp><Ename>SMITH</Ename><Salary>800</Salary><Department>20</Department></Emp>
<Emp><Ename>JONES</Ename><Salary>2975</Salary><Department>20</Department></Emp>
<Emp><Ename>SCOTT</Ename><Salary>3000</Salary><Department>20</Department></Emp>
<Emp><Ename>ADAMS</Ename><Salary>1100</Salary><Department>20</Department></Emp>
<Emp><Ename>FORD</Ename><Salary>3000</Salary><Department>20</Department></Emp>
Inserting XML data into ORACLE DB :-
Consider the following XMLType table containing an XML document with employee information:
SQL>CREATE TABLE emp_xml_tab OF XMLType;
Table created.
Method 1 :-
SQL>INSERT INTO emp_xml_tab VALUES(
XMLType('<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
<EMP>
<EMPNO>412</EMPNO>
<EMPNAME>Jack</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>'));
1 Row Created
Method 2:-
SQL>INSERT INTO emp_xml VALUES(
XMLType(BFILENAME(‘XMLDIR’,’emp.xml’), nls_charset_id(‘AL32UTF8’)));
Prior to Oracle 10g Release 2, retrieving data from XML typically involved manually parsing the XML DOM
tree. Oracle 10g Release 2 introduced the XMLTABLE operator, which allows you to project columns on to
XML data in an XMLTYPE, making it possible to query the data directly from SQL as if it were relational
data. This article presents some simple examples of its use.
Naresh it Technologies
ORACLE 12c
Tag-Based XML
Attribute-Based XML
Nested XML
XML Data in Variables
Performance
Tag-Based XML :-
This example uses tag-based XML, where each data element for an employee is surrounded by its own
start and end tag. First we create a table to hold our XML document and populate it with a document
containing multiple rows of data. Using XMLFOREST gives us a separate tag for each column in the query.
XMLFOREST(
e.empno AS "empno",
e.ename AS "ename",
e.job AS "job",
e.hiredate as “hiredate”
)
)
)
)
FROM emp e;
We can see the resulting row containing the tag-based XML using the following Query.
SELECT x.xml_data
FROM xml_tab x;
X.XML_DATA.GETCLOBVAL()
--------------------------------------------------------------------------------
<employees>
<employee>
<empno>7369</empno>
Naresh it Technologies
ORACLE 12c
<ename>SMITH</ename>
<job>CLERK</job>
<hiredate>17-DEC-1980</hiredate>
</employee>
<employee>
<empno>7499</empno>
<ename>ALLEN</ename>
<job>SALESMAN</job>
<hiredate>20-FEB-1981</hiredate>
</employee>
<employee>
<empno>7521</empno>
<ename>WARD</ename>
<job>SALESMAN</job>
<hiredate>22-FEB-1981</hiredate>
</employee>
<employee>
<empno>7566</empno>
<ename>JONES</ename>
<job>MANAGER</job>
<hiredate>02-APR-1981</hiredate>
</employee>
<employee>
<empno>7654</empno>
<ename>MARTIN</ename>
<job>SALESMAN</job>
<hiredate>28-SEP-1981</hiredate>
</employee>
<employee>
<empno>7698</empno>
<ename>BLAKE</ename>
<job>MANAGER</job>
<hiredate>01-MAY-1981</hiredate>
</employee>
<employee>
<empno>7782</empno>
<ename>CLARK</ename>
<job>MANAGER</job>
<hiredate>09-JUN-1981</hiredate>
</employee>
<employee>
Naresh it Technologies
ORACLE 12c
<empno>7788</empno>
<ename>SCOTT</ename>
<job>ANALYST</job>
<hiredate>19-APR-1987</hiredate>
</employee>
<employee>
<empno>7839</empno>
<ename>KING</ename>
<job>PRESIDENT</job>
<hiredate>17-NOV-1981</hiredate>
</employee>
<employee>
<empno>7844</empno>
<ename>TURNER</ename>
<job>SALESMAN</job>
<hiredate>08-SEP-1981</hiredate>
</employee>
<employee>
<empno>7876</empno>
<ename>ADAMS</ename>
<job>CLERK</job>
<hiredate>23-MAY-1987</hiredate>
</employee>
<employee>
<empno>7900</empno>
<ename>JAMES</ename>
<job>CLERK</job>
<hiredate>03-DEC-1981</hiredate>
</employee>
<employee>
<empno>7902</empno>
<ename>FORD</ename>
<job>ANALYST</job>
<hiredate>03-DEC-1981</hiredate>
</employee>
<employee>
<empno>7934</empno>
<ename>MILLER</ename>
<job>CLERK</job>
<hiredate>23-JAN-1982</hiredate>
</employee>
Naresh it Technologies
ORACLE 12c
</employees>
1 row selected.
The XMLTABLE operator allows us to split the XML data into rows and project columns on to it. We
effectively make a cartesian product between the data table and the XMLTABLE call, which allows
XMLTABLE to split a XML document in a single row into multiple rows in the final result set. The table
column is identified as the source of the data using the PASSINGclause. The rows are identified using a
XQuery expression, in this case '/employees/employee'. Columns are projected onto the resulting XML
fragments using the COLUMNS clause, which identifies the relevant tags using the PATH expression and
assigns the desired column names and data types. Be careful with the names of the columns in the
COLUMNS clause. If you use anything other than upper case, they will need to be quoted to make direct
reference to them. Notice we are querying using the alias of the XMLTABLE call, rather than the regular
table alias.
SELECT xt.*
FROM xml_tab x,
XMLTABLE('/employees/employee'
PASSING x.xml_data
COLUMNS
empno VARCHAR2(4) PATH 'empno',
ename VARCHAR2(10) PATH 'ename',
job VARCHAR2(9) PATH 'job',
hiredate VARCHAR2(11) PATH 'hiredate'
) xt;
Naresh it Technologies
ORACLE 12c
14 rows selected.
Attribute-Based XML :-
This example uses attribute-based XML, where each data element for an employee is
defined as an attribute of the employee tag, not a separate tag.Truncate the table we
defined for the previous example and populate it with a document containing multiple
rows of data. Using XMLATTRIBUTES creates an attribute for each column in the query.
SQL>INSERT INTO XML_TAB
SELECT XMLELEMENT("employees",
XMLAGG(
XMLELEMENT("employee",
XMLATTRIBUTES(
e.empno AS "empno",
e.ename AS "ename",
e.job AS "job",
TO_CHAR(e.hiredate, 'DD-MON-YYYY') AS "hiredate"
)
)
)
)
We can see the resulting row containing the attribute-based XML using
the following query.
SQL>SELECT x.xml_data
FROM xml_tab x;
Naresh it Technologies
ORACLE 12c
X.XML_DATA.GETCLOBVAL()
--------------------------------------------------------------------------------
<employees>
<employee empno="7369" ename="SMITH" job="CLERK" hiredate="17-
DEC-1980"/>
<employee empno="7499" ename="ALLEN" job="SALESMAN"
hiredate="20-FEB-1981"/>
<employee empno="7521" ename="WARD" job="SALESMAN"
hiredate="22-FEB-1981"/>
<employee empno="7566" ename="JONES" job="MANAGER"
hiredate="02-APR-1981"/>
<employee empno="7654" ename="MARTIN" job="SALESMAN"
hiredate="28-SEP-1981"/>
<employee empno="7698" ename="BLAKE" job="MANAGER"
hiredate="01-MAY-1981"/>
<employee empno="7782" ename="CLARK" job="MANAGER"
hiredate="09-JUN-1981"/>
<employee empno="7788" ename="SCOTT" job="ANALYST"
hiredate="19-APR-1987"/>
<employee empno="7839" ename="KING" job="PRESIDENT"
hiredate="17-NOV-1981"/>
<employee empno="7844" ename="TURNER" job="SALESMAN"
hiredate="08-SEP-1981"/>
<employee empno="7876" ename="ADAMS" job="CLERK" hiredate="23-
MAY-1987"/>
<employee empno="7900" ename="JAMES" job="CLERK" hiredate="03-
DEC-1981"/>
<employee empno="7902" ename="FORD" job="ANALYST"
hiredate="03-DEC-1981"/>
<employee empno="7934" ename="MILLER" job="CLERK"
hiredate="23-JAN-1982"/>
</employees>
1 row selected.
Naresh it Technologies
ORACLE 12c
The XMLTABLE operator allows us to split the XML data into rows and
project columns on to it. Notice this time the PATH expression uses a "@"
to indicate this is an attribute, rather than a tag.
SELECT xt.*
FROM xml_tab x,
XMLTABLE('/employees/employee'
PASSING x.xml_data
COLUMNS
empno VARCHAR2(4) PATH '@empno',
ename VARCHAR2(10) PATH '@ename',
job VARCHAR2(9) PATH '@job',
hiredate VARCHAR2(11) PATH '@hiredate'
) xt;
14 rows selected.
Naresh it Technologies
ORACLE 12c
Nested XML
So far we have dealt with simple XML, but we sometimes have to deal with XML
containing multiple levels of nesting. The simplest way to handle this to deal
with the first layer, presenting the next layer down as an XML fragment in
an XMLTYPE, which can then be processed using XMLTABLE in the next step.
Truncate the test table and insert a row of nested XML. The example below
produces a list of departments, with every department containing a nested list
of employees for that department.
DECLARE
l_xmltype XMLTYPE;
BEGIN
SELECT XMLELEMENT("departments",
XMLAGG(
XMLELEMENT("department",
XMLFOREST(
d.deptno AS "department_number",
d.dname AS "department_name",
(SELECT XMLAGG(
XMLELEMENT("employee",
XMLFOREST(
e.empno AS "employee_number",
e.ename AS "employee_name"
)
)
)
FROM emp e
WHERE e.deptno = d.deptno
) "employees"
)
)
)
)
Naresh it Technologies
ORACLE 12c
INTO l_xmltype
FROM dept d;
We can see the resulting row containing the nested XML using the following
query.
X.XML_DATA.GETCLOBVAL()
--------------------------------------------------------------------
------------
<departments>
<department>
<department_number>10</department_number>
<department_name>ACCOUNTING</department_name>
<employees>
<employee>
<employee_number>7782</employee_number>
<employee_name>CLARK</employee_name>
</employee>
<employee>
<employee_number>7839</employee_number>
<employee_name>KING</employee_name>
</employee>
<employee>
<employee_number>7934</employee_number>
<employee_name>MILLER</employee_name>
Naresh it Technologies
ORACLE 12c
</employee>
</employees>
</department>
<department>
<department_number>20</department_number>
<department_name>RESEARCH</department_name>
<employees>
<employee>
<employee_number>7369</employee_number>
<employee_name>SMITH</employee_name>
</employee>
<employee>
<employee_number>7566</employee_number>
<employee_name>JONES</employee_name>
</employee>
<employee>
<employee_number>7788</employee_number>
<employee_name>SCOTT</employee_name>
</employee>
<employee>
<employee_number>7876</employee_number>
<employee_name>ADAMS</employee_name>
</employee>
<employee>
<employee_number>7902</employee_number>
<employee_name>FORD</employee_name>
</employee>
</employees>
</department>
<department>
<department_number>30</department_number>
<department_name>SALES</department_name>
Naresh it Technologies
ORACLE 12c
<employees>
<employee>
<employee_number>7499</employee_number>
<employee_name>ALLEN</employee_name>
</employee>
<employee>
<employee_number>7521</employee_number>
<employee_name>WARD</employee_name>
</employee>
<employee>
<employee_number>7654</employee_number>
<employee_name>MARTIN</employee_name>
</employee>
<employee>
<employee_number>7698</employee_number>
<employee_name>BLAKE</employee_name>
</employee>
<employee>
<employee_number>7844</employee_number>
<employee_name>TURNER</employee_name>
</employee>
<employee>
<employee_number>7900</employee_number>
<employee_name>JAMES</employee_name>
</employee>
</employees>
</department>
<department>
<department_number>40</department_number>
<department_name>OPERATIONS</department_name>
</department>
</departments>
Naresh it Technologies
ORACLE 12c
1 row selected.
SQL>
To make things simpler we've split out the layers using the WITH clause, but this
could also be done with inline-views. The "departments_data" entry in
the WITH clause extracts the basic department data, along with an XML
fragment containing the employees for that department. The
"employees_data" entry selects the department data from the
"departments_data" entry, then extracts the employee information from the
"employees" XMLTYPE using XMLTABLE in the normal way. Finally we select
the flattened data from the "employees_data" entry.
WITH
departments_data AS (
SELECT xt.*
FROM xml_tab x,
XMLTABLE('/departments/department'
PASSING x.xml_data
COLUMNS
deptno VARCHAR2(4) PATH 'department_number',
dname VARCHAR2(10) PATH 'department_name',
employees XMLTYPE PATH 'employees'
) xt
),
employees_data AS (
SELECT deptno,
dname,
xt2.*
FROM departments_data dd,
XMLTABLE('/employees/employee'
PASSING dd.employees
COLUMNS
empno VARCHAR2(4) PATH 'employee_number',
Naresh it Technologies
ORACLE 12c
14 rows selected.
SQL>
That looks like it has worked, but we've lost department "40", which has no
employees. If we want to show that row we need to do a LEFT OUTER
JOIN between the "departments_data" entry and the XMLTABLE, as shown
below. Notice the join condition of "1=1" in the second WITH clause entry.
WITH
departments_data AS (
SELECT xt.*
FROM xml_tab x,
Naresh it Technologies
ORACLE 12c
XMLTABLE('/departments/department'
PASSING x.xml_data
COLUMNS
deptno VARCHAR2(4) PATH 'department_number',
dname VARCHAR2(10) PATH 'department_name',
employees XMLTYPE PATH 'employees'
) xt
),
employees_data AS (
SELECT deptno,
dname,
xt2.*
FROM departments_data dd
LEFT OUTER JOIN
XMLTABLE('/employees/employee'
PASSING dd.employees
COLUMNS
empno VARCHAR2(4) PATH 'employee_number',
ename VARCHAR2(10) PATH 'employee_name'
) xt2 ON 1=1
)
SELECT * FROM employees_data;
Naresh it Technologies
ORACLE 12c
15 rows selected.
SQL>
SET SERVEROUTPUT ON
DECLARE
l_xml VARCHAR2(32767);
BEGIN
l_xml := '<employees>
<employee>
<empno>7369</empno>
<ename>SMITH</ename>
<job>CLERK</job>
<hiredate>17-DEC-1980</hiredate>
</employee>
<employee>
<empno>7499</empno>
<ename>ALLEN</ename>
<job>SALESMAN</job>
<hiredate>20-FEB-1981</hiredate>
Naresh it Technologies
ORACLE 12c
</employee>
</employees>';
FOR cur_rec IN (
SELECT xt.*
FROM XMLTABLE('/employees/employee'
PASSING XMLTYPE(l_xml)
COLUMNS
empno VARCHAR2(4) PATH 'empno',
ename VARCHAR2(10) PATH 'ename',
job VARCHAR2(9) PATH 'job',
hiredate VARCHAR2(11) PATH 'hiredate'
) xt)
LOOP
DBMS_OUTPUT.put_line('empno=' || cur_rec.empno ||
' ename=' || cur_rec.ename ||
' job=' || cur_rec.job||
' hiredate=' || cur_rec.hiredate);
END LOOP;
END;
/
empno=7369 ename=SMITH job=CLERK hiredate=17-DEC-1980
empno=7499 ename=ALLEN job=SALESMAN hiredate=20-FEB-1981
SQL>
SET SERVEROUTPUT ON
DECLARE
l_xml VARCHAR2(32767);
l_xmltype XMLTYPE;
Naresh it Technologies
ORACLE 12c
BEGIN
l_xml := '<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:sawsoap="urn://oracle.bi.webservices/v6">
<soap:Body>
<sawsoap:executeSQLQueryResult>
<sawsoap:return xsi:type="sawsoap:QueryResults">
<sawsoap:rowset>
<![CDATA[<rowset xmlns="urn:schemas-microsoft-com:xml-
analysis:rowset">
<Row><Column0>1000</Column0><Column1>East Region</Column1></Row>
<Row><Column0>2000</Column0><Column1>West Region</Column1></Row>
<Row><Column0>1500</Column0><Column1>Central Region</Column1></Row>
</rowset>]]>
</sawsoap:rowset>
<sawsoap:queryID/>
<sawsoap:finished>true</sawsoap:finished>
</sawsoap:return>
</sawsoap:executeSQLQueryResult>
</soap:Body>
</soap:Envelope>';
FOR cur_rec IN (
SELECT a.mydata, xt.*
FROM (
-- Pull out just the CDATA value.
SELECT EXTRACTVALUE(XMLTYPE(l_xml),
'//sawsoap:rowset/text()','xmlns:sawsoap="urn://oracle.bi.webserv
ices/v6"') AS mydata
FROM dual
) a,
-- Specify the path that marks a new row, remembering to
use the correct namespace.
Naresh it Technologies
ORACLE 12c
XMLTABLE(XMLNAMESPACES(default 'urn:schemas-microsoft-
com:xml-analysis:rowset'), '/rowset/Row'
PASSING XMLTYPE(a.mydata)
COLUMNS
column0 NUMBER(4) PATH 'Column0',
column1 VARCHAR2(20) PATH 'Column1'
) xt)
LOOP
DBMS_OUTPUT.put_line('column0=' || cur_rec.column0 || '
column1=' || cur_rec.column1);
END LOOP;
END;
/
column0=1000 column1=East Region
column0=2000 column1=West Region
column0=1500 column1=Central Region
SQL>
Performance
The XMLTABLE operator works really well with small XML documents, or tables
with many rows, each of which contain a small XML document. As the XML
documents get bigger the performance gets worse compared to the manual
parse method. When dealing with large XML documents you may have to
forgo the convenience for the XMLTABLE operator in favour of a manual
solution.
Naresh it Technologies
ORACLE 12c
Queries to practice:-
1.Display the dept information from department table
2.Display the details of all employees
3.Display the name and job for all employees
4.Display name and salary for all employees
5.Display employee number and total salary for each employee
6.Display employee name and annual salary for all employees
7.Display the names of all employees who are working in department number 10
8.Display the names of all employees working as clerks and drawing a salary more than 3000
9.Display employee number and names for employees who earn commission
10.Display names of employees who do not earn any commission
11.Display the names of employees who are working as clerk , salesman or analyst and drawing a salary
more than 3000
12.Display the names of employees who are working in the company for the past 5 years
13.Display the list of employees who have joined the company before 30 th june 90 or after 31 st dec 90
14.Display current date
15.Display the list of users in your database (using log table)
16.Display the names of all tables from the current user
17.Display the name of the current user
18.Display the names of employees working in department number 10 or 20 or 40 or employees working
as clerks , salesman or analyst
19.Display the names of employees whose name starts with alphabet S
20.Display employee name from employees whose name ends with alphabet S
21.Display the names of employees whose names have sencond alphabet A in their names
22.Display the names of employees whose name is exactly five characters in length
23.Display the names of employees who are not working as managers
24.Display the names of employees who are not working as SALESMAN or CLERK or ANALYST
25.Display all rows from emp table. The system should wait after every screen full of information
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
104) Display employee name ,job,deptname,his manager name ,his grade and make an
under department wise?
105) List out all the employee names ,job,salary,grade and deptname for every one in a company except
'CLERK' . Sort on salary display the highest salary?
106) Display employee name,job abd his manager .Display also employees who are with out
managers?
107) Display Top 5 employee of a Company?
108) Display the names of those employees who are getting the highest salary?
109) Display those employees whose salary is equal to average of maximum and minimum?
110) Select count of employees in each department where count >3?
111) Display dname where atleast three are working and display only deptname?
112) Display name of those managers name whose salary is more than average salary of
Company?
113) Display those managers name whose salary is more than average salary salary of his
employees?
114) Display employee name,sal,comm and netpay for those employees whose netpay is
greater than or equal to any other employee salary of the company?
115) Display those employees whose salary is less than his manager but more than salary of
other managers?
116) Display all employees names with total sal of company with each employee name?
117) Find the last 5(least) employees of company?
118) Find out the number of employees whose salary is greater than their managers salary?
119) Display the manager who are not working under president but they are working under
any other manager?
120) Delete those department where no employee working?
121) Delete those records from emp table whose deptno not available in dept table?
122) Display those enames whose salary is out of grade available in salgrade table?
Ans: select empno,sal from tvsemp where sal<(select min(LOSAL) from salgrade )
OR sal>(select max(hisal) from salgrade)
123) Display employee name,sal,comm and whose netpay is greater than any othere in the
company?
124) Display name of those employees who are going to retire 31-Dec-99 if maximum job period
is 30 years?
125) Display those employees whose salary is odd value?
126) Display those employees whose salary contains atleast 3 digits?
127) Display those employees who joined in the company in the month of Dec?
128) Display those employees whose name contains A?
129) Display those employees whose deptno is available in salary?
130) Display those employees whose first 2 characters from hiredate - last 2 characters sal?
131) Display those employeess whose 10% of salary is equal to the year joining?
132) Display those employees who are working in sales or research?
133) Display the grade of jones?
134) Display those employees who joined the company before 15th of the month?
135) Display those employees who has joined before 15th of the month?
136) Delete those records where no of employees in particular department is less than 3?
137A) Delete those employeewho joined the company 10 years back from today?
137B) Display the deptname the number of characters of which is equal to no of employee
in any other department?
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
Naresh it Technologies
ORACLE 12c
Naresh it Technologies