SQL Material
SQL Material
SQL Material
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
can contain all the data about an individual employee, but one group of users may be authorised to view
Page 1
ORACLE 12c
only payroll data, while others are allowed access to only work history and medical data. The DBMS can
maintain the integrity of the database by not allowing more than one user to update the same record at
the same time. Organisations may use one kind of DBMS for daily transaction processing and then move
the detail onto another computer that uses another DBMS better suited for analysis.
Advantages :-
Disadvantages:-
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
• 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.
Page 3
ORACLE 12c
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 :-
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.
Page 4
ORACLE 12c
In RDBMS :-
ORACLE 11g
Oracle provides a flexible RDBMS called Oracle11g. Using its features, you can store and manage
data with all the advantages of a relational structure plus PL/SQL, an engine that provides you with the
ability to store and execute program units. Oracle11g also supports Java and XML.
The Oracle server offers the options of retrieving data based on optimization techniques. It includes
security features that control how a database is accessed and used. Other features include consistency
and protection of data through locking mechanisms.
Oracle versions :-
Table partitioning
Page 5
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
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:
Page 6
ORACLE 12c
SQL*Plus :-
SQL*Plus is an Oracle tool that recognizes and submits SQL statements to the Oracle server for execution
and contains its own command language.
• Execute SQL statements to retrieve, modify, add, and remove data from the database
• Format, perform calculations on, store, and print query results in the form of reports
• Create script files to store SQL statements for repetitive use in the future
SQL vs SQL*PLUS :-
Page 7
ORACLE 12c
Schema :- a user in oracle db is called schema and objects created by user are called schema objects
Logging In to sql*plus :-
➔ Open sql*plus
➔ Enter username & password
➔ Enter host string
Datatypes :-
When you create a table or cluster, you must specify a datatype for each of its columns. When you create a
procedure or stored function, you must specify a datatype for each of its arguments. These datatypes
define the domain of values that each column can contain or each argument can have. For example, DATE
columns cannot accept the value February 29 (except for a leap year) or the values 2 or ’SHOE’. Each value
subsequently placed in a column assumes the column’s datatype. For example, if you insert ’01-JAN-98’
Page 8
ORACLE 12c
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 9
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.
RAW(size) :-
Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value.
LONG RAW :-
ROWID :-
Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for
values returned by the ROWID pseudocolumn.
UROWID [(size)] :-
Hexadecimal string representing the logical address of a row of an index-organized table. The optional size
is the size of a column of type UROWID. The maximum size and default is 4000 bytes.
CLOB :-
A character large object containing single-byte characters. Both fixed-width and variable-width character
sets are supported, both using the CHAR database character set. Maximum size is 4 gigabytes.
NCLOB :-
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.
OCA question :-
Page 10
ORACLE 12c
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?
OPERATORS IN ORACLE :-
ARTHMETIC OPERATORS :-
+ - * /
Operator precedence:-
RELATIONAL OPERATORS :-
Used for comparision , different relational operators supported by oracle
Operator Description
Page 11
ORACLE 12c
LOGICAL OPERATORS :-
SPECIAL OPERATORS :-
||
BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT
Creating table :-
➔ Standard tables
➔ Partitioned tables
➔ Clustered tables
➔ Index organized tables
➔ External tables
➔ Global temporary tables
Standard Table :-
Syntax:-
Page 12
ORACLE 12c
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 :-
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
Page 13
ORACLE 12c
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 14
ORACLE 12c
Virtual Columns :-
When queried, virtual columns appear to be normal table columns, but their values are derived rather than
being stored on disc. The syntax for defining a virtual column is listed below.
If the datatype is omitted, it is determined based on the result of the expression. The GENERATED ALWAYS
and VIRTUAL keywords are provided for clarity only.
Example :-
SQL>CREATE TABLE employees (
id NUMBER,
first_name VARCHAR2(10),
last_name VARCHAR2(10),
salary NUMBER(9,2),
comm NUMBER(3),
hra NUMBER GENERATED ALWAYS AS (SAL*0.3) VIRTUAL,
CONSTRAINT employees_pk PRIMARY KEY (id)
);
Querying the table shows the inserted data plus the derived hra
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.
Page 15
ORACLE 12c
Limitations :-
→A virtual column can only be of scalar datatype . It can’t be a user defined type, LOB or RAW.
→All columns mentioned as part of the virtual column expression should belong to the same table.
→No DMLs are allowed on the virtual columns.
→The virtual column expression can’t reference any other virtual column.
→Virtual columns can only be created on ordinary tables. They can’t be created on index-organized,
external, object, cluster or temporary tables.
SQL statements may contain literal single quotes in them, such as when a possessive form of a noun is used
(e.g., 'Robert's Bike'). Prior to Oracle 10g, the literal quotes had to be double quoted to make it clear to the
SQL or PL/SQL engine that they were literal (e.g., Robert''s Bike). This can make the code much less
readable and can cause errors that be difficult to find.
Oracle 10g introduces a solution to this problem in the form of user-specified quote character assignment.
With this new functionality, the ' symbol can be replaced by just about any single- or multibyte delimiter or
the character pairs [ ], { }, ( ), or < >.
The delimiter is defined by using the quote operator, q, followed by a quote and then the assigned
replacement quote delimiter to be used. Here is an example that uses the bracket pair ([ ]) as quote
delimiters:
SQL> INSERT INTO record VALUES (q'[Robert's book is good isn't it?]');
SQL> SELECT * FROM record
WHERE the_value=q'XRobert's book is good isn't it?X';
THE_VALUE
--------------------------------------------------
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.
Page 16
ORACLE 12c
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 :-
Page 17
ORACLE 12c
NOTE:-
Arthmetic Expressions :-
an arithmetic expression contain column names,constant numeric values and athmetic operator.
Example :-
Operator precedence :-
Page 18
ORACLE 12c
The above example displays the ename, sal, and annual sal of employees. It calculates the annual sal as 12
multiplied by the monthly salary, plus a one-time bonus of 100. Notice that multiplication is performed
before addition.
Concatenation Operator:-
Example :-
Literals in ORACLE:-
A Literal is a Constant
Types of Literals :-
• String constant
• Numeric constant
• Date constant
Example :-
SQL>SELECT ename || ‘ EARNS ‘|| sal*12 ||’ PER YEAR’ FROM emp;
OCA question :-
Evaluate the following query:
Page 19
ORACLE 12c
Declaring Alias:-
An Alias is an another name or alternative name, aliases in Oracle are of two types.
• Column Alias
• Table Alias
Column Alias :-
Alias declared for column is called column alias.
Syntax :-
COLNAME / EXPR [AS] ALIAS
→If alias contains spaces or special characters then alias must be enclosed in “ “
Example :-
Display ename,sal,comm and in report display sal as basic and comm as bonus ?
SQL>SELECT ename,sal AS basic,comm AS bonus FROM emp;
Display ename , annual salary ?
SQL>SELECT ename,sal*12 AS “ANNUAL SALARY” FROM emp;
Display ename,sal,hra,da,tax,totsal ?
SQL>SELECT ename,sal,sal*0.3 AS hra,sal*0.2 AS da, sal*0.1 AS tax ,
sal+(sal*0.3)+(sal*0.2)-(sal*0.1) AS totsal FROM emp;
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 .
Page 20
ORACLE 12c
Clauses in ORACLE :-
➢ WHERE
➢ ORDER BY
➢ DISTINCT
➢ GROUP BY
➢ HAVING
➢ ON
➢ USING
➢ START WITH
➢ CONNECT BY
➢ WITH
➢ RETURNING
➢ FOLLOWS
➢ MODEL
You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause contains a
condition that must be met, and it directly follows the FROM clause. If the condition is true, the row
meeting the condition is returned.
syntax:
Page 21
ORACLE 12c
• Column name
• Comparison operator
• Column name, constant, or list of values
Examples :-
Display employee record whose empno=7844 ?
SQL>SELECT * FROM emp WHERE empno=7844 ;
BETWEEN operator:-
You can display rows based on a range of values using the BETWEEN operator. The range that you
specify contains a lowerlimit and an upperlimit . Values specified with the BETWEEN condition are
inclusive. You must specify the lower limit first.
Example :-
Page 22
ORACLE 12c
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’
Page 23
ORACLE 12c
Pattern consists of alphabets,digits and metacharacters. The different meta characters in ORACLE
% denotes zero or many characters.
_ denotes one character.
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?
Page 24
ORACLE 12c
IS operator :
The IS operator tests for nulls. A null value means the value is unavailable, unassigned,unknown, or
inapplicable. Therefore, you cannot test with = because a null cannot be equal or unequal to any value.
Syntax :-
IS NULL
IS NOT NULL
Example:-
Display employee records whose comm. Is null ?
Operator Precedence :-
1 Arithmetic Operator
2 Concatenation Operator
3 Comparison Operator
4 IS [NOT] NULL ,LIKE , [NOT] IN
5 [NOT] BETWEEN
6 NOT logical condition
7 AND logical condition
8 OR logical condition
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:
Page 25
ORACLE 12c
ORDER BY specifies the order in which the retrieved rows are displayed.
ASC orders the rows in ascending order ( default order)
DESC orders the rows in descending order
• Numeric values are displayed with the lowest values firs for example 1–999.
• Date values are displayed with the earliest value first for example 01-JAN-92 before 01-JAN-95.
• Character values are displayed in alphabetical order—for example, A first and Z last.
• Null values are displayed last for ascending sequences and first for descending sequences.
Examples :-
Arrange employee records in ascending order of their sal ?
Display employee records working for 10th dept and arrange the result in ascending order of their sal ?
Arrange employee records in ascending of their deptno and with in dept arrange records in descending
order of their sal ?
In ORDER BY clause we can use column name or column position , for example
In the above example records are sorted based on the fifth column in emp table.
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?
Page 26
ORACLE 12c
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?
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:-
Page 27
ORACLE 12c
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 ?
Returning Clause:-
DELETE command :-
Page 28
ORACLE 12c
Syntax:-
INSERT ALL command used to insert data into multiple tables.Using INSERT ALL command we can extract
data from one or more tables and insert data into multiple tables.
INSERT ALL
INTO <TAB1> VALUES (VALUE LIST)
INTO <TAB2> VALUES(VALUE LIST)
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 :-
Page 29
ORACLE 12c
Sales
Prodid Prodname Mon_Amt Tue_Amt Wed_Amt Thu_Amt Fri_Amt Sat_Amt
101 AIWA 2000 2500 2230 2900 3000 2100
102 AKAI 1900 2100 2130 3100 2800 2120
Now we want to add the rows from SALES table Weekly_Sales Table in the following
Structure.
To achieve the above we can give a multi table INSERT statement given below
SQL>Insert all
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Mon’,mon_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,’Tue’,tue_amt)
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
Page 30
ORACLE 12c
Example :-
Copy data from emp to emp1 , emp2 based on the following conditions
SQL>INSERT ALL
WHEN job=’CLERK’ THEN
INTO emp1 VALUES(empno,ename,sal)
WHEN job=’MANAGER’ THEN
INTO emp2 VALUES(empno,ename,sal)
SELECT empno,ename,sal FROM emp;
MERGE Statement:-
the new MERGE SQL command (sometimes referred to as "UPSERT") is a DML command that enables us to
optionally update or insert data into a target table, depending on whether matching records already exist.
In versions prior to 9i, we would have to code this scenario either in separate bulk SQL statements or in
PL/SQL.
Syntax :-
MERGE INTO <TARGETTABLE> <ALIAS>
USING <SOURCE TABLE>/QUERY <ALIAS>
ON (CONDITION)
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
Page 31
ORACLE 12c
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
Page 32
ORACLE 12c
Statement
Because no record in emp table satisfies condition 1=2 , so no record is copied to EMP12 only the
structure is copied.
ALTER command :-
ALTER command is used to modify data definition of a table.ALTER command is used to do following
operations.
➔ ADD A COLUMN(S)
➔ DROP A COLUMN(S)
➔ TO RENAME A COLUMN
➔ MODIFY A COLUMN
• INCR/DECR FIELD SIZE
• CHANGING DATATYPE
• CHANGING FROM NULL TO NOT NULL
• CHANGING FROM NOT NULL TO NULL.
➔ TO MAKE TABLE READ ONLY
Adding a Column:-
Syntax :-
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);
Page 33
ORACLE 12c
NOTE :- all columns in a table cannot be dropped , because the table should contain atleast one column.
Renaming a Column :-
Syntax:-
ALTER TABLE <tabname> RENAME COLUMN <oldname> to <newname> ;
SQL>ALTER TABLE emp RENAME COLUMN sal TO salary ;
Modifying a Column:-
Syntax :-
ALTER TABLE <TABNAME>
MODIFY(COLNAME DATATYPE(SIZE) ,-----------)
Changing Datatype:-
NOTE :-
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.
Page 34
ORACLE 12c
TRUNCATE command :-
DELETE TRUNCATE
RENAME command :-
Syntax :-
Example :-
OCA question :-
Page 35
ORACLE 12c
C. All indexes on the table will remain but they are invalidated.
D. All views and synonyms will remain but they are invalidated.
E. All data in the table are deleted but the table structure will remain.
Integrity Constraints
Integrity constraints are the rules in real life, which are to be imposed on the data. If the data is not
satisfying the constraints then it is considered as inconsistent. These rules are to be enforced on data
because of the presence of these rules in real life. These rules are called integrity constraints. Every DBMS
software must enforce integrity constraints, otherwise inconsistent data is generated.
→Unique Constraint
→Primary Constraint
Refrential Integrity :-
→A refrential integrity constraint states that the values of the foreign key value should match with values
of primary key/unique Column of another or same table. Foreign key constraint establishes relationship
between tables.
If a foreign key in one table refers primary key/unique column of the same table then it is called self
refrential Integrity.
Domain constraints:-
A domain means a set of values assigned to a column. Domain constraints are handled by
The above said constraints are implemented in oracle with the help of
→NOT NULL
→UNIQUE
→PRIMARY KEY
→CHECK
→FOREIGN KEY
The above constraints can be declared at
→Column level
→ Table level
Column level :-
Table level :-
Syntax :-
Columnname Datatype(size) NOT NULL
Example :-
SQL> CREATE TABLE emp(
Empno NUMBER(4),
Ename VARCHAR2(20) NOT NULL,
Job VARCHAR2(20) ,
Mgr NUMBER(4),
Hiredate DATE,
Sal NUMBER(7,2),
Comm NUMBER(7,2),
Deptno NUMBER(2) );
1 row created
UNIQUE constraint :-
→Columns declared with UNIQUE constraint does not accept duplicate values.
→One table can have a number of unique keys.
→By default UNIQUE columns accept null values unless declared with NOT NULL constraint
→Oracle automatically creates UNIQUE index on the column declared with UNIQUE constraint
→UNIQUE constraint can be declared at column level and table level.
Syntax :-
Example :-
Page 39
ORACLE 12c
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 40
ORACLE 12c
prodid NUMBER(4) ,
qty NUMBER(2) ,
CONSTRAINT pk_ordid_prodid PRIMARY KEY(ordid,prodid)) ;
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 41
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 :-
Page 42
ORACLE 12c
Example :-
Creating Parent table :-
SQL> CREATE TABLE dept
(deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY,
dname VARCHAR2(20) ,
loc VARCHAR2(20)) ;
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 44
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 45
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.
SQL>SELECT deptno, dname, loc FROM dept, EXCEPTIONS
Page 46
ORACLE 12c
DELETE RULES :-
Delete rules specifies how child record gets affected if parent record is deleted and these rules are
declared with foreign key declaration. Oracle supports following Delete Rules :-
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 47
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 :-
Page 48
ORACLE 12c
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 49
ORACLE 12c
(ord_no NUMBER(2),
item_no NUMBER(3),
ord_date DATE DEFAULT SYSDATE NOT NULL,
CONSTRAINT ord_pk PRIMARY KEY (ord_no, item_no));
Page 50
ORACLE 12c
Built-in Functions
functions are a very powerful feature of SQL and can be used to do the following:-
Character functions:-
These functions mainly operate on character data.
Page 51
ORACLE 12c
Syntax:- UPPER(string)
Example:-
HELLO
Syntax:- LOWER(string)
Example:-
hello
Syntax:- INITCAP(string)
Example :-
Hello Welcome
Syntax :- LENGTH(string)
Example :-
Example:-
Page 52
ORACLE 12c
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 ?
2 CUSTOMER_TABLE :-
CNAME
Rahuld dravid
Virendra sehwag
Sachin ramesh tendulkar
Page 53
ORACLE 12c
Sourav ganguly
Mahindra singh dhoni
From the above customer names display only those names that contains 3 parts ?
SQL>SELECT * FROM customer WHERE INSTR(cname,’ ‘,1,2) > 0;
Example:-
HELLO
HELLO
Example:-
HELLO
HELLO
HELLO
HELLO
Syntax :- LPAD(string1,length,string2)
Page 54
ORACLE 12c
*****hello
ENAME HIREDATE
SMITH 17-DEC-80
ALLEN 20-FEB-81
WARD 22-FEB-81
USERID
Smi17DEC80
All20FEB81
War22FEB81
Syntax:- TRANSLATE(string1,string2,string3)
Page 55
ORACLE 12c
Example:-
Syntax :- CONCAT(str1,str2)
Example :-
Example :-
Example :-
SQL>SELECT ASCII(‘A’) FROM DUAL ;
65
CHR :- returns character for a given ASCII value
Syntax :- CHR(ascii value)
Example :-
SQL>SELECT CHR(65) FROM DUAL ;
A
Date Functions:-
Example:-
Display ename,sal,hiredate and date of retirement , assume that date of retiment is 30 years after date of
join ?
Example:-
31-MAY-12
Page 57
ORACLE 12c
Syntax:- MONTHS_BETWEEN(date1,date2)
Example:-
12
Example :-
27-MAY-12
Mathematical Functions:-
Syntax:- ABS(number)
Example:-
10
SIGN :-
Syntax :- SIGN(expr)
Syntax :- POWER(M,N)
Example :-
Page 58
ORACLE 12c
Syntax :- SQRT(N)
Example:-
Syntax:- MOD(m,n)
Example:-
Example:-
10
Syntax:- FLOOR(number)
Example:-
Example:-
Page 59
ORACLE 12c
Syntax:- TRUN(m,n)
Example :-
3.45
01-JAN-2012
Conversion Functions :-
These functions are used to convert from one datatype to another datatype
→implicit conversion
→explicit conversion
Page 60
ORACLE 12c
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
Century formats :-
Year Formats :-
Page 61
ORACLE 12c
Quarter :-
Example :-
Month :-
MM Month Number 1
Example :-
Day :-
Example :-
Page 62
ORACLE 12c
Week :-
Time :-
HH hour in 12-format 12
HH24 hour in 24-format 23
MI minute 20
SS second 30
AM/PM AM/PM as appropriate
Example :-
Display sysdate as follows ?
25 january 2012 , Monday 10:00:00 AM
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.
Page 63
ORACLE 12c
OCA question :-
You need to display the date 11-oct-2007 in words as 'Eleventh of October, Two Thousand Seven'.
Which SQL statement would give the required result?
Format Description
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 :-
Page 64
ORACLE 12c
The above statement returns ORACLE error INVALID NUMBER , because 26-AUG-2012 is treated as string ,
so to do the calculation conversion is required.
Example :-
You need to insert date & time into dob column , but by default DATE datatype accepts only DATE but not
time. To insert date along with time conversion is required.
But TIMESTAMP datatype allows both date and time without conversion.
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
Page 65
ORACLE 12c
Syntax :-
DECODE(expr,value1,return expr1,
Value2, return expr2,
---------------,
[default expr])
Example :-
SQL>SELECT ename,sal,
DECODE(job, ’CLERK’,’WORKER’,
‘MANAGER’,’BOSS’,
‘PRESIDENT’,’BIG BOSS’,
‘EMPLOYEE’) AS JOB FROM emp;
SQL>UPDATE emp
SET sal = DECODE(deptno,10, DECODE(job,’CLERK’,SAL*1.1,
‘MANAGER’,SAL*1.15,
SAL*1.05) ,
20, DECODE(JOB,’CLERK’,SAL*1.15,
‘MANAGER’,SAL*1.2,
SAL*1.05) ,
SAL) ;
NVL:-
Syntax :-
NVL(expr1,expr2)
If expr1 is NULL then NVL function returns expr2 otherwise returns expr1 only.
Example :-
NVL2 :-
Syntax :-
NVL2(expr1,expr2,expr3)
Example :-
GREATEST :-
Page 67
ORACLE 12c
Syntax :- GREATEST(expr1,expr2,expr4,----)
Example :-
LEAST :-
Syntax: LEAST(expr1,expr2,expr3)
Example:-
NULLIF :-
Syntax:- NULLIF(expr1,expr2)
COALESCE:-
The Oracle COALESCE function returns the first non-NULL expression in the list. If all expressions in the list
evaluate to NULL, then the COALESCE function will return NULL. The database evaluates each expression's
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.)
Page 68
ORACLE 12c
2 Generate a report showing the total compensation paid to each employee to till date.
SQL>SELECT ename ||' joined on ' hiredate || ', the total compensation paid is '||
ROUND(ROUND(SYSDATE-hiredate)/365) *12* sal + NVL(comm,0)) “Until Date “
FROM emp;
3 Which tasks can be performed using SQL functions built into Oracle Database ? (Choose three.)
PROD_ID PROD_LIST_PRICE
123456 152525.99
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 69
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.)
Page 70
ORACLE 12c
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 :-
Page 71
ORACLE 12c
Syntax:- SUM(expr)
Example:-
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 72
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.
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
Page 73
ORACLE 12c
END ;
→result1, result2,………….., result are the returned results(one for each possible expression). If expression1
evaluates to search_expression, results is returned, and similarly for the other expressions.
Example :-
SQL>SELECT ename,sal, CASE job
WHEN ‘CLERK’ THEN ‘WORKER’
WHEN ‘MANAGER’ THEN ‘BOSS’
WHEN ‘PRESIDENT’ THEN ‘BIG BOSS’
ELSE
‘EMPLOYEE’
END AS JOB
FROM emp ;
Syntax :-
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
………………..
WHEN condition THEN result
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 :-
Page 74
ORACLE 12c
OCA question :-
PROMO_BEGIN _DATE
04-jan-00
10-jan-00
15-dec-99
18-oct-98
You want to display the number of promotions started in 1999 and 2000.
D SELECT
COUNT(DECODE(SUBSTR(TO_CHAR(promo_begin_date,'yyyy'), 8), '1999', 1, 0)) "1999",
COUNT(DECODE(SUBSTR(TO_CHAR(promo_begin_date,'yyyy'), 8),'2000', 1,0)) "2000"
FROM promotions;
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 75
ORACLE 12c
[GROUP BY group_by_expression]
[HAVING condition] [ORDER BY column];
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 76
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 77
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> /
Cross Tabulation:-
Page 78
ORACLE 12c
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;
1 101 10 20 30
Page 79
ORACLE 12c
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 80
ORACLE 12c
SQL>SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY ROLLUP(deptno,job)
ORDER BY deptno,job ;
CUBE :-
Page 81
ORACLE 12c
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 ;
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 :-
GROUP BY CUBE(deptno,job);
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 :-
Page 83
ORACLE 12c
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.
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 :-
Page 84
ORACLE 12c
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.
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 85
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.
Page 86
ORACLE 12c
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.
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
Page 87
ORACLE 12c
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) ;
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)
Page 88
ORACLE 12c
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.
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.
Page 89
ORACLE 12c
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 (+) .
CROSS JOIN :-
Example:-
TABLE TABLE
Page 90
ORACLE 12c
ORDERS DISCOUNT
ORDAMT DIS
100000 5
7
12
ANSI Style :-
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.
Page 91
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:-
Page 92
ORACLE 12c
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.
Example:-
Page 93
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
Page 94
ORACLE 12c
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.
• 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.
Page 95
ORACLE 12c
ROWNUM :-
• ROWNUM represents the sequential order in which ORACLE has retrieved the row and it will
change from query to query .
Page 96
ORACLE 12c
In the above result the ROWNUM generated for KING record is 6, So ROWNUM changes from query to
query.
We can also retrieve records based on their record number. For example to display 1 st record ?
NOTE :- Because ROWNUM is generated after retrieving record. So with ROWNUM we cannot use > , >=
operators.
ORA_ROWSCAN :-
ORA_ROWSCN returns the system change number (SCN) of the last change inside the block containing a
row. It can return the last modification for the row if the table is created with the option
ROWDEPENDENCIES (default is NOROWDEPENDENCIES). The function SCN_TO_TIMESTAMP allows you to
convert SCN to timestamp.
Page 97
ORACLE 12c
Subqueries
Subquery:-
Syntax :-
Page 99
ORACLE 12c
SQL>UPDATE emp SET sal = (SELECT MAX(sal) FROM emp) WHERE EMPNO=7369 ;
if inner query returns more than one row then it is called multi row subquery.
Syntax :-
Displaye employee records whose job equals to job of SMITH or job of BLAKE ?
Displaye employee records who are earning minimum and maximum salaries ?
Page 100
ORACLE 12c
ANY operator:-
Compares a value to each value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=.
Evaluates to FALSE if the query returns no rows.
Example:-
Example:-
Nested Queries:-
→A subquery embedded in another subquery is called NESTED QUERY.
→Queries can be nested upto 255 level.
Example :-
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)) ;
Page 101
ORACLE 12c
Example :-
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 102
ORACLE 12c
In-line Views :-
The inline view is a construct in Oracle SQL Where you can place a query in the SQL FROM clause, just as if
the query was a tablename. A common use of in-line views is to simplify complex queries by removing join
operations and converting separate queries into single query.
Syntax :-
Example :-
SQL>SELECT * FROM
(SELECT a.*, ROWNUM rn
Page 103
ORACLE 12c
SQL>SELECT * FROM
(SELECT a.*, ROWNUM rn FROM
(SELECT * FROM emp) a
WHERE ROWNUM <= 6)
WHERE rn >= 2;
SQL>SELECT d.dname,e.maxsal
FROM dept d , (SELECT deptno,MAX(sal) maxsal FROM emp
GROUP BY deptno) e
WHERE e.deptno = d.deptno ;
Subqueries can also follow SELECT clause. These subqueries returns one value per row.
Syntax :-
Example :-
EMP DEPT
14 4
Page 104
ORACLE 12c
Database Transactions
A database transaction is a group of SQL statements that perform a logical unit of work. Whose results
should be made permanent in the database as a whole or undone as a whole .
An example of a database transaction is a transfer of money from one bank account to another. One
UPDATE statement would subtract from the total amount of money from one account, and another
UPDATE would add money to the other account. Both the subtraction and the addition must be
permanently recorded in the database, otherwise, money will be lost. If there is a problem with the money
transfer, then the subtraction and addition must both be undone.
If transaction ends with COMMIT then it is called successful transaction and the operations are made
permanent.
Page 105
ORACLE 12c
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;
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.
Page 106
ORACLE 12c
Every transaction has to support following four properties called ACID properties.
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 107
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 108
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
You revoke system privileges from a user using REVOKE. The following example connects as system and
revokes the CREATE TABLE privilege from VIJAY.
Page 109
ORACLE 12c
SQL>CONNECT system/manager
Object Privileges:-
An object privilege allows a user to perform certain actions on database objects, such as executing DML
statements on tables. some of the commonly used objects privileges are shown in the table:
SQL>CONNECT SCOTT/TIGER;
SQL>GRANT SELECT, INSERT, UPDATE ON PRODUCTS TO VIJAY;
The next example grants the UPDATE privilege on the last_name and salary columns to VIJAY
You can also use the GRANT option to enable a user to grant a privilege to another user. The following
example grants the SELECT privilege on the customers table with the GRANT option to VIJAY
The SELECT ON customers privilege can then be granted to another user by VIJAY. The following example
connects as VIJAY and grants this privilege to RAJU.
SQL>CONNECT vijay/oracle11g ;
Page 110
ORACLE 12c
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.
Page 111
ORACLE 12c
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 112
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:-
Page 113
ORACLE 12c
Schema Objects
➔ TABLES
➔ SEQUENCES
➔ VIEWS
➔ MATERIALIZED VIEWS
➔ SYNONYMS
➔ TYPES
➔ INDEXES
➔ CLUSTERS
➔ PROCEDURES
➔ FUNCTIONS
➔ PACKAGE
➔ DB TRIGGER
SEQUENCE
→The SEQUENCE Values are often used for PRIMARY KEY’S and UNIQUE KEY’S.
CREATING SEQUENCES:-
Syntax:-
[INCREMENT BY n]
[START WITH n]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE]
ORDER/NORDER;
Increment By :-
Minvalue:-
Page 114
ORACLE 12c
NoMinvalue
Specifies a minimum value of 1 for an ascending sequence and –(10)^26) for a descending sequence.
Maxvalue:-
NoMaxvalue:-
Specifies a maximum value of 10^27 for an ascending sequence and -1 for a descending sequence.
Start With:-
Cycle:-
Specifies whether the sequence contains to generate values after reaching its maximum or minimum
value.
NoCycle:-
Specifies the SEQUENCE cannot general more values after the targeted limit.
Cache:-
Specifies how many values the Oracle Server Preallocates and keep in memory.
NoCache:-
If the above parameters are not specified by default 20 values are cached.
Order:-
NoOrder:-
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:-
Page 116
ORACLE 12c
MAXVALUE 10
NOCACHE
NOCYCLE;
Modifying a Sequence:-
→The ALTER command can be used to change the present status of a SEQUENCE.
Increment Value
Maximum Value
Minimum Value
Cycle Option
Cache Option
Syntax:-
Example :-
SQL>ALTER SEQUENCE SEQ1 MAXVALUE 500
→You must be the owner or have the ALTER privilege for the sequence modify it.
→Only future sequence numbers are affected by the ALTER SEQUENCE statement.
→The sequence must be dropped and re-created in order to restart the sequence at a different number.
Removing a Sequence:-
USER_SEQUENCE
ALL_SEQUENCES
DBA_SEQUENCES
Page 117
ORACLE 12c
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.)
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
Page 118
ORACLE 12c
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:-
→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
Page 119
ORACLE 12c
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 :-
→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 ;
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
Page 121
ORACLE 12c
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
Synonyms
A synonym is another name or alternative name for a table.
Synonyms are created
➔ If tablename if lengthy.
➔ To provide local transparency for remote objects.
Syntax:-
Example :-
After creating synonym , now EMPLOYEE_INFORMATION table can be accessed by using name
EMP. For Example
NOTE:- difference between synonym and table alias is , the scope of the table alias is upto that query only
but synonym can be used any query.
VIEWS vs SYNONYMS:-
VIEWS SYNONYMS
Subset of a table mirror of a table
Page 122
ORACLE 12c
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 :-
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?
Page 123
ORACLE 12c
Indexes
When looking for a particular topic in a book, you either scan the whole book, or you can use the index to
find the location. An index for a database table is similar in concept to a book index, except that database
indexes are used to find specific rows in a table.
• Table Scan
• Index Scan
Table Scan :-
In table scan oracle scans the entire table to locate the desired information.
Index Scan :-
In index scan oracle uses index to locate the place that holds the required data and then jumps to that
place to get required data. This is much faster than table scan.
• When an index is created on a table, oracle internally forms a two dimensional matrix that contains
Data extracted from the column on which index is created and Physical Address of the record
(rowid) .
• When an SQL query that has a WHERE clause based on the column on which index is fired , oracle
finds the value in index and locates the record in the table using ROWID .
TYPES OF INDEXES :-
➔ B-tree Indexes
• Simple Index
• Composite Index
• Unique Index
• Function based Index
➔ Bitmap Indexes
B-TREE INDEXES :-
When to use BTREE Indexes:-
Page 124
ORACLE 12c
Syntax:-
→A SELECT query with a WHERE clause spceicifed on column on which index is created
→A SELECT query with ORDER BY clause specified on column on which index is created
→ SELECT query is fired with WHERE clause specified on the column on which index is not defined
→ SELECT query is fired with ORDER BY clause specified on the column on which index is not defined.
Composite Index :-
Example :-
Oracle server uses above index when SELECT query with WHERE clause is based on leading column of
index is fired.
Page 125
ORACLE 12c
Example :-
Unique Index :-
UNIQUE index doesn’t allow duplicate values into the column on which INDEX is created.
Example :-
NOTE:-
PRIMARY KEY columns and UNIQUE columns are automatically indexed by ORACLE.
There are times when even though an index exists, oracle doesn’t use it and instead follows table scan.
This is usually happens when index created on a column, but the SQL query reference that column with a
function or arithmetic expression.
For example , an index is created on the City column of the Customers table and the following query is
fired to retrieve all those row who belong to MUMBAI.
Above query reference the City column along with UPPER function and hence oracle doesn’t use the index.
In addition, the database administrator must set the initialization parameter QUERY_REWRITE_ENABLED to
true (the default is false) in order to take advantage of function – based indexes.
SQL>CONNECT system/manager
Reverse Index:-
In the index leaf block , Oracle stores the index key value and ROWID.
Assume that there is an unique index on custid , suppose 3 individuals concurrently hit the database to
insert rows with customer numbers 101,102,103 then index entries are stored in same leaft block , which
causes buffer busy waits.
If the index is reverse unique index then the entries will be stored in different leaft block
Page 126
ORACLE 12c
Example :-
NOTE :-
BITMAP INDEXES :-
Example :-
Modifying an Index:-
Example :-
DROPPING INDEX :-
SYNTAX :-
Example:-
USER_INDEXES
USER_IND_COLUMNS
ALL_INDEXES
DBA_INDEXES
OCA question :-
Which statements are correct regarding indexes? (Choose all that apply.)
Page 127
ORACLE 12c
Clusters
A cluster is a data structure that improves retrieval performance. A cluster, like an index, does not affect
the logical view of the table. A cluster is a way of storing related data values together on disk. Oracle reads
data a block at a time, so storing related values together reduces the number of I/O operations needed to
retrieve related values, since a single data block will contain only related rows.
A cluster is composed of one or more tables. The cluster includes a cluster index, which stores all the
values for the corresponding cluster key. Each value in the cluster index points to a data block that contains
only rows with the same value for the cluster key.
If a cluster contains multiple tables, the tables should be joined together and the cluster index should
contain the values that form the basis of the join. Because the value of the cluster key controls the
placement of the rows that relate to the key, changing a value in that key can cause Oracle to change the
location of rows associated with that key value.
Clusters may not be appropriate for tables that regularly require full table scans, in which a query requires
the Oracle database to iterate through all the rows of the table. Because you access a cluster table through
the cluster index, which then points to a data block, full table scans on clustered tables can actually require
more I/O operations, lowering overall performance.
The following statement creates a cluster named personnel with the cluster key column department, a
cluster size of 512 bytes, and storage parameter values:
The following statement creates the cluster index on the cluster key of personnel:
After creating the cluster index, you can add tables to the index and perform DML operations on those
tables.
Page 128
ORACLE 12c
The following statements create some tables and add them to the personnel cluster created in the earlier
example:
USER_CLUSTERS
ALL_CLUSTERS
DBA_CLUSTERS
Materialized Views
→A materialized view is a database object that contains the results of a query unlike normal views that
only contains the query definition and not the results.
→Materialized views are usually a choice 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:-
Page 129
ORACLE 12c
REFRESH:-
Since the materialized view is built on underlying data that is periodically changed, specify how and when
to refresh the data in the view. The following keywords in the REFRESH clause can also be used to create a
schedule for recurring refresh operations.
FAST: - Updates only the values in the materialized view, assuming that some preconditions are met.
FORCE: - Does a FAST refresh if possible and a COMPLETE refresh if the preconditions for a FAST refresh are
not available.
ON COMMIT:- Causes a refresh to occur whenever the underlying data is changed and the changes are
committed.
START WITH DATE:- Indicates the date and interval at which the materialized view is to be refreshed
NEXT DATE:- Indicates the time and interval at which the materialized view is to be refreshed next
WITH PRIMARY KEY: - Indicates whether the materialized view is based on Primary Key
Example :-
Page 130
ORACLE 12c
USER_MVIEWS
ALL_MVIEWS
DBA_MVIEWS
Advanced Features:-
Table Partitioning
→As the number of rows in your table grows, the management and performance impacts will increase.
Backups will take longer, recoveries will take longer and queries on that will take longer.
→Administrative and performance issues can be simplified by seperating rows of a single table into
multiple parts.
→Dividing a table’s data in this manner is called partitioning the table, and table is called partitioned table
and parts are called partitions.
→Partitioning is based on particular column , the column on which table is partitioned is called partition
key.
Advantages :-
➔ The performance of queries against the table may improve.
➔ The tables may be easier to manage.
➔ Backup and recover operations may perform better.
➔ Improves availability.
a table can be partitioned in different ways
1. RANGE PARTITION
2. LIST PARTITION
3. HASH PARTITION
RANGE partition :-
Which records are assigned to which partition depends on range of the partition key.
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)
);
Page 131
ORACLE 12c
→Employee whose salaries less than 2000 all those records are assinged to partition P1.
→Employee whose salaries less than 4000 all those records are assinged to partition P2 .
→MAXVALUE is a keyword , any data that could not be stored in earlier partitions are assigned to partition
P3.
The above query displays only the records assigned to partition P1.
Managing Partitions:-
Partitions can be dropped , new partitions can be added , and two partitions can be merged.
Droping Partition:-
When partition is dropped then records assigned to that partition are also dropped.
LIST partition:-
Which record is assinged to which partition depends on value of partition key value.
HASH Partition:-
A Hash paritition determines the physical placement of data by applying hash function on partition key .
We can create subpartitions that is, paritions of partitions. You can use subpartitions to combine all types
of partitions like range partitions, hash partitions,list partitions.
Page 133
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 134
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 135
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 136
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 137
ORACLE 12c
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
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 139
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 140
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.
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.
Example :-
SQL>EXECUTE DBMS_FLASHBACK.DISABLE() ;
Page 142
ORACLE 12c
Flashback Table :-
→Oracle flashback feature allows recovering a table after drop.When a table is dropped oracle moves it to
the recyclebin rather than actually droping it.
→A Recycle Bin is logical collection of dropped objects. The contents of Recycle Bin is viewed by using
SHOW RECYCLEBIN command.
→Flashback command is introduced in ORACLE 10g , which is used to restore a table after drop.
Example :-
Page 143
ORACLE 12c
CREATE TABLE t1 (
description VARCHAR2(30)
);
ID DESCRIPTION
---------- - -----------------------------
1 DESCRIPTION only
Page 144
ORACLE 12c
3 rows selected.
In previous releases of the Oracle database, there was no direct equivalent of the AutoNumber or
Identity functionality of other database engines. Instead, this behaviour had to be implemented
using a combination of sequences and triggers. Oracle 12c introduces two alternatives to this by
providing identity columns and the ability to use sequence pseudocolumns as default values. This
article will focus on the use of identity columns.
12c database introduces the ability define an identity clause against a table column defined using a
numeric type. The syntax is show below.
GENERATED
AS IDENTITY [ ( identity_options ) ]
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.
Page 145
ORACLE 12c
description VARCHAR2(30)
);
1 row created.
SQL> INSERT INTO identity_test_tab (id, description) VALUES (NULL, 'ID=NULL and
DESCRIPTION');
ERROR at line 1:
SQL> INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and
DESCRIPTION');
INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and DESCRIPTION')
ERROR at line 1:
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');
Page 146
ORACLE 12c
ERROR at line 1:
Using BY DEFAULT ON NULL allows the identity to be used if the identity column is
referenced, but a value of NULL is specified.
description VARCHAR2(30)
);
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 147
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
Page 148
ORACLE 12c
3
4
4
5
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
Page 149
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 150
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 151
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>
Extra Information
Page 152
ORACLE 12c
• The keywords ROW and ROWS can be used interchangeably, as can the FIRST and NEXT keywords.
Pick the ones that scan best when reading the SQL like a sentence.
• If the offset is not specified it is assumed to be 0.
• Negative values for the offset, rowcount or percent are treated as 0.
• Null values for offset, rowcount or percent result in no rows being returned.
• Fractional portions of offset, rowcount or percent are truncated.
• If the offset is greater than or equal to the total number of rows in the set, no rows are returned.
• If the rowcount or percent are greater than the total number of rows after the offset, all rows are
returned.
• The row limiting clause can not be used with the FOR
UPDATE clause, CURRVAL and NEXTVAL sequence pseudocolumns or in an fast refresh materialized
view.
SQL*LOADER
SQL*LOADER utility is used to load data from other data source into Oracle. For example, if you have a
table in FOXPRO, ACCESS or SYBASE or any other third party database, you can use SQL Loader to load the
data into Oracle Tables. SQL Loader will only read the data from Flat files. So If you want to load the data
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).
SQL*LOADER overview :-
Page 153
ORACLE 12c
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 we have a fixed length format file containing employees data, as shown below, and wants to load
this data into an Oracle table.
Page 154
ORACLE 12c
Steps :-
1. First Open the file in a text editor and count the length of fields, for example in our fixed length file,
employee number is from 1st position to 4th position, employee name is from 6th position to 15th
position, Job name is from 17th position to 25th position. Similarly other columns are also located.
2. Create a table in Oracle, by any name, but should match columns specified in fixed length file. In our
case give the following command to create the table.
$vi empfix.ctl
LOAD DATA
INFILE '/u01/oracle/fix.dat'
INTO TABLE emp
( empno POSITION(01:04) INTEGER EXTERNAL,
name POSITION(06:15) CHAR,
job POSITION(17:25) CHAR,
mgr POSITION(27:30) INTEGER EXTERNAL,
sal POSITION(32:39) DECIMAL EXTERNAL,
comm POSITION(41:48) DECIMAL EXTERNAL,
deptno POSITION(50:51) INTEGER EXTERNAL)
Page 155
ORACLE 12c
External Tables
The external tables feature is a complement to existing SQL*Loader functionality. It enables you to access
data in external sources as if it were in a table in the database. Prior to Oracle Database 10g, external
tables were read-only. However, as of Oracle Database 10g, external tables can also be written to.
External tables are created using the SQL CREATE TABLE...ORGANIZATION EXTERNAL statement. When
you create an external table, you specify the following attributes:
TYPE :- specifies the type of external table. The two available types are the ORACLE_LOADER type and the
ORACLE_DATAPUMP type.
ORACLE_LOADER :- access driver is the default. It can perform only data loads, and the data must come
from text datafiles. Loads from external tables to internal tables are done by reading from the external
tables' text-only datafiles.
ORACLE_DATAPUMP :- access driver can perform both loads and unloads. The data must come from
binary dump files. Loads to internal tables from external tables are done by fetching from the binary dump
files. Unloads from internal tables to external tables are done by populating the external tables' binary
dump files.
DEFAULT DIRECTORY :- specifies the default location of files that are read or written by external tables.
The location is specified with a directory object, not a directory path.
ACCESS PARAMETERS :- describe the external data source and implements the type of external table that
was specified. Each type of external table has its own access driver that provides access parameters unique
to that type of external table.
LOCATION:-- specifies the location of the external data. The location is specified as a list of directory
objects and filenames. If the directory object is not specified, then the default directory object is used as
the file location.
The access driver does not allow you to specify a complete specification for files. This is because the server
may have access to files that you do not, and allowing you to read this data would affect security.
Instead, you are required to specify directory objects as the locations from which to read files and write
files. A directory object maps a name to a directory name on the file system. For example, the following
statement creates a directory object named ext_tab_dir that is mapped to a directory located at
/usr/apps/datafiles.
Directory objects can be created by DBAs or by any user with the CREATE ANY DIRECTORY privilege.
After a directory is created, the user creating the directory object needs to grant READ and WRITE
privileges on the directory to other users.
Page 156
ORACLE 12c
Step 4 :- Load the data from the external table emp_load into the table emp:
Step 5 :- Perform the following select operation to verify that the information in the .dat file was loaded
into the emp table:
Page 157
ORACLE 12c
Analytical Functions
→Analytic Functions are commonly used to compute cumulative, moving, centered and reporting
aggregates.
→Oracle provides several analytic functions that help compute an aggregate value based on a group of
rows.
→Analytic Functions provided by Oracle open up a whole new way of looking at the data.
→It helps remove a lot of procedural code and complex code spec that would have taken a long time to
develop, to achieve the same result.
→Whatever an analytic function does, can be done by using SQL, with the help of joins and subqueries.
However, an analytic function always does it faster, when compared to native SQL.
➔ AVG
➔ CORR
➔ COVAR_POP
➔ COVAR_SAMP
➔ COUNT
➔ CUME_DIST
➔ DENSE_RANK
➔ FIRST
➔ FIRST_VALUE
➔ LAG
➔ LAST
➔ LAST_VALUE
➔ LEAD
➔ MAX
➔ MIN
➔ NTILE
➔ PERCENT_RANK
➔ PERCENTILE_CONT
➔ PERCENTILE_DISC
➔ RANK
➔ RATIO_TO_REPORT
➔ STDDEV
➔ STDDEV_POP
➔ STDDEV_SAMP
➔ SUM
➔ VAR_POP
➔ VAR_SAMP
➔ VARIANCE
Page 158
ORACLE 12c
Syntax:-
Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [<window_clause>] )
Where,
→The PARTITION BY clause logically breaks a single result set into N groups, according to the criteria set by
the partition expressions.
→The words partition and group are used synonymously here.
→The analytic functions cane be applied to each group independently.
Order By Clause:
The ORDER BY clause specifies how the data is sorted within each group [partition]. This will definitely
affects the outcome of any analytic function.
Windowing Clause:
The windowing clause allows defining a sliding or anchored window of data, on which the analytic function
will operate, within a group.
Consider the above and its result. The above returns departments and their employee count. Most
importantly it groups the records into departments. As such any non-"group by" column is not allowed in
the select clause.
Page 159
ORACLE 12c
Now consider the analytic function query and its result. Note the repeating values of DEPT_COUNT
column.This brings out the main difference between aggregate and analytic functions. Analytical function
returns aggregate data along with detailed data.
Analytic functions are computed after WHERE clause, GROUP BY and HAVING . The ORDER BY clause of
the query operates after the analytic functions. So analytic functions can only appear in the select list and
in the ORDER BY clause of the query.
In absence of any PARTITION or <window_clause> inside the OVER( ) portion, the function acts on entire
record set returned by the where clause.
ROW_NUMBER( ) :-
gives a running serial number to a partition of records. It is very useful in reporting, especially in places
where different partitions have their own serial numbers. In below ecxmple the function ROW_NUMBER( )
is used to give separate sets of running serial to employees of departments 10 and 20 based on their
HIREDATE.
SQL> SELECT empno, deptno, hiredate,ROW_NUMBER( ) OVER (PARTITION BY deptno
ORDER BY hiredate NULLS LAST) SRLNO
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, SRLNO;
Page 160
ORACLE 12c
Computes the RANK of a row in an ordered group of rows and returns rank as a number begins with 1.this
function is useful to find top-N & bottom-N records.
Example :-
NOTE :- The difference between RANK & DENSE_RANK is RANK function generates gaps but DENSE_RANK
function doesn’t generate gaps.
RANK() and DENSE_RANK() function can be used to find top-N records as follows :-
Display top 3 maximum salaries in emp table ?
The syntax of LAG is similar except that the offset for LAG goes into the previous rows.below example
Page 161
ORACLE 12c
and its result show simple usage of LAG and LEAD function.
The FIRST_VALUE analytic function picks the first record from the partition after doing the ORDER BY. The
<sql_expr> is computed on the columns of this first record and results are returned. The LAST_VALUE
function is used in similar context except that it acts on the last record of the partition.
How many days after the first hire of each department were the next employees hired?
Page 162
ORACLE 12c
SQL>SELECT empno,
deptno,
sal,
MIN(sal) KEEP (DENSE_RANK FIRST ORDER BY sal) OVER (PARTITION BY deptno) "Lowest",
MAX(sal) KEEP (DENSE_RANK LAST ORDER BY sal) OVER (PARTITION BY deptno) "Highest"
FROM emp
ORDER BY deptno, sal ;
How each employee's salary compare with the average salary of the first year hires of their
department?
Page 163
ORACLE 12c
WINDOW clause :-
Some analytic functions (AVG, COUNT, FIRST_VALUE, LAST_VALUE, MAX, MIN and SUM among the ones
we discussed) can take a window clause to further sub-partition the result and apply the analytic function.
An important feature of the windowing clause is that it is dynamic in nature.
1.UNBOUNDED PECEDING
2.CURRENT ROW
3.<sql_expr> PRECEDING or FOLLOWING.
1.UNBOUNDED FOLLOWING or
2.CURRENT ROW or
3.<sql_expr> PRECEDING or FOLLOWING.
For ROW type windows the definition is in terms of row numbers before or after the current row. So for
ROW type windows <sql_expr> must evaluate to a positive integer.
For RANGE type windows the definition is in terms of values before or after the current ORDER. We will
take this up in details latter.
The ROW or RANGE window cannot appear together in one OVER clause. The window clause is defined in
terms of the current row. But may or may not include the current row. The start point of the window and
the end point of the window can finish before the current row or after the current row. Only start point
cannot come after the end point of the window. In case any point of the window is undefined the default is
UNBOUNDED PRECEDING for <start_expr> and UNBOUNDED FOLLOWING for <end_expr>.
If the end point is the current row, syntax only in terms of the start point can be can be
[ROW or RANGE] [<start_expr> PRECEDING or UNBOUNDED PRECEDING ]
[ROW or RANGE] CURRENT ROW is also allowed but this is redundant. In this case the function behaves as
a single-row function and acts only on the current row.
Page 164
ORACLE 12c
For analytic functions with ROW type windows, the general syntax is:
Function( ) OVER (PARTITIN BY <expr1> ORDER BY <expr2,..> ROWS BETWEEN <start_expr> AND
<end_expr>)
or
Function( ) OVER (PARTITON BY <expr1> ORDER BY <expr2,..> ROWS [<start_expr> PRECEDING or
UNBOUNDED PRECEDING]
For ROW type windows the windowing clause is in terms of record numbers.
SQL>SELECT ename,sal,
SUM(sal) over (order by sal ROWS UNBOUNDED PRECEDING)
as cum_sal
from emp ;
Data Pump
Oracle Data Pump (expdp and impdp) introduced in Oracle Database 10g is faster and more flexible
alternative to the "exp" and "imp" utilities used in previous Oracle versions. In addition to basic import and
export functionality data pump provides a PL/SQL API and support for external tables.
To use DATA PUMP utilities first we must create a directory object . The directory object is only a pointer to
a physical directory, creating it does not actually create the physical directory on the file system.
SQL>CONN SYSTEM/MANAGER
SQL>CREATE OR REPLACE DIRECTORY test_dir AS 'C:\WINDOWS’
SQL>GRANT READ, WRITE ON DIRECTORY test_dir TO scott;
Existing directories can be queried using the ALL_DIRECTORIES view.
Table Exports/Imports :-
Page 165
ORACLE 12c
The TABLES parameter is used to specify the tables that are to be exported. The following is an example of
the table export and import syntax and command should be executed at command prompt.
Database Exports/Imports
The FULL parameter indicates that a complete database export is required. The following is an example of
the full database export and import syntax.
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 166
ORACLE 12c
Regular Expressions
The database provides a set of SQL functions that allow you to search and manipulate strings using regular
expressions. You can use these functions on any datatype that holds character data such as CHAR, NCHAR,
CLOB, NCLOB, NVARCHAR2, and VARCHAR2
A regular expression must be enclosed or wrapped between single quotes. Doing so, ensures that the
entire expression is interpreted by the SQL function and can improve the readability of your code.
This function searches a character column for a pattern. Use this function in the WHERE clause of a query
to return rows matching the regular expression you specify.
REGEXP_REPLACE
Page 167
ORACLE 12c
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 168
ORACLE 12c
a.c
This expression matches all of the following sequences:
abc
adc
a1c
a&c
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:-
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
Page 169
ORACLE 12c
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:
Page 170
ORACLE 12c
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):
[^abc]
Page 171
ORACLE 12c
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
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.
Page 172
ORACLE 12c
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
Page 173
ORACLE 12c
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.
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;
Page 174
ORACLE 12c
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).
Queries to practice:-
1.Display the dept information from department table
2.Display the details of all employees
3.Display the name and job for all employees
4.Display name and salary for all employees
5.Display employee number and total salary for each employee
6.Display employee name and annual salary for all employees
7.Display the names of all employees who are working in department number 10
8.Display the names of all employees working as clerks and drawing a salary more than 3000
9.Display employee number and names for employees who earn commission
10.Display names of employees who do not earn any commission
11.Display the names of employees who are working as clerk , salesman or analyst and drawing a salary
more than 3000
12.Display the names of employees who are working in the company for the past 5 years
Page 175
ORACLE 12c
13.Display the list of employees who have joined the company before 30 th june 90 or after 31 st dec 90
14.Display current date
15.Display the list of users in your database (using log table)
16.Display the names of all tables from the current user
17.Display the name of the current user
18.Display the names of employees working in department number 10 or 20 or 40 or employees working
as clerks , salesman or analyst
19.Display the names of employees whose name starts with alphabet S
20.Display employee name from employees whose name ends with alphabet S
21.Display the names of employees whose names have sencond alphabet A in their names
22.Display the names of employees whose name is exactly five characters in length
23.Display the names of employees who are not working as managers
24.Display the names of employees who are not working as SALESMAN or CLERK or ANALYST
25.Display all rows from emp table. The system should wait after every screen full of information
26.Display the total number of employees working in the company
27.Display the total salary and total commission to all employees
28.Display the maximum salary from emp table
29.Display the minimum salary from emp table
30.Display the average salary from emp table
31.Display the maximum salary being paid to CLERK
32.Display the maximum salary being paid in dept no 20
33.Display the minimum salary being paid to any SALESMAN
34.Display the average salary drawn by managers
35.Display the total salary drawn by analyst working in dept no 40
36.Display the names of employees in order of salary i.e. the name of the employee earning lowest salary
shoud appear first
37.Display the names of employees in descending order of salary
38.Display the details from emp table in order of emp name
39.Display empnno,ename,deptno and sal. Sort the output first based on name and within name by deptno
and witdhin deptno by sal;
40) Display the name of employees along with their annual salary(sal*12). the name of the employee
earning highest annual salary should appear first?
41) Display name,salary,Hra,pf,da,TotalSalary for each employee.
The out put should be in the order of total salary ,hra 15% of salary ,DA 10% of salary .pf 5% salary Total
Salary
will be (salary+hra+da)-pf?
42) Display Department numbers and total number of employees working in each Department?
43) Display the various jobs and total number of employees working in each job group?
44)Display department numbers and Total Salary for each Department?
45)Display department numbers and Maximum Salary from each Department?
46)Display various jobs and Total Salary for each job?
47)Display each job along with min of salary being paid in each job group?
48) Display the department Number with more than three employees in each department?
49) Display various jobs along with total salary for each of the job where total salary is greater than 40000?
50) Display the various jobs along with total number of employees in each job.The
output should contain only those jobs with more than three employees?
51) Display the name of employees who earn Highest Salary?
Page 176
ORACLE 12c
52) Display the employee Number and name for employee working as clerk and earning highest salary
among the clerks?
53) Display the names of salesman who earns a salary more than the Highest Salary of the clerk?
54) Display the names of clerks who earn a salary more than the lowest Salary of any salesman?
55) Display the names of employees who earn a salary more than that of jones or that of salary greater
than that of scott?
56) Display the names of employees who earn Highest salary in their respective departments?
57) Display the names of employees who earn Highest salaries in their respective job Groups?
58) Display employee names who are working in Accounting department?
59) Display the employee names who are Working in Chicago?
60) Display the job groups having Total Salary greater than the maximum salary for Managers?
61) Display the names of employees from department number 10 with salary greater than that of ANY
employee working in other departments?
62) Display the names of employees from department number 10 with salary greater than that of ALL
employee working in other departments?
63) Display the names of employees in Upper Case?
64) Display the names of employees in Lower Case?
65) Display the names of employees in Proper case?
Q:66) Find the length of your name using Appropriate Function?
67) Display the length of all the employee names?
68) Display the name of employee Concatinate with Employee Number?
69) Use appropriate function and extract 3 characters starting from 2 characters from the following string
'Oracle' i.e., the out put should be ac?
70) Find the first occurance of character a from the following string Computer Maintenance Corporation?
71) Replace every occurance of alphabet A with B in the string .Alliens (Use Translate function)?
72) Display the information from the employee table . where ever job Manager is found it should be
displayed as Boss?
73) Display empno,ename,deptno from tvsemp table. Instead of display department numbers display the
related department name(Use decode function)?
74) Display your Age in Days?
75) Display your Age in Months?
76) Display current date as 15th August Friday Nineteen Nienty Seven?
77) Display the following output for each row from tvsemp table?
78) Scott has joined the company on 13th August ninteen ninety?
79) Find the nearest Saturday after Current date?
80) Display the current time?
81) Display the date three months before the Current date?
82) Display the common jobs from department number 10 and 20?
83) Display the jobs found in department 10 and 20 Eliminate duplicate jobs?
84) Display the jobs which are unique to department 10?
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?
Page 177
ORACLE 12c
Page 178
ORACLE 12c
Page 179
ORACLE 12c
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
188.Display those employee whose joining date is available in deptno
189.Display those employee name as follows A ALLEN, B BLAKE
190.List out the employees ename,sal,pf from emp
191.Display RSPS from emp without using updating,inserting
192.Create table emp with only one column empno
193.Add this column to emp table ename varchar2(20)
194.OOPSI i forget to give the primary key constraint. Add it now
Page 180
ORACLE 12c
Page 181