SQL
SQL
SQL
Data :-
Data are raw material and unorganized facts that need to be processed.
Example:-
Students fill an admission form when they get admission in college. The form consists of raw facts about
the students. These raw facts are student's name, father name, address etc. The purpose of collecting this
data is to maintain the records of the students during their study period in the college.
Information :-
When data are processed , organized, structured or presented in a given context so as to make them
useful.They are called information.
Example:-
Data collected from census is used to generate different type of information. The government can use it to
determine the literacy rate in the country. Government can use the information in important decision to
improve literacy rate.
Database :-
A Database is a collection of meaningful data that is stored in computer system. For example an employee
data would generally contain Employee Name, Salary, Address and Job. Such data of multiple employees
placed together in one place is termed as Database. DB is represented by using cylinder.
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
Page 1
ORACLE 12c
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 :-
Improved data access to users through use of host and query languages
Disadvantages:-
Development of DBMS :-
Page 2
ORACLE 12c
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
Attributes
Page 3
ORACLE 12c
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 :-
Page 4
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.
Page 5
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 :-
Page 6
ORACLE 12c
Table partitioning
Page 7
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
Page 8
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
Page 9
ORACLE 12c
• Create script files to store SQL statements for repetitive use in the future
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
Page 10
ORACLE 12c
columns cannot accept the value February 29 (except for a leap year) or the values 2 or ’SHOE’. Each value
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.
Page 11
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.
Page 12
ORACLE 12c
NCLOB :-
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?
Page 13
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
Page 14
ORACLE 12c
PIVOT
Creating table :-
Standard tables
Partitioned tables
Clustered tables
Index organized tables
External tables
Global temporary tables
Standard Table :-
Syntax:-
Example:-
SQL> CREATE TABLE emp
(empno NUMBER(4), ename VARCHAR2(20),
job VARCHAR2(10), hiredate DATE,
sal NUMBER(6,2), comm NUMBER(6,2) ,
deptno NUMBER(2));
OCA Question :-
Page 15
ORACLE 12c
Syntax:-
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 :-
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:-
Page 17
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.
Page 18
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)
);
Page 19
ORACLE 12c
Querying the table shows the inserted data plus the derived hra
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:
Page 20
ORACLE 12c
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
--------------------------------------------------
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 :-
• A FROM clause, which specifies the table containing the columns listed in the SELECT
clause
Selecting All Columns :-
SQL>SELECT * FROM dept;
Page 22
ORACLE 12c
NOTE:-
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 :-
Page 23
ORACLE 12c
String constant
Numeric constant
Date constant
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 ?
Page 24
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
Page 25
ORACLE 12c
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:
• 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 ;
Page 26
ORACLE 12c
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 :-
Example :-
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.
Page 28
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
Page 29
ORACLE 12c
8 OR logical condition
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
Page 30
ORACLE 12c
In the above example records are sorted based on the fifth column in emp table.
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?
Page 31
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 ?
Page 32
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.
Page 33
ORACLE 12c
INSERT ALL
INTO <TAB1> VALUES (VALUE LIST)
INTO <TAB2> VALUES(VALUE LIST)
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.
Page 34
ORACLE 12c
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)
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
Page 35
ORACLE 12c
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)
WHEN MATCHED THEN
UPDATE COMMAND
WHEN NOT MATCHED THEN
INSERT COMMAND
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
Example :-
Create table emp11 from table emp ?
After executing above command a new table is created called emp11 from the result of SELECT
Statement
Page 37
ORACLE 12c
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 :-
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 :-
Page 38
ORACLE 12c
Changing Datatype:-
NOTE :-
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 :-
Page 39
ORACLE 12c
DELETE TRUNCATE
RENAME command :-
Syntax :-
Example :-
OCA question :-
Integrity Constraints
Page 40
ORACLE 12c
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.
Unique Constraint
Primary Constraint
Refrential Integrity :-
Page 41
ORACLE 12c
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 :-
Page 42
ORACLE 12c
Syntax :-
Columnname Datatype(size) NOT NULL
Example :-
SQL> CREATE TABLE emp(
Empno NUMBER(4),
Ename VARCHAR2(20) NOT NULL,
Job VARCHAR2(20) ,
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 :-
Page 43
ORACLE 12c
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) );
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.
Page 45
ORACLE 12c
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 :-
Table :- Managers
Page 46
ORACLE 12c
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.
Syntax :-
Colname datatype(size) [constraint <name>] REFERENCES tabname(colname)
Page 47
ORACLE 12c
Example :-
Creating Parent table :-
SQL> CREATE TABLE dept
(deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY,
dname VARCHAR2(20) ,
loc VARCHAR2(20)) ;
Page 48
ORACLE 12c
DEFAULT Option :-
If column Declared with DEFAULT option then oracle inserts DEFAULT value when value is not provided.
DEFAULT option prevents entering NULL values into the column.
Example :-
Constraints can be also be added to an existing table with the help of ALTER command
Syntax :-
Note:- primary key constraint cannot be added to a column that already contains duplicates or NULL values.
Page 49
ORACLE 12c
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 :-
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> ;
Page 50
ORACLE 12c
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 :-
SQL>ALTER TABLE dept ENABLE PRIMARY KEY
EXCEPTIONS INTO EXCEPTIONS;
If duplicate primary key values exist in the dept table and the name of the PRIMARY KEY constraint on dept
is sys_c00610, then the following query will display those exceptions:
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.
Page 51
ORACLE 12c
Example :-
When the clause deferrable is used, the behavior of constraint can be changed in the transaction by using
the set constraint command.
Page 52
ORACLE 12c
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.
Page 53
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
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.
Page 55
ORACLE 12c
Page 56
ORACLE 12c
Built-in Functions
functions are a very powerful feature of SQL and can be used to do the following:-
Page 57
ORACLE 12c
Character functions:-
These functions mainly operate on character data.
Syntax:- UPPER(string)
Example:-
HELLO
Syntax:- LOWER(string)
Example:-
hello
Syntax:- INITCAP(string)
Example :-
Hello Welcome
Syntax :- LENGTH(string)
Example :-
Page 58
ORACLE 12c
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’ ?
Example:-
Scenario :-
1 CUSTOMER TABLE :-
sachin@gmail.com
sourav@gmail.com
from the above email addresses display only the first part ?
Page 59
ORACLE 12c
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
Page 60
ORACLE 12c
HELLO
Syntax :- LPAD(string1,length,string2)
*****hello
ENAME HIREDATE
SMITH 17-DEC-80
ALLEN 20-FEB-81
WARD 22-FEB-81
USERID
Smi17DEC80
All20FEB81
War22FEB81
Page 61
ORACLE 12c
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
Page 62
ORACLE 12c
Date Functions:-
Example:-
Display ename,sal,hiredate and date of retirement , assume that date of retiment is 30 years after date of
join ?
Page 63
ORACLE 12c
Example:-
31-MAY-12
Syntax:- MONTHS_BETWEEN(date1,date2)
Example:-
12
Example :-
27-MAY-12
Mathematical Functions:-
Syntax:- ABS(number)
Example:-
10
SIGN :-
Syntax :- SIGN(expr)
Page 64
ORACLE 12c
Syntax :- POWER(M,N)
Example :-
Syntax :- SQRT(N)
Example:-
Syntax:- MOD(m,n)
Example:-
Example:-
10
Syntax:- FLOOR(number)
Page 65
ORACLE 12c
Example:-
Example:-
Syntax:- TRUN(m,n)
Example :-
3.45
Page 66
ORACLE 12c
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
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
Page 67
ORACLE 12c
Century formats :-
Year Formats :-
Example :-
Page 68
ORACLE 12c
Quarter :-
Example :-
Month :-
MM Month Number 1
Example :-
Day :-
Example :-
Week :-
Page 69
ORACLE 12c
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
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?
Page 70
ORACLE 12c
Format Description
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.
Page 71
ORACLE 12c
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.
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])
Page 72
ORACLE 12c
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,
Page 73
ORACLE 12c
‘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 :-
NVL2 :-
Syntax :-
NVL2(expr1,expr2,expr3)
Example :-
GREATEST :-
Syntax :- GREATEST(expr1,expr2,expr4,----)
Example :-
Page 74
ORACLE 12c
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
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.
Page 75
ORACLE 12c
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
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?
Page 76
ORACLE 12c
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'.
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 :-
MIN:-
Syntax :- MIN(EXPR)
Example:-
SUM :-
Syntax:- SUM(expr)
Example:-
Page 78
ORACLE 12c
Scenario :-
? ? ?
AVG :-
Returns avg value of a given expression.
Syntax:- AVG(expr)
Example:-
COUNT :-
Syntax :- COUNT(expr)
Example:-
COUNT(*):-
Returns no of records
Example :-
? ? ?
Page 79
ORACLE 12c
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.
0 E. A SELECT statement using the COUNT function with a DISTINCT keyword cannot have a WHERE
clause.
CASE Statement :-
Simple case.
Searched case .
Syntax :-
CASE search_expression
WHEN expression1 THEN result1
WHEN expression2 THEN result2
…………………….
WHEN expression THEN result
ELSE default_result
END ;
Page 80
ORACLE 12c
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
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 :-
Page 81
ORACLE 12c
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;
GROUP BY clause:-
You can use GROUP BY clause to divide the rows in a table into smaller groups. You can then use the group
functions to return summary information for each group.
Syntax :-
Page 82
ORACLE 12c
Guidelines :-
only GROUP BY columns and AGGREGATE functions should appear in SELECT list other than these
two if any column appears then oracle returns error.
Using WHERE clause, you can exclude rows before dividing them into groups.
By default, rows are sorted by ascending order of the columns included in the GROUP BY list. You
can override this by using the ORDER BY clause.
Examples :-
SQL>SELECT
EXTRACT(YEAR FROM hiredate) AS YEAR, COUNT(*) AS EMPS
FROM emp
GROUP BY EXTRACT(YEAR FROM hiredate);
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.
Page 83
ORACLE 12c
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
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.
Example :-
SQL>SELECT deptno,sum(sal) FROM emp
WHERE deptno IN (10,20)
GROUP BY deptno
HAVING SUM(sal) > 10000 ;
Page 84
ORACLE 12c
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> /
Page 85
ORACLE 12c
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);
SQL>INSERT INTO unpivot_test VALUES (4, 104, 100, NULL, NULL, NULL);
SQL>COMMIT;
Page 86
ORACLE 12c
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)
Page 87
ORACLE 12c
SQL>SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY ROLLUP(deptno,job)
ORDER BY deptno,job ;
Page 88
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 ;
Page 89
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 :-
Page 90
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.
Page 91
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?
Page 92
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.
Page 93
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;
Page 94
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.
Page 95
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) ;
Page 96
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.
Page 97
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 (+) .
Page 98
ORACLE 12c
CROSS JOIN :-
Example:-
TABLE TABLE
ORDERS DISCOUNT
ORDAMT DIS
100000 5
7
12
ANSI Style :-
Page 99
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 :-
1 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.
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.
2 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.
It gives details of product IDs 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'.
Page 100
ORACLE 12c
Page 101
ORACLE 12c
Set Operators :-
UNION
UNION ALL
INTERSECT
MINUS
Syntax :-
SELECT statement 1
UNION / UNION ALL / INTERSECT / MINUS
SELECT statement 2 ;
Rules :-
1 No of columns returned by first query must be equal to no of columns returned by second query
2 Corrosponding columns datatype type must be same.
UNION:-
UNION operator combines data returned by two SELECT statement.
eliminates duplicates.
Sorts result.
Example :-
UNION ALL:-
UNION ALL
SELECT job FROM emp WHERE deptno=20 ;
UNION vs JOIN :-
UNION JOIN
Union combines data Join relates data
Union is performed on similar structures Join can be performed also be performed on
dissimilar structures also
Scenario :-
EMP1 EMP2
DEPT:-
Display all employee list along with department names and locations ?
INTERSECT:-
INTERSECT operator returns common values from the result of two SELECT statements.
Example:-
MINUS:-
MINUS operator returns values present in the result of first SELECT statement and not present in the result
of second SELECT statement.
Page 103
ORACLE 12c
Example:-
OCA questions :-
Which ORDER BY clauses are valid for the above query? (Choose all that apply.)
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"
Page 104
ORACLE 12c
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
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.
Page 105
ORACLE 12c
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 .
Page 106
ORACLE 12c
How do I write a query to get the Top-N salaries from the employee table?
How can I add unique, sequential numbers to an existing table?
How can I differentiate between two completely identical rows?
How can I find a faster way to retrieve a row?
How can I find the last row processed in a big batch?
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 1 st record ?
Page 107
ORACLE 12c
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.
Page 108
ORACLE 12c
Subqueries
Subquery:-
Syntax :-
Page 109
ORACLE 12c
SQL>UPDATE emp SET sal = (SELECT MAX(sal) FROM emp) WHERE EMPNO=7369 ;
Page 110
ORACLE 12c
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:-
Page 111
ORACLE 12c
WHERE SAL > ANY ( SELECT sal FROM emp WHERE job = 'SALESMAN');
ALL operator :-
Compares a value to every value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=.
evaluates to TRUE if the query returns no rows.
Example:-
Nested Queries:-
A subquery embedded in another subquery is called NESTED QUERY.
Queries can be nested upto 255 level.
Example :-
Display employee name earning second maximum salary ?
SQL>SELECT ename FROM emp
WHERE sal = (SELECT MAX(sal) FROM EMP
WHERE sal < (SELECT MAX(sal) FROM emp)) ;
Example :-
Page 112
ORACLE 12c
Example :-
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.
Page 113
ORACLE 12c
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.
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.
Page 114
ORACLE 12c
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;
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 :-
Page 115
ORACLE 12c
Example :-
SQL>SELECT * FROM
(SELECT a.*, ROWNUM rn
FROM (enter your query here) a
WHERE ROWNUM <= :MAX_ROW)
WHERE rn >= :MIN_ROW;
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.
Page 116
ORACLE 12c
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 (
SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno)
SELECT e.ename AS employee_name,
dc.dept_count AS emp_dept_count
FROM emp e,
dept_count dc
WHERE e.deptno = dc.deptno;
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;
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 :-
Page 118
ORACLE 12c
Example :-
EMP DEPT
14 4
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.
Page 119
ORACLE 12c
You disconnect from the database. If you exist SQL*Plus normally, by entering the EXIT command, a
COMMIT is automatically performed for you. If SQL*Plus terminates abnormally- for example, if the
computer on which SQL*Plus was running were to crash- a ROLLBACK is automatically performed.
You perform a DML statement that fails, in which case a ROLLBACK is automatically performed for that
individual DML statement.
Example :-
SQL>INSERT transaction starts
SQL>UPDATE
SQL>COMMIT ; transaction ends;
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.
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;
Page 120
ORACLE 12c
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.
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
Page 121
ORACLE 12c
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:
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;
Page 122
ORACLE 12c
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.
Page 123
ORACLE 12c
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.
OCA question:-
When does a transaction complete? (Choose all that apply.)
Page 124
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:
Page 125
ORACLE 12c
SQL>CONNECT system/manager
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 :-
Page 126
ORACLE 12c
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
Page 127
ORACLE 12c
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
Page 128
ORACLE 12c
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.
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:
Page 130
ORACLE 12c
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.
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:-
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:-
Page 132
ORACLE 12c
[INCREMENT BY n]
[START WITH n]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE]
ORDER/NORDER;
Increment By :-
Minvalue:-
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:-
Page 133
ORACLE 12c
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:-
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:-
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
Page 135
ORACLE 12c
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’;
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.)
Page 136
ORACLE 12c
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
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:-
Page 137
ORACLE 12c
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.
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 :-
Page 138
ORACLE 12c
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.
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 ;
Query contains
AGGREGATE functions
DISTINCT clause
GROUP BY clause
HAVING clause
Sub-queries
Constants
Strings or Values Expressions
UNION,INTERSECT,MINUS operators.
Example 1 :-
SQL>CREATE VIEW V3
AS
SELECT E.empno,E.ename,E.sal,D.dname,D.loc
FROM emp E JOIN dept D
USING(deptno) ;
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;
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 :-
1. Which two statements are true regarding views? (Choose two.)
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
Page 140
ORACLE 12c
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;
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
Page 141
ORACLE 12c
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
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 :-
Page 142
ORACLE 12c
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?
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.
Page 143
ORACLE 12c
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:-
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
Page 144
ORACLE 12c
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.
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.
Page 145
ORACLE 12c
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
Example :-
NOTE :-
BITMAP INDEXES :-
Example :-
Page 146
ORACLE 12c
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.)
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
Page 147
ORACLE 12c
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.
The following statements create some tables and add them to the personnel cluster created in the earlier
example:
Page 148
ORACLE 12c
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 when creating summary tables on aggregate of a table’s data.
A materialized view can query tables, view’s and other materialized views.
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:-
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.
Page 149
ORACLE 12c
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 :-
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.
Page 150
ORACLE 12c
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.
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.
Page 151
ORACLE 12c
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.
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 .
sal NUMBER(7,2) ,
deptno NUMBER(2)
)
PARTITION BY HASH(deptno)
PARTITIONS 4;
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.
Page 153
ORACLE 12c
NO
Oracle Objects :-
Oracle object types are user-defined types that make it possible to model real-world entities.
New object types can be created from any built-in database types and any previously created object types,
object references, and collection types. Metadata for user-defined types is stored in a schema that is
available to SQL, PL/SQL, Java.
Page 154
ORACLE 12c
Object types and related object-oriented features such as variable-length arrays and nested tables provide
higher-level ways to organize and access data in the database. Underneath the object layer, data is still
stored in columns and tables, but you are able to work with the data in terms of the real-world entities,
such as customers and purchase orders, that make the data meaningful. Instead of thinking in terms of
columns and tables when you query the database, you can simply select a customer.
Internally, statements about objects are still basically statements about relational tables and columns, and
you can continue to work with relational data types and store data in relational tables as before. But now
you have the option to take advantage of object-oriented features too. You can begin to use object-oriented
features while continuing to work with most of your data relationally, or you can go over to an object-
oriented approach entirely. For instance, you can define some object data types and store the objects in
columns in relational tables, which enables you to extend the system built-in types with user-defined ones.
You can also create object views of existing relational data to represent and access this data according to an
object model. Or you can store object data in object tables, where each row is an object.
Advantages of Objects:-
In general, the object-type model is similar to the class mechanism found in C++ and Java. Like classes,
objects make it easier to model complex, real-world business entities and logic, and the reusability of
objects makes it possible to develop database applications faster and more efficiently. By natively
supporting object types in the database, Oracle enables application developers to directly access the data
structures used by their applications. No mapping layer is required between client-side objects and the
relational database columns and tables that contain the data.
Database tables contain only data. Objects can include the ability to perform operations that are likely to be
needed on that data. Thus a purchase order object might include a method to sum the cost of all the items
purchased. Or a customer object might have methods to return the customer's buying history and payment
pattern. An application can simply call the methods to retrieve the information.
Page 155
ORACLE 12c
Object types and their methods are stored with the data in the database, so they are available for any
application to use. Developers can benefit from work that is already done and do not need to re-create
similar structures in every application.
You can fetch and manipulate a set of related objects as a single unit. A single request to fetch an object
from the server can retrieve other objects that are connected to it. For example, when you select a
customer object and get the customer's name, phone, and the multiple parts of his address in a single
round-trip between the client and the server. When you reference a column of a SQL object type, you
retrieve the whole object.
Syntax :-
Creating Table :-
After creating user defined datatype then it can be used as a datatype for any column in any table.
SQL>CREATE TABLE customer
(cid NUMBER(2) ,
cname VARCHAR2(20) ,
caddr ADDR);
Page 156
ORACLE 12c
Methods :-
You can also defined methods that apply to datatype ,and by applying those datatypes to table , you can
apply those methods to the data in those tables.
Before creating the body for a method , you must name the method within the datatype declaration.
Type Declaration :-
Page 157
ORACLE 12c
now want to implement object-relational concepts in your application without rebuilding and re-creating
the entire application , to do this oracle provides object views as a means for defining objects used by
existing relational tables.
Example :-
SQL>CREATE TABLE customer(
customer_id NUMBER PRIMARY KEY,
cname VARCHAR2(20),
street VARCHAR2(20),
city VARCHAR2(20),
state CHAR(2),
zip NUMBER);
if you want to create another table or application that stores information about people and addresses, you
may choose to create ADDRESS_TY and PERSON_TY object types and you want to apply these types to
CUSTOMER table
Now create an object view based on the CUSTOMER table using the object types you have defined.
Now you can insert the data into CUSTOMER table via CUSTOMER_OV as follows
Page 158
ORACLE 12c
Example :-
NESTED TABLE :-
Whereas varying array have a limited number of entries , a Second type called NESTED TABLE has no limit
on the number Of entries per row. A nested table as its name implies a table within a table.It is a table that
is represented as a column within in another table.
Example :-
SQL>SELECT hno,street,city,state FROM THE (SELECT CADDR FROM cust WHERE cid=1)
Page 159
ORACLE 12c
SQL>DELETE FROM THE (SELECT caddr FROM customer WHERE cid=1) WHERE hno=’100A’ ;
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 :-
Page 160
ORACLE 12c
Example :-
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.
Page 161
ORACLE 12c
FROM dept D, (SELECT level emplevel, LPAD(' ',2*level-2)||ename ename, empno, mgr, deptno
FROM emp
CONNECT BY PRIOR empno = mgr
START WITH ename=’KING’) E
WHERE E.deptno = D.deptno ;
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.
Page 162
ORACLE 12c
Flashbacking Data :-
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.
Page 163
ORACLE 12c
Example :-
Page 164
ORACLE 12c
CREATE TABLE t1 (
description VARCHAR2(30)
);
ID DESCRIPTION
---------- - -----------------------------
1 DESCRIPTION only
3 rows selected.
Page 165
ORACLE 12c
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 ) ]
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.
Page 166
ORACLE 12c
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:
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:
Page 167
ORACLE 12c
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)
);
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
Page 168
ORACLE 12c
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.
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
Page 169
ORACLE 12c
5
6
VAL
----------
6
7
7
8
8
9
9
10
10
20 rows selected.
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
Page 170
ORACLE 12c
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
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>
Page 171
ORACLE 12c
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
4
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>
Page 172
ORACLE 12c
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>
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>
Page 173
ORACLE 12c
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.
Null values for offset, rowcount or percent result in no rows being returned.
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
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.
Is character set aware (you can specify the character set of the data).
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).
Page 174
ORACLE 12c
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.
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.
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.
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>
Page 176
ORACLE 12c
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
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
Page 177
ORACLE 12c
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.
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
Page 178
ORACLE 12c
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)
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,
Page 179
ORACLE 12c
$sqlldr userid=scott/tiger
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
Page 180
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.
Page 181
ORACLE 12c
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.
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:
Page 182
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
Page 183
ORACLE 12c
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
RANK
RATIO_TO_REPORT
STDDEV
STDDEV_POP
STDDEV_SAMP
SUM
VAR_POP
VAR_SAMP
VARIANCE
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.
Page 184
ORACLE 12c
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.
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
Page 185
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 ?
Page 186
ORACLE 12c
The syntax of LAG is similar except that the offset for LAG goes into the previous rows.below example
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?
Page 187
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 ;
Page 188
ORACLE 12c
How each employee's salary compare with the average salary of the first year hires of their
department?
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.
Page 189
ORACLE 12c
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.
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 ;
Page 190
ORACLE 12c
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:-
Page 191
ORACLE 12c
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:
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
Page 192
ORACLE 12c
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.
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.
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.
Page 194
ORACLE 12c
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.
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.
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’
Page 196
ORACLE 12c
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.
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.
Page 197
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.
Page 198
ORACLE 12c
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
^ Beginning of Line Anchor
$ End of Line Anchor
[:class:] POSIX Character Class
[.element.] POSIX Collating Sequence
[=character=] POSIX Character Equivalence Class
Page 199
ORACLE 12c
As mentioned earlier, regular expressions are constructed using metacharacters and literals.
Metacharacters that operate on a single literal, such as '+' and '?' can also operate on a sequence of literals
or on a whole expression. To do so, you use the grouping operator to enclose the sequence or
subexpression.
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
adc
abbc
Zero or More—Star:-
Page 200
ORACLE 12c
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:
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):
used to specify characters that you do not want to match. Characters that are not in the non-matching
character list are returned as a match. For example, to exclude the characters 'a', 'b', and 'c' from your
search results, use the following regular expression:
[^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:
(abc)?def
This expression matches strings 'abcdef' and 'def' in the following strings:
abcdefghi
defghi
Page 203
ORACLE 12c
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
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:-
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.
Page 205
ORACLE 12c
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).
XML
Page 206
ORACLE 12c
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>
Output :-
<Date>1994-06-07</Date>
Page 207
ORACLE 12c
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>
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>
Page 208
ORACLE 12c
<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 :-
Output :-
<Emp><Ename>SMITH</Ename><Salary>800</Salary><Department>20</Department></Emp>
<Emp><Ename>JONES</Ename><Salary>2975</Salary><Department>20</Department></Emp>
Page 209
ORACLE 12c
<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’)));
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
Page 210
ORACLE 12c
85) Display the details of those employees who do not have any person working under him?
86) Display the details of those employees who are in sales department and grade is 3?
87) Display thoes who are not managers?
88) Display those employees whose name contains not less than 4 characters?
89) Display those department whose name start with"S" while location name ends with "K"?
90) Display those employees whose manager name is Jones?
91) Display those employees whose salary is more than 3000 after giving 20% increment?
92) Display all employees with their department names?
93) Display ename who are working in sales department?
94) Display employee name,dept name,salary,and commission for those sal in between 2000
to 5000 while location is Chicago?
95) Display those employees whose salary is greater than his managers salary?
96) Display those employees who are working in the same dept where his manager is work?
97) Display those employees who are not working under any Manager?
98) Display the grade and employees name for the deptno 10 or 30 but grade is not 4 while
joined the company before 31-DEC-82?
99) Update the salary of each employee by 10% increment who are not eligible for commission?
100) Delete those employees who joined the company before 31-Dec-82 while their department Location is
New York or Chicago?
101) Display employee name ,job,deptname,loc for all who are working as manager?
102) Display those employees whose manager name is jones and also display their manager
name?
103) Display name and salary of ford if his salary is equal to hisal of his grade?
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?
Page 213
ORACLE 12c
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?
138) Display the deptname where no employee is working?
139) Display those employees who are working as manager?
140) Count th number of employees who are working as managers (Using set opetrator)?
141) Display the name of the dept those employees who joined the company on the same date?
142) Display those employees whose grade is equal to any number of sal but not equal to first number of
sal?
143) Count the no of employees working as manager using set operation?
144) Display the name of employees who joined the company on the same date?
145) Display the manager who is having maximum number of employees working under him?
146) List out the employee name and salary increased by 15% and express as whole number of Dollars?
147) Produce the output of the emptable "EMPLOYEE_AND JOB" for ename and job ?
148) Lust of employees with hiredate in the format of 'June 4 1988'?
149) print list of employees displaying 'Just salary' if more than 1500 if exactly 1500
display 'on taget' if less than 1500 display below 1500?
150) Which query to calculate the length of time any employee has been with the company
151) Given a string of the format 'nn/nn' . Verify that the first and last 2 characters are numbers .And that
the middle character is '/' Print the expressions 'Yes' IF valid 'NO' of not valid . Use the following values to
test your solution'12/54',01/1a,'99/98'?
152) Employes hire on OR Before 15th of any month are paid on the last friday of that month
those hired after 15th are paid the last friday of th following month .print a list of employees .their hiredate
and first pay date sort those who se salary contains first
digit of their deptno?
153) Display those managers who are getting less than his employees salary?
154) Print the details of employees who are subordinates to BLAKE?
151.Display those who working as manager using co related sub query
Page 214
ORACLE 12c
152.Display those employees whose manager name is JONES and also with his manager name
153.Define variable representing the expressions used to calculate on employees total annual
renumaration
154.Use the variable in a statement which finds all employees who can earn 30000 a year or more
155.Find out how many managers are there with out listing them
156.Find out the avg sal and avg total remuneration for each job type remember salesman earn
commission
157.Check whether all employees number are indeed unique
158.List out the lowest paid employees working for each manager, exclude any groups where minsal is less
than
1000 sort the output by sal
159.List ename,job,annual sal,depno,dname and grade who earn 30000 per year and who are not clerks
160.Find out th job that was falled in the first half of 1983 and the same job that was falled during the
same period on 1984
161.Find out the all employees who joined the company before their manager
162.List out the all employees by name and number along with their manager's name and number also
display
'NO MANAGER' who has no manager
163.Find out the employees who earned the highest sal in each job typed sort in descending sal order
164.Find out the employees who earned the min sal for their job in ascending order
165.Find out the most recently hired employees in each dept order by hire date
166.Display ename,sal and deptno for each employee who earn a sal greater than the avg of their
department order by deptno
167.Display the department where there are no employees
168.Display the dept no with highest annual remuneration bill as compensation
169.In which year did most people join the company. Display the year and number of employees
170.Display avg sal figure for the dept
171.Write a query of display against the row of the most recently hierd employee.display ename hire date
and column max date showing
172.Display employees who can earn more than lowest sal in dept no 30
173.Find employees who can earn more than every employees in dept no 30
174.select dept name and deptno and sum of sal
175.Find out avg sal and avg total remainders for each job type
176.Find all dept's which have more than 3 employees
177.If the pay day is next Friday after 15th and 30th of every month. What is the next pay day from
their hire date for employee in emp table
178.If an employee is taken by you today in your organization and is a policy in your company to have a
review after 9 months the joined date (and of 1st of next month after 9 months) how many days from today
your employee has to wait for a review
179.Display employee name and his sal whose sal is greater than highest avg of deptno
180.Display the 10 th record of emp table (without using rowid)
181.Display the half of the enames in upper case and remaining lower case
182.Display the 10th record of emp table without using group by and rowid
183.Delete the 10th record of emp table
184.Create a copy of emp table
185.select ename if ename exists more than once
186.Display all enames in reverse order
187.Display those employee whose joining of month and grade is equal
Page 215
ORACLE 12c
Page 216