You are on page 1of 164

Understanding SQL using ORACLE Database Introducing SQL

Introducing SQL
SCOPE
1.1 Introducing Fundamentals oI SQL
1.1.1 Data Types in Oracle 10g
1.1.1.1 CHAR Data Type
1.1.1.2 VARCHAR2 Data Type
1.1.1.3 NUMBER Data Type
1.1.1.4 Date Data Type
1.1.2 Operators and Literals in Oracle 10g
1.1.2.1 Concatenation Operator
1.1.2.2 Operator Precedence
1.1.2.3 Literals
1.2 Introducing Tables
1.2.1 Creating a Table Irom existing Table
1.2.2 SpeciIying DeIault Values Ior Columns
1.2.3 SpeciIying Comments
1.3 ModiIying Tables
1.3.1 Add Column
1.3.2 Drop Column
1.3.3 ModiIying Column
1.3.4 Rename Table
1.3.5 Drop Table
Copyright 2006, Tata Consultancy Services Limited (TCS). 1
Understanding SQL using ORACLE Database Introducing SQL
1.1 Introducing Fundamentals of SQL
Organizations generate, maintain, and require large amount oI data to perIorm day-to-day
operations. For example, an organization has 1000 employees in its manuIacturing plant.
The organization needs to maintain data related to the employees, such as employee
name, age, department, and shiIt. To perIorm basic operations, such as searching the
department oI an employee whose name is Smith can be a tedious task. Moreover,
consider a situation where an organization has many employees with the name Smith. In
these circumstances, it is diIIicult and time consuming to perIorm operations, such as
searching, moving, comparing, or modiIying records. To overcome these problems data
can be stored in a database, such as Oracle 10g. A database is an application, which
stores data in the Iorm oI rows and columns, as illustrated in Iigure 1.1.
Emp_id Emp_name Age Designation Department Salary
1 John 28 Team Leader Assembling 20k
2 Smith 25 Project Manager QA 30K
Figure1.1
Employee Table
The rows and columns oI a database constitute a table. Every column is called a field and
every row is called a record.
To insert data in the database, retrieve data Irom the database, or Ior managing the
database a Structured Query Language (SQL) is used. SQL is a programming language
that provides several commands to perIorm these operations on a database. For example,
listing 1.1 shows the query that is used to retrieve all the records in the employee table:
Select * from employee;
Listing 1.1
Sample SQL Statement
Oracle10g provides a tool, SQL*Plus to execute SQL statements. In addition, SQL*Plus
enables you to perIorm certain tasks easily. These tasks include:
Connect to a database located on the local server machine or a database located on
a diIIerent machine over a network
Create, edit, and retrieve SQL statements
Copy data Irom one database to another
Format the result oI SQL statement into reports
Administer the database
Send messages to users and accept inputs Irom those users
Copyright 2006, Tata Consultancy Services Limited (TCS). 2
Record Field
Understanding SQL using ORACLE Database Introducing SQL
1.1.1 Data Types in Oracle 10g
To store data in Oracle 10g, you need to create a table. For this, the data type Ior each
column oI the table needs to be speciIied. Based on the requirement, you can speciIy any
oI the commonly used data types, which include:
CHAR(si:e)
VARCHAR2(si:e)
NUMBER(p,s)
DATE
1.1.1.1 CHAR Data Type
Is used to store alphanumeric values. The deIault size oI this data type is 1 byte and
maximum allowed is 2000 bytes. In addition, while using CHAR data type, when you
insert a value less than the value speciIied in the size parameter, Oracle 10g Iills the
remaining size by inserting blank spaces. For example, you have speciIied the size Ior the
empname column oI the employee table, as shown:
empname char(10);
When you insert a value Smith Ior this column. Oracle 10g stores it in the manner, as
shown:
Smith `
However, when you insert a value more than the value speciIied in the size parameter,
Oracle 10g returns an error message.
1.1.1.2 VARCHAR2 Data Type
Is also used to store alphanumeric values. However, there is no deIault size oI this data
type and you must speciIy a value Ior the size parameter oI this data type. In addition, the
varchar2 data type can store a maximum oI 4000 bytes.
The diIIerence between char and varchar2 data types is the separate comparison rule Ior
trailing spaces. The char data type ignores trailing spaces. However, the varchar2 data
type treats a value with trailing spaces as higher than a same value with no trailing
spaces. This is illustrated in the given example:
CHAR data type: Smith` Smith `
VARCHAR2 data type: Smith` Smith `
1.1.1.3 NUMBER Data Type
Is used to store negative and positive integers, Iixed-point numbers, and Iloating-point
numbers with a precision p and scale s. The precision p, or the number oI digits ranges
Irom 1 to 38. The scale s, or the number oI digits aIter decimal point ranges Irom 84 to
127. However, the precision and scale values are optional. II the precision and scale
Copyright 2006, Tata Consultancy Services Limited (TCS). 3
Understanding SQL using ORACLE Database Introducing SQL
values are not speciIied, Oracle 10g assumes the maximum range Ior both the values.
Table 1.1 lists common precision and scale examples:
Data Type Value Inserted Value Stored Explanation
NUMBER 123.45678 123.45678 No values are speciIied
Ior precision and scale
parameters. ThereIore,
complete value is stored.
NUMBER(5,2) 123.45678 123.46 The value speciIied Ior
the scale parameter is 2.
ThereIore, the decimal
part oI the value inserted
is rounded to two digits.
Number(4,2) 123.45678 Error The speciIied data type
can include integers
value in the range oI 99
to 99. This is because the
value oI precision is 4
and scale is 2. This
indicates 4-22 digit
values can only be stored
in the precision
parameter.
Number(4,2) 1234546 Error The precision value is
larger than the value
speciIied.
Number(4) 1234.5678 1235 The decimal part
rounded oII to the next
integer.
Number(4, -2) 1234.5678 1200 The precision value
rounded oII to the
negative value speciIied
in the scale parameter.
Copyright 2006, Tata Consultancy Services Limited (TCS). 4
Understanding SQL using ORACLE Database Introducing SQL
1.1.1.4 Date Data Type
Is used to store date and time inIormation. The advantage oI using this data type is that
several date and time Iunctions, such as SYSDATE can be applied easily on this data
type.
Tip: Use SYSDATE Iunction to insert the system date in a column.
The Date data tvpe consumes a storage space of seven bvtes.
1.1.2 Operators and Literals in Oracle 10g
Operators are applied to individual data items to obtain a result. In Oracle 10g, operators
are represented by symbols or keywords. For example, the multiplication operator is
represented by an asterisk (*). In Oracle 10g, operators are classiIied in the two
categories, which include:
Unary Operators: This type oI operators has only one operand. For example, 1
and 2. Typically, a unary operator has operator~ operand~ Iormat.
Binary Operators: This type oI operators operate on two operands. For example, 2
* 5. They have operand~ operator~ operand~ Iormat.

1.1.2.1 Concatenation Operator
Is used to combine two character strings, and the result oI concatenation is another
character string. In addition, two vertical bars, ,, are used as the concatenation operator.
The given example illustrates the use oI concatenation operator:
Project Manager ` ,, Smith` results in Project Manager Smith`
1.1.2.2 Operator Precedence
When multiple operators are used in the same expression, Oracle 10g evaluates them in
their order oI precedence. As a result, operators with higher precedence are evaluated
beIore the operators with lower precedence. Operators with equal precedence are
evaluated leIt to right within an expression. Table 1.2 lists the operator precedence Irom
low to high.
Copyright 2006, Tata Consultancy Services Limited (TCS). 5
Understanding SQL using ORACLE Database Introducing SQL
Precedence Operator Rationale
1 , - Unary operators, negation
2 *, / Multiplication, division
3 , -, ,, Addition, subtraction,
concatenation
You can use parenthesis to override the order oI precedence. Oracle 10g evaluates the
expressions in the innermost parenthesis beIore evaluating the expressions outside it. For
example, 23*4 14 and (23)*4 20.
The Set operators, such as UNION, UNION ALL, INTERSECT, and MINUS
have equal precedence.
1.1.2.3 Literals
These are used to represent Iixed data values. There are Iour types oI literals:
Text: SpeciIies a text or character literal, this literal should be enclosed in single
quotation marks. A text literal can have a maximum length oI 4000 bytes. Certain
valid text literals include HELLO`, It`s raining in Texas`, and `26-JAN-05`.
Integer: SpeciIies an integer value up to 38 digits. Certain valid integer literals
include 0, -45, and 50.
Number: Includes digits, digits with decimals, and scientiIic notation. Certain
valid number literals include 55, 24.85, and 20E-10.
Interval: SpeciIies a period oI time, which can be in terms oI years and months or
in terms oI days and seconds.
1.2 Introducing Tables
Table is a database object used to store data. Every data or inIormation that you want to
store in Oracle 10g is stored in a table. In Iact, the inIormation required by Oracle 10g to
manage itselI is also stored in a series oI tables known as, data dictionary. You can
consider data dictionary as tables that store inIormation about tables, such as location and
type oI data.
A table consists oI columns; in Oracle 10g each column name within a table should be
unique. However, you can speciIy same data type Ior several columns oI a table. To
create a table in Oracle 10g, you Iirst need to open Oracle SQL*Plus window. To open
the Oracle SQL *PLUS window:
1. Select StartProgramsOracle-OraHome10gApplication Development
SQL Plus to open the Log On dialog box, as shown in Iigure 1.2.
Copyright 2006, Tata Consultancy Services Limited (TCS). 6
Understanding SQL using ORACLE Database Introducing SQL

Figure1.2
Log On Dialog Box
2. Enter the user name and password provided to you, or enter scott as username and
tiger as password.
3. Click the OK button to connect to Oracle 10g, as shown in Iigure 1.3.
Figure 1.3
Oracle SQL `Plus Window
On the SQL prompt, write the code displayed in Iigure 1.4 to create a table,
Commodities.

Copyright 2006, Tata Consultancy Services Limited (TCS). 7
Understanding SQL using ORACLE Database Introducing SQL
Figure 1.4
Commodities Table
Tip: You should provide descriptive table name and column names, which can be up to
30 characters.
You can include dollar sign, underscore, and pound svmbol in table and column
names.
In addition, to obtain a list oI all the columns oI a table along with inIormation, such as
data type and size oI columns you can use the Describe command. The syntax oI using
this command is Describetable name~, as shown in Iigure 1.5.
Copyright 2006, Tata Consultancy Services Limited (TCS). 8
Understanding SQL using ORACLE Database Introducing SQL
Figure 1.5
Describe Command
1.2.1 Creating a Table from an Existing Table
There might be situations where you want to create a table having same columns and data
types oI an existing table. For example, you wan to create a table Employees having the
same characteristics and data as the existing Emp table. To accomplish this task, you can
write the query shown in Iigure 1.6.
Copyright 2006, Tata Consultancy Services Limited (TCS). 9
Understanding SQL using ORACLE Database Introducing SQL
Figure 1.6
Creating a Table from an Existing Table
1.2.2 Specifying Default Values for Columns
Oracle 10g enables you to speciIy deIault values Ior columns. The deIault value is
inserted automatically when the user does not speciIy value Ior the column. You can use
the code shown in Iigure 1.7 to create a table Customers with the deIault value oI
custcountry column as USA.
Copyright 2006, Tata Consultancy Services Limited (TCS). 10
Query to create a table
Employees having the
same characteristics oI an
existing table Emp.
VeriIying
Understanding SQL using ORACLE Database Introducing SQL
Figure 1.7
Specifying Default Value for a Column
1.2.3 Specifying Comments
You can speciIy comment on a table or column Ior Iuture reIerence by using the
Comment statement. You can use the code shown in Iigure 1.8 to speciIy comments Ior
table Customers and column custcountry:
Copyright 2006, Tata Consultancy Services Limited (TCS). 11
Understanding SQL using ORACLE Database Introducing SQL
Figure 1.8
Specifying Comments
To delete the comment speciIied Ior column custcountry, write the code shown in Iigure
1.9.
Figure 1.9
Deleting Comments
1.3 Modifying Tables
You might need to modiIy an existing table due to several reasons. For example, you
want to add a column Telno in the Customers table Ior including telephone number oI
the customers. Similarly, you might need to perIorm the several tasks on tables to meet
your requirements. These tasks include:
Copyright 2006, Tata Consultancy Services Limited (TCS). 12
Understanding SQL using ORACLE Database Introducing SQL
Add Column
Drop Column
ModiIy Column
Rename Table
Drop Table
1.3.1 Add Column
The syntax oI adding column to a table is:
Alter table table name~ add column name~ data type~;
You can use the code shown in the Iigure 1.10 to add a column Telno in the Customers
table:
Figure 1.10
Adding Columns
1.3.2 Drop Column
The syntax oI deleting a column Irom a table is:
Alter table table name~ drop column column name~;
You can use the code shown in the Iigure 1.11 to delete column Telno Irom the
Customers table:
Copyright 2006, Tata Consultancy Services Limited (TCS). 13
Adding
Column
VeriIying
Understanding SQL using ORACLE Database Introducing SQL
Figure 1.11
Dropping Column
1.3.3 Modifying Column
The syntax oI modiIying a column oI an existing table is:
Alter table table name~ modiIy column new attributes~;
You can use the code shown in the Iigure 1.12 to modiIy column CustName oI the
Customers table:
Figure 1.12
Modifying Column
Copyright 2006, Tata Consultancy Services Limited (TCS). 14
Understanding SQL using ORACLE Database Introducing SQL
1.3.4 Rename Table
The syntax Ior changing the table name is:
RENAME table name~ to new table name~;
You can use the code shown in the Iigure 1.13 to rename the Customers table as Clients:
Figure 1.13
Renaming Table
Copyright 2006, Tata Consultancy Services Limited (TCS). 15
Understanding SQL using ORACLE Database Introducing SQL
1.3.5 Drop Table
The syntax Ior deleting a table is:
DROP TABLE table name~;
You can use the code shown in the Iigure 1.14 to delete the Clients table:
Figure 1.14
Deleting Table
Copyright 2006, Tata Consultancy Services Limited (TCS). 16
Understanding SQL using ORACLE Database Introducing SQL
SUMMARY
The rows and columns oI a database constitute a table. Every column is called a
field and every row is called a record.
To insert data in the database, retrieve data Irom the database, or Ior managing the
database a Structured Query Language (SQL) is used.
Oracle10g provides a tool, SQL*Plus to execute SQL statements.
In Oracle 10g, CHAR, VARCHAR2, NUMBER, and DATE are commonly used
data types.
Operators are applied to individual data items to obtain a result.
Concatenation Operator is used to combine two character strings, and the result oI
concatenation is another character string.
When multiple operators are used in the same expression, Oracle 10g evaluates
them in their order oI precedence.
Literals are used to represent Iixed data values. Text, integer, number, and interval
are Iour types oI literals.
Table is a database object used to store data. Every data or inIormation that you
want to store in Oracle 10g is stored in a table.
You can speciIy comment on a table or column Ior Iuture reIerence by using the
Comment statement.
You can also perIorm several tasks on tables to meet your speciIic requirements.
These tasks include:
o Add Column
o Drop Column
o ModiIy Column
o Rename Table
o Drop Table
Copyright 2006, Tata Consultancy Services Limited (TCS). 17
Understanding SQL using ORACLE Database Introducing SQL
SELF ASSESMENT
Q1) Fill in the blanks:
1. In Oracle 10g, every column oI a table is called a and every row is called
a .
2. To insert data in the database, retrieve data Irom the database, or Ior managing the
database a is used.
3. CHAR Data Type is used to store values.
4. The deIault size oI CHAR data type is byte and maximum allowed
is bytes.
5. VARCHAR2 Data Type is used to store values.
6. The Date data type consumes a storage space oI bytes.
Q2) State true or Ialse:
1. In number data type, the precision p, or the number oI digits ranges Irom 1 to 38.
2. In number data type, the scale s, or the number oI digits aIter decimal point ranges
Irom 84 to 100.
3. II the precision and scale values are not speciIied Ior the number data type, Oracle
10g assumes the maximum range Ior both the values.
4. In Oracle 10g, operators with higher precedence are evaluated beIore the
operators with lower precedence.
5. You can include dollar sign, underscore, and pound symbol in table and column
names.
Copyright 2006, Tata Consultancy Services Limited (TCS). 18
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Basic SQL Commands and Constraints
SCOPE
2.1 Introducing the SELECT Statement
2.1.1 Using the AS Keyword with the SELECT Statement
2.1.2 Using the DISTINCT Keyword with the SELECT Statement
2.1.3 Using the WHERE Clause with the SELECT Statement
2.1.4 Using Operators in SQL Queries
2.1.4.1 Using the Comparison Operators
2.1.4.2 Using the Logical Operators
2.1.4.3 Using the Other Operators
2.2 Introducing Constraints
2.2.1 The NOT NULL Constraint
2.2.2 The CHECK Constraint
2.2.3 The UNIQUE Constraint
2.2.4 The PRIMARY KEY Constraint
2.2.5 The FOREIGN KEY Constraint
2.2.6 Working with Constraints
Copyright 2006, Tata Consultancy Services Limited (TCS). 19
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
2.1 Introducing the SELECT Command
Oracle 9i stores data in tables. However, as a database administrator, you might need to
retrieve data stored in diIIerent tables. For example, to generate the monthly sales report,
you need to retrieve data Irom the Sales and the Employee tables.
To retrieve data Irom the tables, you need to use an SQL query. A query is a collection oI
SQL commands that is used to retrieve data Irom database tables. The main component
oI a SQL query is the SELECT statement.
The SELECT statement is the most commonly used SQL statement and is used to retrieve
data Irom the tables. II you need to retrieve data Irom speciIic or selected columns oI a
table, the syntax oI the SELECT statement is:
SELECT column name1~, column name2~,..column name N~ FROM table
name~;
Where:
Column name: ReIers to the column oI the table Irom which you need to retrieve
the required data.
Table name: ReIers to the table that consists oI the column names speciIied in the
parameters, column name1 and column name2.
For example, you need to retrieve data stored in the empid and the empname columns
oI the Employee table. The SQL query to retrieve this data will be:
SELECT emp_id, emp_name FROM Employee;
Listing 2.1
Illustration of the SELECT Statement
The query shown in Listing 2.1 will display the rows oI the columns, empid and
empname oI the Employee table, as shown in Iigure 2.1.
Figure 2.1
Result of Listing 2.1
Copyright 2006, Tata Consultancy Services Limited (TCS). 20
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Similarly, iI you need to retrieve the entire data Irom a table, the SQL query oI the
SELECT statement will be:
SELECT * FROM table name~;
This SQL query will display data oI all the columns oI the table, which is speciIied in the
parameter, table name.
For example, as a database administrator, you need to retrieve all the details related to the
employees oI your organization, such as empid, empname, empaddress,
empdesignation, and so on. For this, the SQL query will be:
SELECT * FROM Employee;
Listing 2.2
Illustration of the SELECT Statement
The SQL query shown in Listing 2.2 will display the data stored in all the columns oI the
table, Employee, as shown in Iigure 2.2.
Figure 2.2
Result of Listing 2.2
The SELECT statement is a widely used SQL statement, as it enables you to retrieve data
stored in the tables, as per your requirements. You can either retrieve entire data stored in
the tables or speciIic columns Irom the table.
Copyright 2006, Tata Consultancy Services Limited (TCS). 21
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
2.1.1 Using the AS Keyword with the SELECT Statement
For better presentation oI the data retrieved Irom the tables, you can change the display
name oI the columns. To change the display name oI the column oI a table, you need to
use the AS keyword with the SELECT statement. This display name oI the column is
called as an alias. The AS keyword enables you to display aliases Ior the column names
speciIied in the SQL query.
For example, the table Employee contains various columns, such as empid, empname,
and dept. You want to retrieve the data stored in the empid and the dept columns oI the
table. However, you want that the column heading oI the empid and the dept columns
should be displayed as Employee ID and Department. For this, the SQL query will be:
SELECT emp_id AS Employee ID, dept AS Department FROM Employee;
Listing 2.3
Illustration of the AS Keyword

The result oI the SQL query given in Listing 2.3, is shown in Iigure 2.3.
Figure 2.3
Using the AS Keyword
However, you need to remember that you need to enclose the alias oI the column in
double quotation marks, iI the alias consists oI a space. For example, alias, Minimum
Salary needs to be enclosed in double quotation marks as it consists oI a space. In
addition, be deIault, the aliases are displayed in uppercase. However, double quotation
marks preserve the case oI the alias and display it, as speciIied by the user.
2.1.2 Using the DISTINCT Keyword with the SELECT Statement
A database table can consist oI duplicate records. However, you can ensure that the result
oI the SQL query consists oI unique or distinct records. ThereIore, to eliminate duplicate
records Irom the query result, you need to use the DISTINCT keyword along with the
SELECT statement.
For example, you need to Iind the names oI all the departments in your organization,
stored in the Employee table. In addition, you want that the records oI the employees
Copyright 2006, Tata Consultancy Services Limited (TCS). 22
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
belonging to the same department should be displayed only once. The SQL query Ior this
is:
SELECT DISTINCT dept FROM Employee;
Listing 2.4
Illustration of the DISTINCT Keyword
The result oI query given in Listing 2.4 is shown in Iigure 2.4.
Figure 2.4
Using the DISTINCT Keyword
However, while using the DISTINCT keyword, you need to remember that duplicity oI
the records is veriIied on the basis oI the number oI columns speciIied aIter the
DISTINCT keyword in the query. ThereIore, iI the query speciIies two column names oI
a table aIter the DISTINCT keyword, the uniqueness oI the records will be determined on
the basis oI both the columns oI the table.

2.1.3 Using the WHERE Clause with the SELECT Statement
There might be situations when you want to retrieve only those records Irom the tables,
which IulIil a speciIic condition. For example, you want to view the records oI only those
employees, who work in the Production department. For such condition-oriented SQL
queries, you can use the WHERE clause with the SELECT statement.
The syntax oI using the WHERE clause is:
SELECT column name1~, column name2~..column name N~ FROM table
name~ WHERE condition statement~;
For example, you want to view the empid and empname oI only those employees, who
work in the Administration department. The SQL query Ior this will be:
SELECT emp_id, emp_name FROM Employee WHERE dept = `Administration';
Copyright 2006, Tata Consultancy Services Limited (TCS). 23
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Listing 2.5
Illustration of the WHERE Clause
The result oI the query shown in Listing 2.5, is shown in Iigure 2.5.
Figure 2.5
Using the WHERE Clause
2.1.4 Using Operators in SQL Queries
As the WHERE clause speciIies diIIerent condition statements, it perIorms various types
oI comparison operations, such as logical comparisons. To perIorm these comparisons
the WHERE clause uses various operators, such as logical and comparison operators.
The various operators used along with the WHERE clause are:
Comparison operators
Logical operators
Other operators
2.1.4.1 Using the Comparison Operators
Comparison operators are used to compare two values or expressions Ior providing a
Boolean result that can be True, False, or Null. The comparison operators are used with
the WHERE clause in the SQL query.
The comparison operators used in a SQL query are:
Equality: Is indicated by the equal to () sign. The equality operator generates a
true result, iI the values on both sides oI the equal to operator are equal. For
example, you need to view the records oI those employees who work in the
Production department. The SQL query Ior this, using the equality operator is:
SELECT emp_id, emp_name FROM Employee WHERE dept = `Production';
Listing 2.6
Illustration of the Equality Operator
The result oI the SQL query shown in Listing 2.6, is shown in Iigure 2.6.
Copyright 2006, Tata Consultancy Services Limited (TCS). 24
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.6
Using the Equality Operator
Inequality: Is indicated by either !, ~, or ` signs. The inequality operator
generates a true result iI values on both sides oI the inequality operator do not
match with each other. The Iollowing query displays the use oI the inequality
operator:
SELECT emp_id, emp_name FROM Employee WHERE dept <> `Production';
Listing 2.7
Illustration of the Inequality Operator
The result oI the query shown in Listing 2.7 is shown in Iigure 2.7.
Figure 2.7
Using the Inequality Operator
Less than: Is indicated by the sign. The less than operator generates a true result
iI the value on the leIt side oI the less than () operator is less than the value on
Copyright 2006, Tata Consultancy Services Limited (TCS). 25
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
the right side oI the operator. The Iollowing query displays the use oI the less than
operator:
SELECT emp_id, emp_name FROM Employee WHERE emp_id < 2100;
Listing 2.8
Illustration of the Less than Operator
The result oI the query shown in Listing 2.8, is shown in Iigure 2.8.
Figure 2.8
Using the Less Than Operator
Less than or Equal to: Is indicated by the sign. The less than or equal to
operator generates a true result iI the value on the leIt side oI the operator is less
than or equal to the value on the right side oI the operator. The Iollowing query
displays the use oI the less than or equal to operator:
SELECT emp_id, emp_name FROM Employee WHERE emp_id <=3100;
Listing 2.9
Illustration of the Less Than or Equal To Operator
The result oI the query shown in Listing 2.9, is shown in Iigure 2.9.
Copyright 2006, Tata Consultancy Services Limited (TCS). 26
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.9
Using the Less than or Equal To Operator
Greater than: Is indicated by the ~ sign. The greater than operator generates a true
result iI the value on the leIt side oI the operator is greater than the value on the
right side oI the operator. The Iollowing query displays the use oI the greater than
operator:
SELECT emp_id, emp_name FROM Employee WHERE emp_id > 3100;
Listing 2.10
Illustration of the Greater Than Operator
The result oI the query shown in Listing 2.10 is shown in Iigure 2.10.
Figure 2.10
Using the Greater than Operator
Greater than or Equal to: Is indicated by the ~ sign. The greater than or equal to
operator generates a true result iI the value on the leIt side oI the operator is
greater than or equal to the value on the right side. The Iollowing query displays
the use oI the greater than or the equal to operator:
Copyright 2006, Tata Consultancy Services Limited (TCS). 27
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
SELECT emp_id, emp_name FROM Employee WHERE emp_id >= 2100;
Listing 2.11
Illustration of the Greater Than or Equal To Operator
The result oI the query shown in Listing 2.11 is shown in Iigure 2.11.
Figure 2.11
Using the Greater Than or Equal To Operator
ANY or SOME: These operators are used to compare a value with all the values
in a given list oI values. In addition, the ANY or the SOME operators should
always be preceded with any oI the comparison operators, such as , , ~, , ~,
or ~. The Iollowing query displays the use oI the ANY operator:
SELECT emp_id, emp_name FROM Employee WHERE emp_id >=ANY (1100, 1200,
2100, 3100);
Listing 2.12
Illustration of the ANY Operator
The result oI the query shown in Listing 2.12 is shown in Iigure 2.12.
Copyright 2006, Tata Consultancy Services Limited (TCS). 28
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.12
Using the ANY Operator
ALL: This operator is used to compare a value with all the values given in a list oI
values. In addition, the ALL operator should always be preceded with any oI the
comparison operators, such as , , ~, , ~, or ~. The Iollowing query
displays the use oI the ANY operator:
SELECT emp_id, emp_name FROM Employee WHERE emp_id >= ALL (1100, 2100);
Listing 2.13
Illustration of the ALL Operator
The result oI the query shown in Listing 2.13 is shown in Iigure 2.13.
Figure 2.13
Using the ALL Operator
Copyright 2006, Tata Consultancy Services Limited (TCS). 29
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
2.1.4.2 Using the Logical Operators
Logical operators are used to generate a single result Ior the results oI two comparison
operations. In addition, you can use the logical operators to reverse the result oI a single
comparison operation.
SQL provides the Iollowing logical operators:
AND: Is used to generate a single result Ior the results oI two comparison
operations. The AND operator generates a true result iI both the operands are true.
In case, any oI the operand is Ialse, the AND operator generates a Ialse result. The
result returned by the AND operator can be shown in given table.
AND TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL
This table is called the truth table, which indicates the result generated by the AND
operator.
For example, you need to view the records oI those employees whose dept is
marketing, and whose empid is greater than 3000. The query Ior this will be:
SELECT emp_id, emp_name FROM Employee WHERE dept = `Marketing' AND
emp_id > 3000;
Listing 2.14
Illustration of the AND Operator
The result oI the query shown in Listing 2.14 is shown in Iigure 2.14.
Figure 2.14
Using the AND Operator
OR: Is also used to generate a single result Ior the results oI two comparison
operations. But, unlike the AND operator, the OR operator generates a true result,
iI either oI the operands are true. In case, both the operands are Ialse, the OR
operator generates a Ialse result, else it generates a null result. The given table is
the truth table Ior the OR operator.
Copyright 2006, Tata Consultancy Services Limited (TCS). 30
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
OR TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL
For example, you want to view the records oI all the employees, whose empid is
greater than 3000 or who work in the Administration department. The query Ior this
will be:
SELECT emp_id, emp_name FROM Employee WHERE emp_id > 3000 OR dept =
`Administration';
Listing 2.15
Illustration of the OR Operator
The result oI the query shown in Listing 2.15 is shown in Iigure 2.15.
Figure 2.15
Using the OR Operator
NOT: Is used to reverse the result generate by the comparison operation. II the
operand is Ialse, the NOT operator generates a Ialse result. In case, the operand is
true, the NOT operator generates a true result. This can be shown with the help oI
the truth table Ior the NOT operator. The given table is the truth table Ior the NOT
operator.
NOT
TRUE FALSE
FALSE TRUE
NULL NULL
Copyright 2006, Tata Consultancy Services Limited (TCS). 31
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
The Iollowing query displays the use oI the NOT operator.
SELECT emp_id, emp_name FROM Employee WHERE NOT (dept = `Production');
Listing 2.16
Illustration of the NOT Operator
The result oI the query shown in Listing 2.16 is shown in Iigure 2.16.
Figure 2.16
Using the NOT Operator
2.1.4.3 Using the Other Operators
Apart Irom the logical and comparison operators, SQL provides various other operators.
These operators are:
IN: This operator is used to test the availability oI a value in a given list oI values.
The IN operator generates a true result iI a value exists in the given list oI values.
In addition, the IN operator is equivalent to the ANY operator. The Iollowing
query displays the use oI the IN operator:
SELECT emp_id, emp_name, dept FROM Employee WHERE dept IN (`Production',
`Administration', `Marketing');
Listing 2.17
Illustration of the IN Operator
The result oI the query shown in Listing 2.17 is shown in Iigure 2.17.
Copyright 2006, Tata Consultancy Services Limited (TCS). 32
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.17
Using the IN Operator
NOT IN: This operator is used to test the non-availability oI a value in a given list
oI values. The NOT IN operator generates a true result iI the value does not exists
in the given list oI values. The Iollowing query displays the use oI the NOT
NULL operator:
SELECT emp_id, emp_name, dept FROM Employee WHERE dept NOT IN
(`Production', `Administration');
Listing 2.18
Illustration of the NOT IN Operator
The result oI the query shown in listing 2.18 is shown in Iigure 2.18.
Copyright 2006, Tata Consultancy Services Limited (TCS). 33
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.18
Using the NOT IN Operator
BETWEEN: This operator is used to test the availability oI values in a given
range oI values. This implies that the BETWEEN operator is used to test a given
range oI values. The BETWEEN operator generates a true result iI a given value
exists within the speciIied range oI values. The Iollowing query displays the use
oI the BETWEEN operator:
SELECT emp_id, emp_name FROM Employee WHERE emp_id BETWEEN 3100 AND
4500;
Listing 2.19
Illustration of the BETWEEN Operator
The result oI the query shown in listing 2.19 is shown in Iigure 2.19.
Figure 2.19
Using the BETWEEN Operator
IS NULL: This operator is used to Iind the NULL values in a table. The IS NULL
operator generates a true result iI the table contains a NULL value Ior the
speciIied column or Iield. The Iollowing query displays the use oI IS NULL
operator:
SELECT emp_id, emp_name, dept FROM Employee WHERE dept IS NULL;
Listing 2.20
Illustration of the IS NULL Operator
The result oI the query shown in listing 2.20 is shown in Iigure 2.20.
Copyright 2006, Tata Consultancy Services Limited (TCS). 34
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.20
Using the IS NULL Operator
IS NOT NULL: This operator is used to Iind the not null Ior the speciIied column
oI a table. The IS NOT NULL operator generates true result iI the speciIied
column does not contain NULL values. The Iollowing query displays the use oI
the IS NOT NULL operator:
SELECT emp_id, emp_name, dept FROM Employee WHERE dept IS NOT NULL;
Listing 2.21
Illustration of the IS NOT NULL Operator
The result oI the query shown in the listing 2.21 is shown in Iigure 2.21.
Figure 2.21
Using the IS NOT NULL Operator
LIKE: This operator is used to perIorm pattern matching, which helps in
searching a speciIic value. The LIKE operator uses the sign to perIorm the
pattern matching process, and can be used to indicate a single character or
Copyright 2006, Tata Consultancy Services Limited (TCS). 35
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
multiple characters. Apart Irom the sign, the LIKE operator uses the sign to
match and search Ior a single character. The Iollowing query displays the use oI
the LIKE operator with the sign:
SELECT emp_id, emp_name, FROM Employee WHERE dept LIKE `A%';
Listing 2.22
Illustration of the LIKE Operator
This query is used to search the names oI all those employees that start with J. The result
oI the query shown in listing 2.22 is shown in Iigure 2.22.
Figure 2.22
Using the LIKE Operator
2.2 Introducing Constraints
SQL enables you to apply constraints on the data entered in the tables. Constraints can be
deIined as restrictions applied to the tables, so that incorrect and inaccurate data can be
prevented Irom being stored in the tables. Constraints check the data speciIied by the user
at the time when the data is being entered in the tables. This ensures that the data stored
in the tables is correct and as per the data type oI each column oI the table. These
constraints are also called as Integrity constraints, as these constraints enable you to
maintain the integrity oI the data stored in the tables.
SQL provides the Iollowing deIault integrity constraints:
NOT NULL
CHECK
UNIQUE
PRIMARY KEY
FOREIGN KEY
Apart Irom the deIault constraints, you can create user-deIined constraints. Constraints
are created using the CREATE TABLE command, and can be assigned at the
column-level or at the table-level. At the column-level, the constraint is applied to a
single column only, whereas, at the table-level, the constraint can be applied to multiple
Copyright 2006, Tata Consultancy Services Limited (TCS). 36
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
columns. In addition, you need to speciIy unique and appropriate names to the
constraints.
2.2.1 The NOT NULL Constraint
This constraint is used to prevent NULL values Irom being speciIied in the columns oI
the table. As a result, this constraint is applied at the column-level and not at the
table-level. In addition, this constraint is applied at a single column at a single instance.
However, by deIault, Oracle 9i permits NULL values to be speciIied in the columns.
The syntax oI the NOT NULL constraint is:
|CONSTRAINT Constraint name~| |NOT| NULL
For example, you need to create a table that stores the details oI the products
manuIactured by your organization. You want that the table should contain the
productid Iield that should not be leIt blank by the users. The query Ior this will be:
CREATE TABLE Products
(
product_id number(5) CONSTRAINT prod_id_num NOT NULL,
product-name varchar2 (10),
product_desc varchar2 (10)
);
Listing 2.23
Illustration of the NOT NULL Constraint
The query shown in listing 2.23 creates a table, named as Products and consists oI the
three Iields. These Iields are productid, productname, and productdesc. Due to the
NOT NULL constraint that is applied to the productid column, this Iield cannot be leIt
blank while entering data into the table. You will have to speciIy the 5-digit product
identiIication number Ior each row oI data entered in the table.
In case, you do not speciIy the productid, Oracle 9i generates an error message, as
shown in Iigure 2.23.
Figure 2.23
Copyright 2006, Tata Consultancy Services Limited (TCS). 37
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Applying the NOT NULL Constraint
2.2.2 The CHECK Constraint
This constraint checks and veriIies iI the condition speciIied with the constraint is
IulIilled by the data being entered in the table. However, the condition speciIied with the
CHECK constraint should generate a boolean value, such as true or Ialse. Unlike the
NOT NULL constraint, you can speciIy the CHECK constraint at the column-level as
well as the table-level.
The syntax oI the CHECK constraint is:
|CONSTRAINT Constraint name~| CHECK (condition statement);
For example, as a database administrator, you want to ensure that the value oI the Bonus
Iield should be greater than 0.
CREATE TABLE Employee_details
(
emp_id number(5),
emp_name varchar(15),
bonus number(4),
min_salary number(4),
CONSTRAINT ck_bonus CHECK (bonus > 0)
);
Listing 2.24
Illustration of the CHECK Constraint
In this query, the constraint, ckbonus checks iI the speciIied bonus is greater than 0. In
case, the value oI the bonus Iield is 0 or less than 0, Oracle 9i displays the message, as
shown in Iigure 2.24.
Figure 2.24
Applying the CHECK Constraint
You can also use the ALTER TABLE command to add new CHECK constraints or
modiIy the existing CHECK constraints.
Copyright 2006, Tata Consultancy Services Limited (TCS). 38
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
For example, you need to ensure that the value speciIied in the bonus Iield should be
greater than 0. For this, the query will be:
ALTER TABLE Employee_details
ADD CONSTRAINT ck_bonus_2 CHECK (bonus < min_salary);
Listing 2.25
Illustration of the CHECK Constraint
The result oI the query shown in listing 2.25 is shown in Iigure 2.25.
Figure 2.25
Using the ALTER TABLE Command with the CHECK Constraint
2.2.3 The UNIQUE Constraint
This constraint is used to ensure that there are no duplicate values Ior any column oI a
table. The UNIQUE constraint can be applied at column-level and table-level to eliminate
duplicity oI values Ior a column and multiple columns oI a table, respectively.
The column-level syntax oI the UNIQUE constraint is:
|CONSTRAINT Constraintname~| UNIQUE;
Similarly, the Iollowing is the table-level syntax oI the UNIQUE constraint:
|CONSTRAINT Constraintname~| UNIQUE (column1~, column2~,..column~);
While implementing a UNIQUE constraint, Oracle 9i creates a unique index Ior the
speciIied column. In addition, the UNIQUE constraint allows NULL values to be
speciIied in the column oI the table, on which the UNIQUE constraint is applied.
The Iollowing query displays the use oI the UNIQUE constraint:
ALTER TABLE Employee
ADD CONSTRAINT emp_id_un UNIQUE (emp_id);
Listing 2.26
Illustration of the UNIQUE Constraint
The result oI the query shown in listing 2.26 is shown in Iigure 2.26.
Copyright 2006, Tata Consultancy Services Limited (TCS). 39
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.26
Applying the UNIQUE Constraint
2.2.4 The PRIMARY KEY Constraint
This constraint is used to deIine the primary key Ior a table. A table can contain only a
single primary key. However, unlike the UNIQUE key constraint, the PRIMARY KEY
constraint does not allow NULL values to be speciIied Ior the column on which the
PRIMARY KEY constraint is applied.
The column-level syntax oI the PRIMARY KEY constraint is:
|CONSTRAINT Constraintname~| PRIMARY KEY (column name);
For example, the Iollowing query displays the use oI the PRIMARY KEY constraint.
CREATE TABLE customer
(
cust_id number(4),
cust_name varchar2(10),
CONSTRAINT cust_id_pk PRIMARY KEY (cust_id)
);
Listing 2.27
Illustration of the PRIMARY KEY Constraint
The result oI the query shown in listing 2.27 is shown in Iigure 2.27.
Figure 2.27
Applying the PRIMARY KEY Constraint
Copyright 2006, Tata Consultancy Services Limited (TCS). 40
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
2.2.5 The FOREIGN KEY Constraint
This constraint is applied to a column oI a table, and is used to ensure that Ior each value
in this column, there is some related data available in the database. The column on which
the FOREIGN KEY constraint is applied belongs to the child table, and is called the
Ioreign key. Whereas, the column to which the FOREIGN KEY constraint reIers to,
belongs to the parent table, and is called the reIerenced key. In addition, the reIerenced
key is the primary key oI the parent table. Moreover, the data type oI the Ioreign key and
the reIerenced key should be same, else, Oracle 9i generates an error message.
The syntax oI the applying the column-level FOREIGN KEY constraint is:
|CONSTRAINT Constraintname~| FOREIGN KEY
REFERENCES (table name~ (column name));
The Iollowing query displays the use oI the FOREIGN KEY constraint:
ALTER TABLE Products ADD CONSTRAINT cust_id_fk FOREIGN KEY (cust_id)
REFERENCES Customer (cust_id);
Listing 2.28
Illustration of the FOREIGN KEY Constraint
The result oI the query shown in listing 2.28 is shown in Iigure 2.28.
Figure 2.28
Applying the FOREIGN KEY Constraint
2.2.6 Working with Constraints
AIter creating various constraints, you can perIorm various operations on these
constraints, such as disabling and dropping constraints. However, when you create a
constraint, the constraint is automatically enabled. As a result, you do not have to enable
a constraint.
To disable a constraint, you need to use the ALTER TABLE statement with the
DISABLE CONSTRAINT keyword. For example, you need to disable the UNIQUE
constraint, empidun, created on the Employee table. The query Ior this will be:
ALTER TABLE Employee DISABLE CONSTRAINT emp_id_un;
Copyright 2006, Tata Consultancy Services Limited (TCS). 41
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Listing 2.29
Illustration of the DISABLE CONSTRAINT Keyword
The result oI the query shown in listing 2.29 is shown in Iigure 2.29.
Figure 2.29
Disabling a UNIQUE Constraint
Similarly, you can drop a constraint, using the DROP CONSTRAINT keyword oI the
ALTER TABLE statement. For example, you need to delete the UNIQUE constraint,
empidun. The query Ior this will be:
ALTER TABLE Employee DROP CONSTRAINT emp_id_un;
Listing 2.30
Illustration of the DROP CONSTRAINT Keyword
The result oI the query shown in listing 2.30 is shown in Iigure 2.30.
Figure 2.30
Dropping a UNIQUE Constraint
However, to drop a NOT NULL constraint, you need to use the ALTER TABLE
MODIFY statement. For example, iI you want to drop the NOT NULL constraint,
prodidnum, created on the Products table, the query Ior this will be:
ALTER TABLE Products MODIFY product_id NULL;
Listing 2.31
Illustration of the MODIFY Keyword
The result oI the query shown in listing 2.31 is shown in Iigure 2.31.
Copyright 2006, Tata Consultancy Services Limited (TCS). 42
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
Figure 2.31
Dropping a NOT NULL Constraint
Copyright 2006, Tata Consultancy Services Limited (TCS). 43
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
SUMMARY
To retrieve data Irom the tables, you need to use an SQL query.
A query is a collection oI SQL commands that is used to retrieve data Irom
database tables.
The main component oI a SQL query is the SELECT statement.
To change the display name oI the column oI a table, you need to use the AS
keyword with the SELECT statement.
To eliminate duplicate records Irom the query result, you need to use the
DISTINCT keyword along with the SELECT statement.
For condition-oriented SQL queries, you can use the WHERE clause with the
SELECT statement.
The various operators used along with the WHERE clause are:
o Comparison operators
o Logical operators
o Other operators
Comparison operators are used to compare two values or expressions Ior
providing a Boolean result that can be True, False, or Null.
Logical operators are used to generate a single result Ior the results oI two
comparison operations.
SQL provides various other operators, such as IN, NOT IN, BETWEEN, LIKE,
IS NULL, and IS NOT NULL.
Constraints can be deIined as restrictions applied to the tables, so that incorrect
and inaccurate data can be prevented Irom being stored in the tables.
SQL provides various deIault integrity constraints, which are:
o NOT NULL
o CHECK
o UNIQUE
o PRIMARY KEY
o FOREIGN KEY
Copyright 2006, Tata Consultancy Services Limited (TCS). 44
Understanding SQL using ORACLE Database Basic SQL Commands and Constraints
SELF ASSESMENT
Q1) Fill in the blanks:
1. is used to disable the existing constraints.
2. To remove duplicate records Irom the result, you need to use the
keyword with the statement.
3. Operators are used along with the clause.
4. Comparison operators generate a result.
Q2) State true or Ialse:
1. Inequality operator is a comparison operator.
2. ANY is a comparison operator, whereas SOME is a logical operator.
3. ALL is a logical operator.
4. LIKE operator is used Ior pattern matching.
5. sign indicates multiple characters in the pattern matching process.
Copyright 2006, Tata Consultancy Services Limited (TCS). 45
Understanding SQL using ORACLE Database Introducing Functions
Introducing Functions
SCOPE
3.1 IdentiIying the Types oI Functions
3.1.1 Single-Row Functions
3.1.1.1 Number Functions
3.1.1.2 Character Functions
3.1.1.3 Date/Time Functions
3.1.1.4 Conversion Functions
3.1.1.5 Miscellaneous Functions
3.2 Group Functions
3.2.1 Working with the GROUP BY and HAVING Clause
Copyright 2006, Tata Consultancy Services Limited (TCS). 46
Understanding SQL using ORACLE Database Introducing Functions
3.1 Identifying the Types of Functions
Functions are database objects that enable you to create customize programs to meet the
user requirements. Functions contain the set oI encapsulated SQL code within them. It
takes either zero or desired number oI arguments and returns the result. For example,
Iunction name~ (argument 1, argument 2, .) Irom table name~. There are multiple
SQL Iunctions available in Oracle 9i that return alphabetic or numeric values based on
the required result.
There are two types oI Iunctions:
Single-Row: This Iunction returns the result on row-by-row basis oI a queried
table. You can use this Iunctions using SELECT, WHERE, and ORDER BY
clauses oI the SELECT statement.
Group: This Iunction returns the result based on the group oI rows oI a queried
table. You can use this Iunction using SELECT, HAVING clauses oI the
SELECT statement. You can also use the GROUP BY clause with the SELECT
clause.
3.1.1 Single-Row Functions
SQL provides various single-row Iunctions. These built-in Iunctions are grouped
according to their Iunctionality as illustrated in the Iigure 3.1.
Figure 3.1
Types of Single-Row Functions
Copyright 2006, Tata Consultancy Services Limited (TCS). 47
Number Functions
Character Functions
Date/Time Functions
Conversion Functions
Miscellaneous Functions
Understanding SQL using ORACLE Database Introducing Functions
3.1.1.1 Number Functions
Number Iunctions are used where you need to perIorm arithmetic or numeric
calculations. These Iunctions accept the numeric arguments and return the numeric
values. The commonly used numeric Iunctions deIined in SQL are:
ABS: Returns the absolute value oI an argument. It takes one argument. The
syntax oI the ABS Iunction is:
Select ABS(<arg>) <column name> from <table name>;
Listing 3.1
Syntax of the ABS Function
For example, you want to Iind the absolute value Ior -16. To do this, you need to enter
the query shown in listing 3.2.
Select ABS(-16) from dual;
Listing 3.2
Illustration of the ABS Function
Figure 3.2
Result of Listing 3.2
COS: Returns the cosine oI an argument up to 36 digits oI precision. It takes one
argument. The syntax oI the COS Iunction is:
Select COS(<arg> from <table name>;
Listing 3.3
Syntax of the COS Function
For example, you need to Iind the Cosine Ior the value 1. To do this, you need to enter
the query shown in listing 3.4.
Select COS(1) from dual;
Listing 3.4
Illustration of the COS Function
Copyright 2006, Tata Consultancy Services Limited (TCS). 48
Understanding SQL using ORACLE Database Introducing Functions
Figure 3.3
Result of Listing 3.4
ROUND: Takes two arguments, arg1 and arg2. The argument, arg2 is an integer.
It returns the value by rounding oII arg1 to the number oI digits speciIied in arg2
Irom the right side oI the decimal. II arg2 is negative then arg1 is rounded Irom
the leIt oI the decimal. The syntax oI the ROUND Iunction is:
Select ROUND(<arg1>, <arg2) <column name> form <table name>;
Listing 3.5
Syntax of the ROUND Function
For example, you need to round oII the Iigure 4321.34531 with the 2 digits oI precision
Irom the right oI the decimal. To do this, you need to enter the query shown in listing 3.6.
Select ROUND(4321.34531, 2) Round from dual;
Listing 3.6
Illustration of the ROUND Function
Figure 3.4
Result of Listing 3.6
SQRT: Returns the square root oI an argument. It takes one argument. The syntax
oI the SQRT Iunction is:
Select SQRT(<arg>) from <table name>;
Listing 3.7
Syntax of the SQRT Function
For example, you need to Iind the square root oI 25. To do this, you need enter the query
shown in listing 3.8.
Select SQRT(25) from dual;
Listing 3.8
Copyright 2006, Tata Consultancy Services Limited (TCS). 49
Understanding SQL using ORACLE Database Introducing Functions
Illustration of the SQRT Function
Figure 3.5
Result of Listing 3.8
SQL also provides additional numeric Iunctions, which are speciIied in the given table.
Function Description Example Result
ACOS Returns the arc cosine oI an
argument.
Select acos(1)
Irom dual;
0
ASIN Returns the arc sine oI an
argument.
Select asin(-1)
Irom dual;
-1.5707963
ATAN Returns the arc tangent oI an
argument.
Select atan(1)
Irom dual;
.785398163
CEIL Returns the next integer
greater than or equal to the
value.
Select ceil(25.01)
Irom dual;
26
FLOOR Returns the next integer less
than or equal to the value.
Select Iloor(25.99)
Irom dual;
25
MOD Returns the remainder oI the
value speciIied in arg1
divided by the value
speciIied in arg2.
Select mod(23,7)
Irom dual;
2
POWER Takes two arguments, arg1
and arg2 and returns the
arg2
th
power oI arg1.
Select power(3,2)
Irom dual;
9
SIGN Returns the number
speciIying that the value is
positive, negative, or zero.
Select sign(-34)
Irom dual;
-1
SIN Returns the sine oI an
argument.
Select sin(1) Irom
dual;
.841470985
TAN Returns the tangent oI an
argument.
Select tan(1) Irom
dual;
1.55740772
TRUNC Returns the truncated value
up to the value speciIied in
arg2.
Select
trunc(234.345,2)
Irom dual;
234.34
Copyright 2006, Tata Consultancy Services Limited (TCS). 50
Understanding SQL using ORACLE Database Introducing Functions
3.1.1.2 Character Functions
Character Iunctions accept arguments that are oI character data type. However, most oI
the character Iunctions return character values. The commonly used character Iunctions
deIined in SQL are:
ASCII: Returns the ASCII value oI the character argument. This Iunction can also
take character string as an argument but returns the ASCII value oI the Iirst
character oI that string. The syntax oI the ASCII Iunction is:
Select ASCII(`<arg>') <column name> from <table name>;
Listing 3.9
Syntax of the ASCII Function
For example, you need to Iind the ASCII value Ior the character M in upper and lower
case. So, to do this you need to enter the query shown in listing 3.10.
Listing 3.10
Illustration of the ASCII Function
Select ASCII(`M') Uppercase, ASCII(`m') Lowercase from dual;
Figure 3.6
Result of Listing 3.10
CHR: Returns the character corresponding to the integer value passed as an
argument. It takes one argument. The syntax oI the CHR Iunction is:
Select CHR(<arg>) from <table name>;
Listing 3.11
Syntax of the CHR Function
For example, you need to Iind the character Ior the value, 75. To do this, you need to
enter the query shown in listing 3.12.
Select CHR(75) from dual;
Listing 3.12
Illustration of the CHR Function
Copyright 2006, Tata Consultancy Services Limited (TCS). 51
Understanding SQL using ORACLE Database Introducing Functions
Figure 3.7
Result of listing 3.12
CONCAT: Appends arg2 with arg1 and returns the character string. It takes two
character string arguments. II arg1 is NULL then arg2 is returned and vice versa.
The syntax oI the CONCAT Iunction is:
Select CONCAT(`<arg1>`, `<arg2>') <column name> from <table name>;
Listing 3.13
Syntax of the CONCAT Function
For example, you need to concatenate two character strings, John and Chacko. To do this,
you need to enter the query shown in listing 3.14.
Select CONCAT(`John `, `Chacko') Name from dual;
Listing 3.14
Illustration of the CONCAT Function
Figure 3.8
Result of Listing 3.14
LENGTH: Returns the length oI the character string entered as an argument. It
takes one argument. II an argument is NULL then NULL is returned. The syntax
oI the LENGTH Iunction is:
Select LENGTH(`<arg>') <column name> from <table name>;
Listing 3.15
Syntax of the LENGTH Function
For example, you need to Iind the length oI the character string, The Brown Fox. For this,
you need to enter the query shown in listing 3.16.
Select LENGTH(`The Brown Fox') Length from dual;
Copyright 2006, Tata Consultancy Services Limited (TCS). 52
Understanding SQL using ORACLE Database Introducing Functions
Listing 3.16
Illustration of the LENGTH Function
Figure 3.9
Result of Listing 3.16
SQL also provides additional character Iunctions, which are speciIied in the given table.
Function Description Example Result
INITCAP Returns the character
string with Iirst letter in
uppercase.
Select initcap(book`) Irom
dual;
Book
LOWER Returns all the characters
oI the string in lowercase.
Select lower(WORLD`)
Irom dual;
World
UPPER Returns all the characters
oI the string in uppercase.
Select upper(press`) Irom
dual;
PRESS
LPAD Returns the character
string by Iilling the special
character on the leIt side
oI the string until the
length oI the string
becomes equal to the
speciIied length.
Select lpad(Final`,`10`,
#`) Irom dual;
#####Final
LTRIM Returns the characters by
trimming the string Irom
leIt side until the character
that are not in the
trimming value are Iound.
Select ltrim(promise`,
pro`) Irom dual;
mise
RPAD Returns the character
string by Iilling the special
character on the right side
oI the string until the
length oI the string
becomes equal to the
speciIied length.
Select rpad(Page 1`, 10`,
.`) Irom dual;
Page 1..
RTRIM Returns the characters by
trimming the string Irom
right side until the
character that are not in
the trimming value are
Iound.
Select
rtrim(Proportionate`,
ate`) Irom dual;
Proportion
Copyright 2006, Tata Consultancy Services Limited (TCS). 53
Understanding SQL using ORACLE Database Introducing Functions
SOUNDEX Returns the characters that
sound alike an argument.
Select soundex(Mike`)
Irom dual;
M200
TRANSLATE Returns the argument,
arg1 aIter replacing all the
characters in arg2 with the
characters mentioned in
arg3.
Select
translate(king`,`g`,`d`)
Irom dual;
kind
3.1.1.3 Date/Time Functions
Date and Time Iunctions work with the values oI DATE datatype. These Iunction returns
a date/time or interval value oI DATE datatype. The commonly used date Iunctions
deIined in SQL are:
ADDMONTHS: Adds the system date mentioned in arg1 with the number oI
months mentioned in arg2. It takes two arguments in which arg1 is SYSDATE
and arg2 is an integer. The syntax oI the ADDMONTHS Iunction is:
Select ADD_MONTHS(<arg1>, <arg2>) from <table name>;
Listing 3.17
Syntax of the ADD_MONTHS Function
For example, you need to add Iive months to the system date. To do this, you need to
enter the query shown in listing 3.18.
Select SYSDATE,
ADD_MONTHS(Sysdate, 5)
From dual;
Listing 3.18
Illustration of the SYSDATE Function
Figure 3.10
Result of Listing 3.18
CURRENTDATE: Returns the current date. It takes no argument. The syntax oI
the CURRENTDATE Iunction is:
Copyright 2006, Tata Consultancy Services Limited (TCS). 54
Understanding SQL using ORACLE Database Introducing Functions
Select CURRENT_DATE from <table name>;
Listing 3.19
Syntax of the CURRENT_DATE Function
For example, you need to Iind the current date. To do this, you need to enter the query
shown in listing 3.20.
Select CURRENT_DATE from dual;
Listing 3.20
Illustration of the CURRENT_DATE Function
Figure 3.11
Result of Listing 3.20
LASTDAY: Returns the last day oI the month Ior the date mentioned in arg. It
takes one date argument. The syntax oI the LASTDAY Iunction is:
Select LAST_DAY(<arg>) from <table name>;
Listing 3.21
Syntax of the LAST_DAY Function
For example, you need to Iind out the last day oI the month. To do this, you need to enter
the query shown in listing 3.22.
Select SYSDATE,
LAST_DAY(SYSDATE) Last_Day
from dual;
Listing 3.22
Illustration of the LAST_DAY Function
Figure 3.12
Result of Listing 3.22
Copyright 2006, Tata Consultancy Services Limited (TCS). 55
Understanding SQL using ORACLE Database Introducing Functions
MONTHSBETWEEN: Returns the number oI months between dates mentioned
in arg1 and arg2. It takes two date arguments. The syntax oI the
MONTHSBETWEEN Iunction is:
Select MONTHS_BETWEEN(<arg1>, <arg2>) from <table name>;
Listing 3.23
Syntax of the MONTHS_BETWEEN Function
For example, you need to Iind out the number oI months between 4-May-05 and
4-Feb-05. To do this, you need to enter the query shown in listing 3.24.
Select MONTHS_BETWEEN('04-FEB-2005', '04-MAY-2005') Months
from dual;
Listing 3.24
Illustration of the MONTHS_BETWEEN Function
Figure 3.13
Result of Listing 3.24
SQL also provides additional DATE and TIME Iunctions, which are speciIied in the
given table.
Functions Description Example Result
CURRENTTIMESTAMP Returns the current
date and time in the
session`s time zone.
Select
currenttimestamp
Irom dual;
01-FEB-05
08.46.00.000000 AM
05:30
DBTIMEZONE Returns the
database`s time zone.
Select dbtimezone
Irom dual;
-05:00
EXTRACT Extracts and returns a
component oI
date/time interval.
Select sysdate,
extract(month Irom
sysdate) Irom dual;
2 (returns the month
as per the current
date)
SESSIONTIMEZONE Returns the current
session`s time zone. It
takes no argument
Select sessiontimezone
Irom dual;
05:00
TODATE Converts and returns
the date in a speciIied
Iormat.
Select
todate(10/12/2003`,`
MM/DD/YYYY) Irom
dual;
12-OCT-2003
Copyright 2006, Tata Consultancy Services Limited (TCS). 56
Understanding SQL using ORACLE Database Introducing Functions
3.1.1.4 Conversion Functions
Conversion Iunctions enable you to convert value oI one datatype to another. The
commonly used conversion Iunctions deIined in SQL are:
BINTONUM: Converts the bit-Iield set as an argument to a number. It takes
one argument, which contains the list oI bits separated by comma. The syntax oI
the BINTONUM Iunction is:
Select BIN_TO_NUM(<arg>) from <table name>;
Listing 3.25
Syntax of the BIN_TO_NUM Function
For example, you need to convert the bit-Iield, (1,0,0,1) to a number. To do this, you
need to enter the query shown in listing 3.26.
Select BIN_TO_NUM(1,0,0,1) from dual;
Listing 3.26
Illustration of the BIN_TO_NUM Function
Figure 3.14
Result of Listing 3.26
TOCHAR(Date): Converts and Iormat the arg1 into a character string. It takes
three arguments, arg1 can be either number or date, arg2 is the Iormat oI character
string, and arg3 speciIies the language in which month and day names are
returned. The syntax oI the TOCHAR Iunction is:
Select TO_CHAR(<arg1>, `<arg2>', `<arg3>') from <table name>;
Listing 3.27
Syntax of the TO_CHAR Function
For example, you need to convert the system date, 01-FEB-2005 in a character string
Iormat. To do this, you need to enter the query shown in listing 3.28.
Select TO_CHAR(SYSDATE, `Ddspth month yyyy')
System_Date from dual;
Listing 3.28
Illustration of the TO_CHAR Function
Copyright 2006, Tata Consultancy Services Limited (TCS). 57
Understanding SQL using ORACLE Database Introducing Functions
Figure 3.15
Result of Listing 3.28
UNISTR: Returns the Unicode oI the argument in the database Unicode character
set. It takes one character string argument. The syntax oI the UNISTR Iunction is:
Select UNISTR(`<arg>') from <table name>;
Listing 3.29
Syntax of the UNISTR Function
For example, you want the Unicode character set Ior the Unicode \00B4 and \00D5. To
do this, you need to enter the query shown in listing 3.30.
Select UNISTR(`\00B4')
UNISTR(`\00D5') from dual;
Listing 3.30
Illustration of the UNISTR Function
Figure 3.16
Result of Listing 3.30
SQL also provides additional conversion Iunctions, which are speciIied in the given table.
Copyright 2006, Tata Consultancy Services Limited (TCS). 58
Understanding SQL using ORACLE Database Introducing Functions
Functions Description Example Result
CHARTOROWID Creates a ROWID
value Irom a
character-based
representation oI a
ROWID.
Select empno, ename Irom
emp where rowid
chartorowid(AAAH14AA
BAAAOHAAA`);
EMPNO: 7369
ENAME:
SMITH
TOCHAR(Numb
er)
Converts the
numeric value into
a VARCHAR2
value.
Select tochar(Sal,
$9,999.99`) Irom emp;
It appends $ sign
on the leIt side oI
the salary
amount.
TODSINTERVA
L
Creates an interval
day to second
value.
Select sysdate
todsinterval(1 00:00:00`)
Irom dual;
It displays a date
beIore the
current date.
TOTIMESTAMP Creates a
timestamp value.
Select
totimestamp(2002-dec-1
2 08:00:00`,
yyyy-mon-dd`) Irom dual;
12-dec-2002
08.00.00.000000
000 AM
TOTIMESTAMP
TZ
Creates a
timestamp with
time zone value.
Select
totimestamptz(2002-de
c-12 08:00:00`,
yyyy-mon-dd hh:mi:ss
tzh:tzm`) Irom dual;
12-dec-2002
08.00.00.000000
000 AM -08:00
3.1.1.5 Miscellaneous Functions
Miscellaneous Iunctions are those Iunctions that are not included in any category oI
single-row Iunctions. These Iunctions work with string values in SQL. The commonly
used miscellaneous Iunctions deIined in SQL are:
DECODE: Compares the argument against the search value one-by-one. The
syntax oI DECODE Iunction is:
Select DECODE(<arg1>, `<arg2>', `<arg3>') from <table name>;
Listing 3.31
Syntax of the DECODE Function
For example, you want to convert the job description, ANALYST to the job description,
OFFICER. To do this, you need to enter the query as shown in listing 3.32.
Select ename, DECODE(job, `ANALYST', `OFFICER', job)
from emp;
Listing 3.32
Illustration of the DECODE Function
Copyright 2006, Tata Consultancy Services Limited (TCS). 59
Understanding SQL using ORACLE Database Introducing Functions
Figure 3.17
Result of Listing 3.32
GREATEST: Returns the greatest value Irom the list. The syntax oI GREATEST
Iunction is:
Select GREATEST(<arg1>, <arg2>, <arg3>, ...) from <table name>;
Listing 3.33
Illustration of the GREATEST Function
For example, you want to Iind the greatest value out oI the list oI numbers entered as the
arguments. To do this, you need to enter the query shown in listing 3.34.
Select GREATEST(2,4,6,3,5)
from dual;
Listing 3.34
Illustration of the GREATEST Function
Copyright 2006, Tata Consultancy Services Limited (TCS). 60
Understanding SQL using ORACLE Database Introducing Functions
Figure 3.18
Result of Listing 3.34
LEAST: Returns the least value Irom the list. The syntax oI LEAST Iunction is:
Select LEAST(<arg1>, <arg2>, <arg3>, ...) from <table name>;
Listing 3.35
Illustration of the LEAST Function
For example, you want to Iind the least value out oI the list oI numbers entered as the
arguments. To do this, you need to enter the query shown in listing 3.36.
Select LEAST(3,2,4,6,9)
from dual;
Listing 3.36
Illustration of the LEAST Function
Figure 3.19
Result of Listing 3.36
UID: Returns the value that uniquely identiIies the connected user. The syntax oI
UID Iunction is:
Select uid from <table name>;
Listing 3.37
Illustration of the UID Function
For example, you want to Iind the ID oI the currently connected user. To do this, you
need to enter the query shown in listing 3.38.
Copyright 2006, Tata Consultancy Services Limited (TCS). 61
Understanding SQL using ORACLE Database Introducing Functions
Select uid from dual;
Listing 3.38
Illustration of the UID Function
Figure 3.20
Result of Listing 3.38
USER: Returns the name oI the currently connected user. The syntax oI USER
Iunction is:
Select user from <table name>;
Listing 3.39
Illustration of the USER Function
For example, you want to Iind the currently connected user. To do this, you need to enter
the query shown in listing 3.40.
Select User from dual;
Listing 3.40
Illustration of the USER Function
Figure 3.21
Result of Listing 3.40
3.2 Group Functions
SQL also includes multiple built-in group Iunctions, which are:
AVG: Returns the average oI the expression. The syntax oI the AVG Iunction is:
Copyright 2006, Tata Consultancy Services Limited (TCS). 62
Understanding SQL using ORACLE Database Introducing Functions
Select AVG(<exp>) from <table name>;
Listing 3.41
Syntax of the AVG Function
For example, you need to Iind out the average salary oI all the employees Irom the
employee table. To do this, you need to enter the query shown in listing 3.42.
Select AVG(SAL) from emp;
Listing 3.42
Illustration of the AVG Function
Figure 3.22
Result of Listing 3.42
COUNT: Returns the number oI rows in a query. The syntax oI the COUNT
Iunction is:
Select COUNT(<exp>) from <table name>;
Listing 3.43
Syntax of the COUNT Function
For example, you need to Iind out the number oI employees entered in the employee
table. To do this, you need to enter the query shown in listing 3.44.
Select COUNT(EMPNO) from emp;
Listing 3.44
Illustration of the COUNT Function
Figure 3.23
Result of Listing 3.44
Copyright 2006, Tata Consultancy Services Limited (TCS). 63
Understanding SQL using ORACLE Database Introducing Functions
MAX: Returns the maximum value in the expression. The syntax oI the MAX
Iunction is:
Select MAX(<exp>) from <table name>;
Listing 3.45
Syntax of the MAX Function
For example, you need to Iind the highest salary that is paid to the employee. To do this,
you need to enter the query shown in listing 3.46.
Select MAX(SAL) from emp;
Listing 3.46
Illustration of the MAX Function
Figure 3.24
Result of Listing 3.46
MIN: Returns the minimum value in the expression. The syntax oI the MIN
Iunction is:
Select MIN(<exp>) from <table name>;
Listing 3.47
Syntax of the MIN Function
For example, you need to Iind the lowest salary that is paid to the employee. To do this,
you need to enter the query shown in listing 3.48.
Select MIN(SAL) from emp;
Listing 3.48
Illustration of the MIN Function
Figure 3.25
Result of Listing 3.48
Copyright 2006, Tata Consultancy Services Limited (TCS). 64
Understanding SQL using ORACLE Database Introducing Functions
3.2.1 Working with the GROUP BY and HAVING Clause
SQL also enables you to group or categorize the data according to your requirements. For
example, you need to Iind out the average salaries Ior each department. To do this, you
can use GROUP BY clause.
Select job, AVG(Sal) AVG_SAL
from emp
GROUP BY job;
Listing 3.49
Illustration of the GROUP BY Clause
Figure 3.26
Result of Listing 3.49
To continue with previous example, you can also Iilter the resultant rows using the
HAVING clause. For example, iI you want to see all those job positions that have an
average salary greater than or equal to 2500. To do this, you can use HAVING clause.
Select Job, AVG(Sal) AVG_SAL
from emp
GROUP BY Job
HAVING AVG(Sal) >= 2500;
Listing 3.50
Illustration of the HAVING Clause
Copyright 2006, Tata Consultancy Services Limited (TCS). 65
Understanding SQL using ORACLE Database Introducing Functions
Figure 3.27
Result of Listing 3.50
SUMMARY
Functions are the database objects that enable you to create customize programs
to meet the user requirements.
Functions contain the set oI encapsulated SQL code within them.
Single-Row Iunctions return the result on row-by-row basis oI a queried table.
Group Iunctions return the result based on the group oI rows oI a queried table.
Single-Row Iunctions are grouped according to their Iunctionality. This includes:
o Number Iunction
o Character Iunction
o Date/Time Iunction
o Conversion Iunction
o Miscellaneous Iunction
SQL also enables you to group or categorize the data according to your
requirements by using the GROUP BY clause.
Copyright 2006, Tata Consultancy Services Limited (TCS). 66
Understanding SQL using ORACLE Database Introducing Functions
SELF ASSESSMENT
I. Fill up the blanks:
a) Iunctions return the result on row-by-row basis oI a queried table.
b) Iunction returns the result based on the group oI rows oI a queried table.
c) The Iunction converts the bit-Iield set as an argument to a number.
d) The Iunction returns the length oI the character string entered as an
argument.
e) The Iunction Returns the Unicode oI the argument in the database
Unicode character set.
II. State True or False:
a) The LASTDAY Iunction returns the last day oI the year.
b) The COUNT Iunction returns the number oI rows in a query.
c) The ASCII Iunction returns the ASCII value oI the numeric argument.
d) The CHR Iunction returns the character corresponding to the integer value passed as
an argument.
Copyright 2006, Tata Consultancy Services Limited (TCS). 67
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Introducing 1oins and Subqueries
SCOPE
4.1 Working with Joins
4.1.1 Inner Join
4.1.2 Outer Join
4.1.2.1 LeIt Outer Join
4.1.2.2 Right Outer Join
4.1.2.3 Full Outer Join
4.1.3 SelI Join
4.1.4 Natural Join
4.2 Working with Subqueries
4.2.1 Single row subqueries
4.2.2 Multiple row subqueries
4.2.3 Nested subqueries
4.2.4 Correlated subqueries
Copyright 2006, Tata Consultancy Services Limited (TCS). 68
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
4.1 Working with 1oins
In an organization, data is stored in multiple tables. This data can also be dependent or
related to each other. For example, deptno column is the primary key oI the department
table and Ioreign key oI employee table. In these circumstances, data Irom multiple tables
can be required. For example, HR department oI an organization stores data regarding
employees in several tables, such as employee and department. The structure oI employee
and department table is shown in the Iigure 4.1.

Emp_id Ename Designation Salary Dept_no
4501 John Sales Man 1000 10
4502 Michael Team Leader 1800 20
4503 Nancy Project
Manager
2500 20
4504 Smith Clerk 1500 30
4505 Harry Clerk 1500 30
Dept_no Dept_name Location
10 Sales Texas
20 IT CaliIornia
30 Accounting Denver
Figure 4.1
Structure of Employee and Department Tables
Consider a situation where the HR manager require data Irom multiple tables to perIorm
operations, such as gross salaries paid to employees oI a particular department or Ior
gathering inIormation, such as employee perIormance. To achieve these tasks, Joins are
used. SQL perIorms a join operation, when you speciIy two or more tables in the FROM
clause oI the SELECT query. For example, the given query shows the name, designation,
and department name oI every employee based on the data stored in the employee and
department tables.
Select ename, designation, dept_name from employee, department where
employee.dept_no=department.dept_no;
Figure 4.2 illustrates how a join is perIormed and shows the result oI the given query:
Copyright 2006, Tata Consultancy Services Limited (TCS). 69
Employee
Department
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Figure 4.2
1oin Process
In Oracle 9i, several types oI joins can be perIormed, which include:
Inner join
Outer join
SelI join
Natural join
Copyright 2006, Tata Consultancy Services Limited (TCS).
70
Empid Ename Designation Salary Deptno
4501 John Sales Man 1000 10
4502 Michael Team Leader 1800 20
4503 Nancy Project
Manager
2500 20
4504 Smith Clerk 1500 30
4505 Harry Clerk 1500 30
Deptno Deptname Location
10 Sales Texas
20 IT CaliIornia
30 Accounting Denver
Join
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
4.1.1 Inner join
Is a simple and most commonly used type oI join? It is used to retrieve only those rows oI
table, which satisIy the join condition. Consider a scenario where the HR manager oI an
organization wants to view a list oI employees with their corresponding department
name. To achieve this task, you can use the query shown in Iigure 4.3.
Figure 4.3
Inner 1oin
4.1.2 Outer 1oin
Is an extension oI inner join, as it retrieves rows oI data, which satisIy the join condition?
In addition, outer join retrieves the rows oI data Ior which no record is Iound in the
corresponding join table.
Consider a situation where the employee table also includes records oI new employees
who have not been assigned any department, as shown:
.
Copyright 2006, Tata Consultancy Services Limited (TCS). 71
Emp_id Ename Designation Salary Dept_no
4501 John Sales Man 1000 10
4502 Michael Team Leader 1800 20
4503 Nancy Project
Manager
2500 20
4504 Smith Clerk 1500 30
4505 Harry Clerk 1500 30
4506 Clark Executive 1000
4507 Ella Executive 1000
Record oI
Employees
having no
department
Employee
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
The HR manger wants to view records oI all the employees with their department names.
In addition, the HR manager wants to view records oI employees who have not been
assigned department names. This type oI tasks can be achieved easily using outer joins.
SQL provides three types oI outer joins:
LeIt Outer Join
Right Outer Join
Full Outer Join
4.1.2.1 Left Outer 1oin
This join includes all the rows Irom the Iirst table and the matching rows oI the second
table, as illustrated in the Iigure 4.4.
Figure 4.4
Left Outer 1oin
4.1.2.2 Right Outer 1oin
This join includes all the rows oI the second table and the matching rows oI the Iirst
table. Consider a scenario where an organization has opened a new department Tech
Support and its record has been added to the Department table, as shown:
Dept_no Dept_name Location
10 Sales Texas
20 IT CaliIornia
30 Accounting Denver
40 Tech Support Rhode Island
However, currently no employees are recruited Ior this department. The HR manager
wants to view a list oI all the departments along with employees working in each
department. In addition, the HR manager wants to view a list oI departments Ior which
Copyright 2006, Tata Consultancy Services Limited (TCS).
72
Keyword to perIorm leIt
outer join
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
employees have not been recruited. To achieve this task, you can use the query shown in
the Iigure 4.5.
Figure 4.5
Right Outer 1oin
4.1.2.3 Full Outer 1oin
This join is used to view all the rows oI both the tables. Consider a scenario where the
HR manager wants to view a list, which includes:
Name oI employees along with their departments
Name oI employees who have not been assigned any department
Name oI the departments Ior which employees have not been recruited
To achieve this task, you can use the query shown in the Iigure 4.6.
Copyright 2006, Tata Consultancy Services Limited (TCS). 73
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Figure 4.6
Full Outer 1oin
4.1.3 Self 1oin
This join is used to derive results Irom a single table. Consider the given structure oI the
employee table:
Copyright 2006, Tata Consultancy Services Limited (TCS).
74
Emp_id Ename Designation Salary Dept_no Manager_ID
4501 John Sales Man 1000 10 4508
4502 Michael Team Leader 1800 20 4509
4503 Nancy Project
Manager
2500 20 4509
4504 Smith Clerk 1500 30 4510
4505 Harry Clerk 1500 30 4510
4506 Clark Executive 1000 40 4511
4507 Ella Executive 1000 40 4511
4508 Tom Sr.Vice
President
4500 10 4511
4509 Steve Vice President 4000 20 4511
4510 James Vice President 4000 30 4511
4511 David President 7000
Employee
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
The HR manager wants to view a list oI employees along with name oI their
corresponding managers. These types oI tasks can be easily achieved using selI-join, as
shown in the Iigure 4.7.
Figure 4.7
Self 1oin
Figure 4.8 illustrates the process oI selI join:
Copyright 2006, Tata Consultancy Services Limited (TCS). 75
Employee e1
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Figure 4.8
Self 1oin Process
4.1.4 Natural 1oin
This join retrieves records Irom tables having same column. In addition, while using this
join, you are not required to speciIy the same column name. As Oracle 9i implicitly joins
the two tables based on that column. Consider a scenario where the HR manager oI an
organization wants to view a list oI employees along with their salary and department
names. For achieving this task query shown in Iigure 4.9 can be used.
Copyright 2006, Tata Consultancy Services Limited (TCS).
76
Employee e2
E1.manager

E2.empid
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Figure 4.9
Natural 1oin
4.2 Working with Subqueries
A subquerv is a query, which is nested within a query and is used to retrieve complex
results. In addition, a subquery is used to retrieve records Irom a table when the condition
speciIied to retrieve records is based on the table itselI. Consider a scenario where the HR
manager oI an organization wants to view a list oI employees having same designation as
employee Steve. To achieve this task, the query shown in Iigure 4.10 can be used.
Figure 4.10
Sample Subquery
Oracle 9i processes the subquery Iirst and the result oI subquery is used by the parent
query. For example, in the query given in Iigure 4.10, Oracle 9i evaluates the sub query
SELECT DESIGNATION FROM EMPLOYEE WHERE ENAME ='Steve' and the
result oI this sub query is 20. AIter processing the sub query, the parent query becomes
select emp_id, ename from employee where designation =20.
The records are retrieved based on this parent query.
The subqueries can be classiIied in Iour categories:
Single row subqueries
Multiple row subqueries
Nested subqueries
Correlated subqueries
4.2.1 Single Row Subqueries
The subqueries, which return only a single record, are called single row subqueries.
Consider a scenario where the HR manager oI an organization wants to view the details
oI the employee who gets maximum salary. To achieve this task, query shown in Iigure
4.11 can be used.
Copyright 2006, Tata Consultancy Services Limited (TCS). 77
Parent Query
Sub Query
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Figure 4.11
Sample Single Row Subquery
4.2.2 Multiple Row Subqueries
The subqueries, which return multiple records, are called multiple row subqueries.
Consider a scenario where the HR manager oI an organization wants to view a list oI
employees earning maximum salary in each department. To achieve this task, query
shown in Iigure 4.12 can be used.
Figure 4.12
Sample Multiple Row Subquery
You need to specifv multi row operator, such as IN or ALL with a multiple row
subquerv.
4.2.3 Nested Subqueries
When a query contains more than one subquery, then the outermost subquery is called a
nested subquery. Consider a scenario where the HR manager wants to view details oI the
employees who get salary more than the highest salary paid to the employee in the
accounting department. To achieve this task, query shown in Iigure 4.13 can be used.
Copyright 2006, Tata Consultancy Services Limited (TCS).
78
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Figure 4.13
Sample Nested Subquery
4.2.4 Correlated Subqueries
When a subquery reIerences to a column oI the parent query, it is called a correlated
subquery. A correlated subquery is evaluated once Ior retrieving a single record Ior the
parent query. Consider a scenario where the HR manager oI an organization wants to
view a list oI employees who earns salary more than the average salary paid to the
employees oI their department. To achieve this task, query shown in Iigure 4.14 can be
used.
Figure 4.14
Sample Correlated Subquery
SUMMARY
SQL perIorms a join operation, when you speciIy two or more tables in the
FROM clause oI the SELECT query.
In Oracle 9i, several types oI joins can be perIormed, which include:
o Inner join
o Outer join
o SelI join
o Natural join
Inner join is a simple and most commonly used type oI join. It is used to retrieve
only those rows oI table, which satisIy the join condition.
Copyright 2006, Tata Consultancy Services Limited (TCS). 79
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Outer join is an extension oI inner join, as it retrieves rows oI data, which satisIy
the join condition. In addition, outer join retrieves the rows oI data Ior which no
record is Iound in the corresponding join table.
SQL provides three types oI outer joins:
o LeIt Outer Join
o Right Outer Join
o Full Outer Join
Natural join retrieves records Irom tables having same column.
A subquerv is a query, which is nested within a query and is used to retrieve
complex results.
The subqueries can be classiIied in Iour categories:
o Single row subqueries
o Multiple row subqueries
o Nested subqueries
o Correlated subqueries
The subqueries, which return only a single record, are called single row
subqueries.
The subqueries, which return multiple records, are called multiple row subqueries.
When a query contains more than one subquery, then the outermost subquery is
called a nested subquery.
When a subquery reIerences to a column oI the parent query, it is called a
correlated subquery.
SELF-ASSESMENT
Q1) Fill in the blanks:
1. Oracle 9i provides three types oI outer joins, , , and .
2. is an extension oI inner join.
3. outer join includes all the rows Irom the Iirst table and the matching rows
oI the second table.
4. outer join includes all the rows oI the second table and the matching rows
oI the Iirst table.
5. outer join is used to view all the rows oI both the tables.
Copyright 2006, Tata Consultancy Services Limited (TCS).
80
Understanding SQL using ORACLE Database Introducing Joins and Subqueries
Q2) State true or Ialse:
1. Natural join is used to derive results Irom a single table.
2. SelI join retrieves records Irom tables having same column.
3. The subqueries, which return only a single record, are called correlated
subqueries.
4. The subqueries, which return multiple records, are called multi row subqueries.
5. When a subquery reIerences to a column oI the parent query, it is called a
correlated subquery.
Copyright 2006, Tata Consultancy Services Limited (TCS). 81
Understanding SQL using ORACLE Database Data ModiIication
Data Modification
SCOPE
5.1 Working with Data Manipulation Language (DML) Statements
5.1.1 Using the INSERT Statement
5.1.2 Using the UPDATE Statement
5.1.3 Using the MERGE Statement
5.1.4 Using the DELETE Statement
5.2 Truncating Tables
5.2.1 Comparing the TRUNCATE and the DELETE Statements
5.2.2 Locking Tables
5.3 Transaction Control in Oracle 9i
Copyright 2006, Tata Consultancy Services Limited (TCS). 81
Understanding SQL using ORACLE Database Data ModiIication
5.1 Working with Data Manipulation Language (DML)
Statements
To modiIy data stored in Oracle 9i database tables, SQL provides various statements that
are called as Data Manipulation Language (DML) statements. DML statements, such as
INSERT, UPDATE, MERGE, and, DELETE, enable you to modiIy data stored in the
database tables. However, while modiIying data, you need to remember that Oracle 9i is
a multi-user database, and enables multiple users to access and modiIy the database,
simultaneously. This may lead to inconsistency oI data, when multiple users change data
simultaneously. Inconsistency oI data can be a severe problem Ior any organization and
can lead to usage oI inaccurate data.
To eliminate inconsistency oI data in a multi-user environment, SQL provide various
DML statements that enable you to maintain the consistency oI data by controlling the
modiIications made to the data. For this, SQL provides the DML statements, such as
LOCK TABLE and SELECT FOR UPDATE.
The DML statements used Ior modiIying data in the tables are:
INSERT
UPDATE
MERGE
DELETE
5.1.1 Using the INSERT Statement
The INSERT statement is used to insert rows in a table. In addition, you can add rows to
multiple tables using the INSERT statement. The rows insert using the INSERT
statement can contain speciIic data values or data obtained as a result oI a sub-query.
The syntax oI the INSERT statement Ior inserting rows in a single table is:
INSERT INTO [<table name> <column name>] <sub-query> VALUES (value 1,
value 2, .., value N) <sub-query>;
Listing 5.1
Syntax of the Single-Table INSERT Statement
In the syntax given in listing 5.1, the column name parameter is optional as, by deIault,
all columns are speciIied in sequence oI their column ID. In addition, you need to
remember that the data types oI the speciIied data values should match the data types oI
the corresponding columns oI the table. For example, you need to insert details about the
new employees, such as empid, empname, and department in the Employee table. For
this, you need to speciIy the given query:
INSERT INTO Employee VALUES (3005, `Dave Jackson', `Production');
Listing 5.2
Illustration of the Single-Table INSERT Statement
The query given in listing 5.2 inserts this row with speciIic data values in the Employee
table. The result oI this query is shown in Iigure 5.1.
Copyright 2006, Tata Consultancy Services Limited (TCS). 82
Understanding SQL using ORACLE Database Data ModiIication
Figure 5.1
Using the Single-Table INSERT Statement
Similarly, you can use the INSERT statement to insert data values in multiple tables
simultaneously. For inserting data values in multiple tables, you need to use a single
INSERT statement. The syntax oI the INSERT statement that is used to insert data values
in multiple tables, simultaneously is:
INSERT ALL WHEN <condition1> THEN INTO <table name1> VALUES <value1,
value2,..valueN) ELSE INTO <table name2> VALUES <value1, value2,.
valueN);
Listing 5.3
Syntax of the INSERT Statement for Multiple Tables
For example, you have created two tables, named Admindetails and Productiondetails.
You need to insert the details oI the employees working in the Administration department
in the Admindetails table, Irom the Employee table. In addition, you need to insert the
details oI the employees working in the Production department in the Productiondetails
table, Irom the Employee table. The structure oI the Admindetails and the
Productiondetails table are:
Admindetails (Aempid, Aempname, Adept)
Productiondetails (Pempid, Pempname, Pdept)
The query Ior inserting data values in the Admindetails and the Productiondetails
0tables, is:
INSERT ALL
WHEN dept = `Administration' THEN
INTO Admin_details (Aemp_id, Aemp_name, Adept) VALUES (emp_id, emp_name,
dept)
WHEN dept = `Production' THEN
INTO Production_details (Pemp_id, Pemp_name, Pdept) VALUES (emp_id),
emp_name, dept)
SELECT emp_id, emp_name, dept FROM Employee;
Listing 5.4
Copyright 2006, Tata Consultancy Services Limited (TCS). 83
Understanding SQL using ORACLE Database Data ModiIication
Illustration of Multiple Table INSERT Statement
The given in listing 5.4 query inserts the speciIic data values in the Admindetails and
the Productiondetails tables, Irom the Employee table.
The result oI this query is displayed in Iigure 5.2.
Figure 5.2
Using the Multiple Table INSERT Statement
5.1.2 Using the UPDATE Statement
SQL enables you to modiIy the existing data values oI a table using the UPDATE
statement. The syntax oI the UPDATE statement is:
UPDATE <table name>
SET <column name1, column name2> = (subquery)
WHERE <condition>;
Listing 5.5
Syntax of the UPDATE Statement
The given query displays the use oI the UPDATE statement.
UPDATE Employee
SET dept = `Administration'
WHERE emp_name = `Janet Smith';
Listing 5.6
Illustration of the UPDATE Statement
The query given in listing 5.6 updates the Employee table, and modiIies the data value oI
the Dept column, where the employee name is Janet Smith`.
The result oI this query is shown in the Iigure 5.3.
Copyright 2006, Tata Consultancy Services Limited (TCS). 84
Understanding SQL using ORACLE Database Data ModiIication
Figure 5.3
Using the UPDATE Statement
Similarly, you can modiIy multiple columns oI a table using a single UPDATE statement.
The given sample query displays the use oI the UPDATE statement.
UPDATE Employee
SET dept = `Production', emp_id = 3301
WHERE emp_name = `David Smith';
Listing 5.7
Using the UPDATE Statement with Multiple Columns
The result oI the query given in listing 5.7 is shown in Iigure 5.4.
Figure 5.4
Using the UPDATE Statement with Multiple Columns
Copyright 2006, Tata Consultancy Services Limited (TCS). 85
Understanding SQL using ORACLE Database Data ModiIication
5.1.3 Using the MERGE Statement
SQL provides the MERGE statement that enables you to insert and update the rows oI a
table, simultaneously. In addition, the MERGE statement consists oI a join speciIication
that determines iI an update or insert has to be perIormed on the speciIied table.
The syntax oI the MERGE statement is:
MERGE INTO <table name> USING (<table name1> <sub query>)
ON <condition1> WHEN MATCHED THEN UPDATE SET
<column1 = expression> WHEN NOT MATCHED THEN INSERT
<column1> VALUES (expression);
Listing 5.8
Syntax of the MERGE Statement
5.1.4 Using the DELETE Statement
SQL provides the DELETE statement to remove those rows Irom a table that are not
required. The syntax oI the DELETE statement is:
DELETE FROM <table name> WHERE <condition>;
Listing 5.9
Syntax of the DELETE Statement
For example, one oI the employees, whose empid is 1001, has leIt the organization. You
need to remove this record Irom the Employee table. The given query enables you to
perIorm this task:
DELELTE FROM Employee WHERE emp_id = 1001;
Listing 5.10
Illustration of the DELELTE Statement
The result oI this query is shown in the Iigure 5.5.
Figure 5.5
Using the DELETE Statement
Copyright 2006, Tata Consultancy Services Limited (TCS). 86
Understanding SQL using ORACLE Database Data ModiIication
The use of the WHERE clause in the DELETE statement is optional. However, if
vou do not specifv the WHERE clause with the DELETE statement, all the rows in the
specified table are removed.
After executing the DML statements, vou need to execute either the COMMIT or
the ROLLBACK statements. The COMMIT statement is used to make the changes made
bv the DML statements to the table, as permanent. The ROLLBACK statement is used to
undo the changes made to the table bv the execution of the DML statements.
5.2 Truncating Tables
SQL provides the TRUNCATE command, which is used to remove all the rows Irom the
table. However, unlike the DELETE statement, the TRUNCATE statement is a Data
DeIinition Language (DDL) statement. The DDL statements are SQL statements that are
used to deIine the database objects, such as tables, views, and stored procedures.
In addition, the DDL statements automatically perIorm the COMMIT process aIter their
execution, whereas you need to explicitly execute the COMMIT statement aIter the
execution oI the DML statements. Moreover, while implicitly executing the COMMIT
statement, the DDL statements also commit any pending DML statements. Another
diIIerence between the DDL and the DML statements is that the DDL statements cannot
be rolled back whereas the DML statements can be rolled back.
Apart Irom the TRUNCATE statement, SQL provides other DDL statements, such as
CREATE ALTER, and DROP. The CREATE statement is used to create various
database objects, such as tables and views. The ALTER statement is used to modiIy the
database objects, whereas the DROP statement is used to delete the database objects.
The syntax oI the TRUNCATE statement is:
TRUNCATE TABLE <table name> DROP/REUSE STORAGE;
Listing 5.11
Syntax of the TRUNCATE Statement
In the listing 5.11, the STORAGE clause is optional. The STORAGE clause is used to
indicate the storage space used by the table, within the database. The deIault value oI the
STORAGE clause is DROP. The DROP STORAGE option shrinks the table and its
related indexes to their original size, whereas the REUSE STORAGE option does not
shrink the table and its related indexes to their original sizes.
For example, you need to remove all the rows oI the Products table, but you do not want
to shrink the size oI the Products table. The query Ior perIorming this task is:
TRUNCATE TABLE Products REUSE STORAGE;
Listing 5.12
Using the TRUNCATE Statement
Copyright 2006, Tata Consultancy Services Limited (TCS). 87
Understanding SQL using ORACLE Database Data ModiIication
The result oI this query is shown in Iigure 5.6.
Figure 5.6
Using the TRUNCATE Statement
5.2.1 Comparing the TRUNCATE and the DELETE Statements
Table 5.1 lists the diIIerences between the TRUNCATE and the DELETE statements:
TRUNCATE Statement DELETE Statement
It is a DDL statement and perIorms an
implicit COMMIT process. You cannot
ROLLBACK a TRUNCATE statement.
It is a DML statement and does not perIorm
an implicit COMMIT process.
It is a Iast process and quickly removes the
rows oI large as well as small tables. In
addition, the TRUNCATE statement
cannot be rolled back.
It is a slow process iI executed on large
tables. In addition, it will generate undo
inIormation in case the DELETE statement
is rolled back.
It can be used to shrink the size oI the table
to the original size oI the table.
It cannot be used to shrink the size oI the
table.
II the table contains a reIerential integrity
constraint, then the TRUNCATE statement
cannot be applied to it. You need to remove
the reIerential integrity constraint and then
use the TRUNCATE statement on the
table.
You can use the DELETE statement on the
table that contains a reIerential integrity
constraint applied to it.
Table 5.1
Comparison between the TRUNCATE and DELETE Statements
The TRUNCATE statement is also different from the DROP table statement. The
TRUNCATE statement does not invalidate other database obfects that are dependent on
the table on which the TRUNCATE is applied. The other dependent database obfects can
be views, index, and stored procedures. In addition, when a TRUNCATE statement is
applied to a table, it does not delete the triggers and referential integritv constraints
related to the table.
Copyright 2006, Tata Consultancy Services Limited (TCS). 88
Understanding SQL using ORACLE Database Data ModiIication
5.2.2 Locking Tables
Oracle 9i is a multi-user database and enables multiple users to access and modiIy
multiple users, simultaneously. As a result oI this Iacility, the database can encounter a
problem oI data inconsistency. For example, two users are accessing the Employee table,
simultaneously. One oI the users deletes the record oI the employee with empid, 3002,
whereas another user tries to modiIy the same record. As a result, there occurs an
inconsistency oI data values in the table. Due to data inconsistency, the users can utilize
incorrect or inaccurate data values.
To eliminate the problem oI data inconsistency, SQL provides the LOCK TABLE
statement. The LOCK TABLE statement is used to lock a table Ior other users, so that
you are able to complete your operation on the table. The LOCK TABLE command can
be used on one table or on multiple tables simultaneously.
II you have locked a table, other users will not be able to modiIy the table, till you
complete the operations on the table. AIter you complete your operations on the table,
you need to either COMMIT or ROLLBACK the operations perIormed on the table, to
unlock the table. However, other users will be able to access and query the locked table.
The syntax oI the LOCK TABLE statement is:
LOCK TABLE <table name> IN MODE <EXCLUSIVE/SHARED>
Listing 5.13
Syntax of the LOCK TABLE Statement
In the listing 5.13, the MODE option can either be EXCLUSIVE or SHARED. In the
EXCLUSIVE mode, other users are prevented Irom acquiring a shared or an exclusive
lock Ior the speciIied table, whereas in the SHARED mode, other users are prevented
Irom acquiring an exclusive lock on the speciIied table, but can acquire a shared lock on
the speciIied table.
For example, you need to lock the Employee table so that other users are not able to
acquire either the shared or the exclusive lock Ior the Employee table. The query Ior
perIorming this table is:
LOCK TABLE Employee IN EXCLUSIVE MODE;
Listing 5.14
Illustration of the LOCK TABLE Statement
The result oI this listing is shown in Iigure 5.7.
Figure 5.7
Using the LOCK TABLE Statement
Copyright 2006, Tata Consultancy Services Limited (TCS). 89
Understanding SQL using ORACLE Database Data ModiIication
Locks are primarily used in Oracle to maintain the consistency oI the database and its
tables, when the tables are being simultaneously accessed and modiIied by multiple users.
As a result, Oracle enables you to lock tables, as well as the rows oI the tables. However,
the row locks are always oI the exclusive type whereas the table locks can be either be oI
exclusive or shared type. But, all the types oI locks permit read access to the tables.
However, beIore, modiIying the rows oI a table, the required row or table-level locks are
acquired. The DML statements, such as INSERT, UPDATE, and DELETE implicitly
acquire the required locks.
Oracle uses various types oI locks, which are:
ROW SHARE (SS): This type oI lock prevents other users Irom exclusive lock
Ior the speciIied table, and permits changes oI the rows oI the speciIied table. In
addition, this type oI lock permits multiple row share and row exclusive locks on
a single table. The LOCK TABLE statement explicitly acquires this type oI lock.
ROW EXCLUSIVE (SX): This type oI lock prevents the users to acquire a share,
share row exclusive, or an exclusive lock Ior a speciIied table. In addition, this
lock is implicitly acquired by the INSERT, UPDATE, and the DELETE
statements. However, you can explicitly acquire this type oI lock using the LOCK
TABLE statement.
SHARE (S): This type oI lock permits multiple SS and S locks on the speciIied
table. In addition, the SHARE lock provides transaction-level consistency to the
table being modiIied. This is because, other users cannot modiIy the rows oI the
speciIied table till you COMMIT or ROLLBACK the transaction, which will
release the table lock. However, this type oI lock prevents the use oI multiple
SHARE ROW EXCLUSIVE locks or other table locks on the speciIied table. The
SHARE table lock can be explicitly acquired using the LOCK TABLE statement.
SHARE ROW EXCLUSIVE (SRX): This type oI lock permits other ROW
SHARE locks on the speciIied table. However, you can apply only one SRX lock
on the speciIied table at a given instant. The SRX type oI lock prevents other
users Irom acquiring other types oI locks, such as SHARE, ROW EXCLUSIVE,
or the EXCLUSIVE lock Ior the speciIied table. In addition, the SRX can be
explicitly acquired by the LOCK TABLE statement.
EXCLUSIVE (X): This type oI lock prevents other users Irom acquiring all other
types oI locks Ior a speciIied table, and can be explicitly acquired using the
LOCK TABLE statement.
Oracle permits multiple users to use locks on a single table, simultaneously. However,
this might sometimes, result in a situation called as a deadlock. Deadlock is a situation
that occurs when two transactions hold locks on a table and each transaction is waiting
Ior the other to release the lock. In such a situation, neither oI the transactions releases the
locks and result in a deadlock. As a result oI these deadlocks, none oI the transactions are
completed. These deadlocks are detected and resolved by Oracle within Iew seconds oI
their occurrence.
Copyright 2006, Tata Consultancy Services Limited (TCS). 90
Understanding SQL using ORACLE Database Data ModiIication
5.3 Transaction Control in Oracle 9i
Oracle 9i is a multi-user database and uses transactions to control the access and
modiIication to data values stored in the tables. Transactions can be deIined as the
smallest unit oI work. Oracle supports multiple transactions, simultaneously, which
modiIy the same data at the same time. As a result, these transactions need to be
controlled and coordinated so that data consistency is maintained. This process oI
maintaining data consistency and controlling multiple transactions is called transaction
control. Transaction control ensures that when a transaction is updating data values in a
table, the other transactions do not modiIy the same data. In addition, when the data
values are updated by a transaction, other transactions view the updated data values.
Oracle uses Iour SQL statements to implement transaction control and ensure data
consistency:
COMMIT: This SQL statement is used to save the changes made to the tables by
the current transaction. The changes made by the current transactions are made
permanent by this statement and are visible to other users. The COMMIT
statement also indicates the end oI a transaction. For example, you have inserted
new record in the Employee table. To make the change made to the Employee
table, as permanent and visible to other users, you need to speciIy the query
shown in Listing 5.15.
INSERT INTO Employee VALUES (4001, `Nancy', `Marketing');
COMMIT;

Listing 5.15
Illustration of the COMMIT Statement
The result oI listing 5.15 is shown in Iigure 5.8.
Figure 5.8
Using the COMMIT Statement
Copyright 2006, Tata Consultancy Services Limited (TCS). 91
Understanding SQL using ORACLE Database Data ModiIication
ROLLBACK: This SQL statement undoes the changes made by the transaction to
the tables. You can use this SQL statement in case, you have speciIied wrong or
incorrect data values Ior a table. You can rollback the current transaction so that
the changes made to the tables are not made permanent and not visible to other
users. Like the COMMIT statement, ROLLBACK statement also indicates the
end oI a transaction. For example, you have speciIied incorrect values Ior the
empid Iield oI the Employee table. You need to undo this change to the
Employee table. For this, you need to speciIy the query as shown in listing 5.16.
INSERT INTO Employee VALUES (3444, `Ella', `Marketing');
ROLLBACK;
Listing 5.16
Illustration of the ROLLBACK Statement
The result oI listing 5.16 is shown in Iigure 5.9.
Figure 5.9
Using the ROLLBACK Statement
ROLLBACK TO SAVEPOINT: This SQL statement undoes the changes made to
the table by the current transaction but to a speciIic point. This point is called the
savepoint. In addition, this SQL statement undoes the changes in a backward
sequence, occurrence oI these changes. For example, you have made Iour changes
to the Employee table and have created a savepoint aIter the second change,
named as Secondchange. AIter this savepoint, you have made two other changes
to the Employee table. Now, you just want to revert back the last two changes
made in the table. For this, you can use the ROLLBACK TO SAVEPOINT
statement and rollback the last two transactions to the Secondchange savepoint.
The rollback that occurs using the ROLLBACK TO SAVEPOINT statement is
called partial rollback, as only some oI the changes made by the current
Copyright 2006, Tata Consultancy Services Limited (TCS). 92
Understanding SQL using ORACLE Database Data ModiIication
transaction are rolled back as compared to complete rollback, in which all the
changes oI the current transaction are rolled back.
SET TRANSACTION: This SQL statement is used Ior implementing
transaction-level or statement-level consistency. The SET TRANSACTION
statement consists oI two keywords, which are, ISOLATION LEVEL READ
COMMITTED and ISOLATION LEVEL SERIALIZABLE. ISOLATION
LEVEL READ COMMITTED is the deIault option with the SET
TRANSACTION statement and ensures statement-level consistency. The
ISOLATION LEVEL SERIALIZABLE option indicates transaction-level
consistency. In addition, you can use the SET TRANSACTION statement to
speciIy a rollback segment Ior transaction. This statement enables Oracle to
manage space requirements Ior large transactions. By deIault, Oracle uses the
round-robin algorithm to assign any rollback segment to large transactions. This
may cause rollback segments to increase in size and decrease the perIormance oI
the database. To avoid such situations and prevent the random assignment oI large
transactions to any rollback segment, you can start large transactions with the
SET TRANSACTION USE ROLLBACK SEGMENT rollback segment name~.

Copyright 2006, Tata Consultancy Services Limited (TCS). 93
Understanding SQL using ORACLE Database Data ModiIication
SUMMARY
To modiIy data stored in Oracle 9i database tables, SQL provides various
statements that are called as Data Manipulation Language (DML) statements.
Oracle 9i is a multi-user database, and enables multiple users to access and
modiIy the database, simultaneously
When multiple users change data simultaneously, it can result in the problem oI
data inconsistency.
The DML statements used Ior modiIying data in the tables are:
o INSERT
o UPDATE
o MERGE
o DELETE
The INSERT statement is used to insert rows in a table. In addition, you can add
rows to multiple tables using the INSERT statement.
SQL enables you to modiIy the existing data values oI a table using the UPDATE
statement.
SQL provides the MERGE statement that enables you to insert and update the
rows oI a table, simultaneously.
SQL provides the DELETE statement to remove those rows Irom a table that are
not required.
SQL provides the TRUNCATE command, which is used to remove all the rows
Irom the table.
The TRUNCATE statement is a Data DeIinition Language (DDL) statement. The
DDL statements are SQL statements that are used to deIine the database objects,
such as tables, views, and stored procedures.
To eliminate the problem oI data inconsistency, SQL provides the LOCK TABLE
statement.
The LOCK TABLE statement is used to lock a table Ior other users, so that you
are able to complete your operation on the table.
Oracle uses various types oI locks, which are:
Copyright 2006, Tata Consultancy Services Limited (TCS). 94
Understanding SQL using ORACLE Database Data ModiIication
o ROW SHARE (SS)
o ROW EXCLUSIVE (SX)
o SHARE (S)
o SHARE ROW EXCLUSIVE (SRX)
o EXCLUSIVE (X)
Deadlock is a situation that occurs when two transactions hold locks on a table
and each transaction is waiting Ior the other to release the lock.
Transactions can be deIined as the smallest unit oI work.
The process oI maintaining data consistency and controlling multiple transactions
is called transaction control.
Oracle uses Iour SQL statements to implement transaction control and ensure data
consistency:
o COMMIT
o ROLLBACK
o ROLLBACK TO SAVEPOINT
o SET TRANSACTION
Copyright 2006, Tata Consultancy Services Limited (TCS). 95
Understanding SQL using ORACLE Database Data ModiIication
SELF ASSESMENT
Q1) Fill in the blanks:
1. is a DML statement that is sued to insert and update
data values in a table.
2. statement is used to remove all the rows oI a table.
3. statement is used to end a transaction and save the changes
made by the transaction.
4. statements are SQL statements that are used to deIine the
database objects, such as tables, views, and stored procedures.
5. statement undoes the changes made to the table by the current
transaction but to a speciIic point
Q2) State true or Ialse:
1. Oracle 9i is a multi-user database but does not implement transaction control.
2. SET TRANSACTION is used to implement only transaction-level consistency.
3. Only 16 rows can be inserted in a table using a single INSERT statement.
4. EXCLUSIVE lock allows other types oI locks to be acquired Ior a table.
5. In case oI a deadlock situation, the Iirst transaction is completed whereas the
second transaction is cancelled.
6. ISOLATION LEVEL READ COMMITTED is the deIault option with the SET
TRANSACTION statement and ensures transaction-level consistency.
Copyright 2006, Tata Consultancy Services Limited (TCS). 96
Understanding SQL using ORACLE Database Understanding Advanced Queries
Understanding Advanced Queries
SCOPE
6.1 Using the SET Operators
6.1.1 The UNION Operator
6.1.2 The UNION ALL Operator
6.1.3 The INTERSECT Operator
6.1.4 The MINUS Operator
6.2 The CASE Statement
6.2.1 CASE Statement Using Value
6.2.2 CASE Statement Without Using Value
6.3 Using Hierarchical Queries
6.3.1 Clauses used with Hierarchical Queries
6.3.1.1 The START WITH Clause
6.3.1.2 The CONNECT BY PRIOR Clause
6.3.2 Using the ROLL UP Clause
6.4 Using Analytic Functions
6.4.1 Ranking Functions
6.4.1.1 The rank and denserank Functions
6.4.1.2 The cumedist and percentrank Functions
6.4.1.3 The NTILE Function
6.4.2 The Inverse Percentile Functions
6.4.3 The Windowing Functions
6.4.4 The Reporting Functions
Copyright 2006, Tata Consultancy Services Limited (TCS). 97
Understanding SQL using ORACLE Database Understanding Advanced Queries
6.1 Using the SET Operators
Oracle 9i provides set operators that enable you to combine two or more SQL queries
into a single statement. In addition, you can use the set operators to combine the result oI
multiple queries. The queries that contain set operators are also known as compound
queries. II multiple set operators exist in one query, then they are evaluated Irom leIt to
right. Oracle 9i provides Iour set operators, which are:
UNION
UNION ALL
INTERSECT
MINUS
6.1.1 The UNION Operator
The UNION operator returns all the rows selected by either query excluding the duplicate
rows. Consider an example, where you need to select the empno and ename oI all the
employees whose name starts with A or B. In the second query, you need to select the
empno and ename oI all the employees whose name starts with B or F. The UNION
operator Iilters the duplicate rows Irom both the queries and returns the result. To solve
this problem, you need to speciIy the query as shown in the listing 6.1.
Select empno, ename from emp where
Ename like `A%' or ename like `B%'
UNION
Select empno, ename from emp where
ename like `B%' or ename like `F%';
Listing 6.1
Illustration of UNION Operator
Figure 6.1
Result of Listing 6.1
Copyright 2006, Tata Consultancy Services Limited (TCS). 98
Understanding SQL using ORACLE Database Understanding Advanced Queries
6.1.2 The UNION ALL Operator
The UNION ALL operator returns all the rows selected by either query. Unlike the
UNION operator, this operator includes duplicate rows. In continuation oI the previous
example, you can also use the UNION ALL operator instead oI UNION operator. Using
the UNION ALL operator the name, BLAKE appears twice, as shown in the listing 6.2.
Select empno, ename from emp where
Ename like `A%' or ename like `B%'
UNION ALL
Select empno, ename from emp where
ename like `B%' or ename like `F%';
Listing 6.2
Illustration of UNION ALL Operator
Listing 6.2
Result of Listing 6.2
6.1.3 The INTERSECT Operator
The INTERSECT operator returns all the rows selected Irom both the queries. This
operator Iilters the rows that appear in both the Iirst and the second query. Consider an
example where you want to Iind the list oI managers whose name begins with C. To
solve this problem, you need to speciIy the query as shown in the listing 6.3.
Select ename, job from emp
where job = `MANAGER'
INTERSECT
Select ename, job from emp
Where ename like `C%';
Listing 6.3
Illustration of INTERSECT Operator
Copyright 2006, Tata Consultancy Services Limited (TCS). 99
Understanding SQL using ORACLE Database Understanding Advanced Queries
Figure 6.3
Result of Listing 6.3
6.1.4 The MINUS Operator
The MINUS operator returns all the rows selected by the Iirst query and excludes all the
rows selected Irom the second query. Consider an example where you need to Iind the list
oI all the employees except the employees whose job designation is CLERK. To solve
this problem, you need to speciIy the query as shown in the listing 6.4.
Select ename, job from emp
MINUS
Select ename, job from emp
where job = `CLERK';
Listing 6.4
Illustration of MINUS Operator
Figure 6.4
Result of Listing 6.4
Copyright 2006, Tata Consultancy Services Limited (TCS). 100
Understanding SQL using ORACLE Database Understanding Advanced Queries
6.2 The CASE Statement
Oracle 9i has introduced the CASE statement that is an alternative Ior the IF.THEN.
ELSE construct in SQL. The IF.THEN.ELSE construct is used to test a given
condition. II the given condition evaluates to true, the SQL statements Iollowing the IF
statement are executed. However, iI the given condition evaluates to Ialse, the SQL
statements Iollowing the ELSE statement are executed.
Like the IF.THEN.ELSE construct, the CASE statement is also used to test
conditions. However, with the CASE statement, you can test multiple conditions and are
quicker to code as compared to the IF.THEN.ELSE statement. You can test multiple
conditions using a single CASE statement. There are two types oI SQL CASE statements.
The Iirst type oI CASE statement takes the value whereas, the second type oI CASE
statement does not take a value on the CASE line. CASE line reIers to the Iirst line oI the
CASE statement.
6.2.1 CASE Statement Using Value
This type oI CASE statement takes value on the CASE line. This value is then compared
to each WHEN clause. The syntax Ior this CASE statement is:
CASE value
WHEN <compare value> THEN
<return value>
. . . .
[ELSE
<return value>]
END
Listing 6.5
Syntax of the CASE Statement Using Value
Consider a scenario where you need to set the value, Senior corresponding to job
designation, MANAGER and the value, Junior corresponding to job designation,
CLERK. You also need to set value, Other, corresponding to remaining job designations.
To do this, you need to enter the query shown in the listing 6.6.
Select ename, job,
CASE job WHEN `MANAGER' THEN `SENIOR'
WHEN `CLERK' THEN `Junior'
ELSE `Other' END
from EMP;
Listing 6.6
Illustration of CASE Statement
Copyright 2006, Tata Consultancy Services Limited (TCS). 101
Understanding SQL using ORACLE Database Understanding Advanced Queries
Figure 6.6
Result of Listing 6.6
6.2.2 CASE Statement Without Using Value
This type oI CASE statement does not take value on the CASE line. It evaluates each
expression in the WHEN clause and returns the value based on the Iirst condition Iound
TRUE. The syntax Ior this CASE statement is:
CASE
WHEN <condition> THEN <return value>
. .
[ELSE <return value>]
END
Listing 6.7
Syntax of the CASE Statement Without Using Value
Consider a scenario where you need to set the status oI the employee corresponding to
the amount oI salary given as:
II salary is ~ 5000 then status is HIGH.
II salary is 2000 then status is LOW.
II salary is 3500 then status is MEDIUM.
Copyright 2006, Tata Consultancy Services Limited (TCS). 102
Understanding SQL using ORACLE Database Understanding Advanced Queries
To do this, you need to enter the query as shown in the listing 6.8.
Select ename, deptno, sal,
CASE WHEN sal >= 5000 THEN `HIGH'
WHEN sal < 2000 THEN `LOW'
WHEN sal < 3500 THEN `MEDIUM'
END Status
From EMP;
Listing 6.8
Illustration of CASE Statement
Figure 6.7
Result of Listing 6.8
6.3 Using Hierarchical Queries
Oracle 9i has introduced the concept oI presenting the data in hierarchical order using
hierarchical queries. Hierarchical query allows you to select data and give the result in
hierarchical order. For example, in the employee table one column contains the list oI all
Copyright 2006, Tata Consultancy Services Limited (TCS). 103
Understanding SQL using ORACLE Database Understanding Advanced Queries
the employees working in an organization and other column contains the list oI managers
handling those employees. You, as a database administrator want to Iind out the
hierarchy oI employees working in a particular department. To accomplish this task, you
need to speciIy a hierarchical query.
6.3.1 Clauses used with Hierarchical Queries
The hierarchical query has two types oI clauses:
START WITH
CONNECT BY PRIOR
6.3.1.1 The START WITH Clause
In Oracle 9i, the START WITH clause seeks the row with which the hierarchy should
start. The syntax Ior using the START WITH clause is:
START WITH condition~
For example, iI you want to start the hierarchy Irom the employee name, SMITH, then
the syntax is:
START WITH ename = `SMITH'
Listing 6.9
Syntax of the START WITH Clause
6.3.1.2 The CONNECT BY PRIOR Clause
The CONNECT BY PRIOR clause allows you to relate one row to another. This clause
deIines the hierarchical relationship among rows. For example, you need to display the
hierarchy oI managers and the employees working under them. To do this, you need to
enter the query, shown in the listing 6.10.
Select lpad (` `, (level-1)*2, ` `) || ename ename
from emp;
START WITH ename = `KING'
CONNECT BY PRIOR empno = mgr;
Listing 6.10
Illustration of the CONNECT BY PRIOR Clause
Copyright 2006, Tata Consultancy Services Limited (TCS). 104
Understanding SQL using ORACLE Database Understanding Advanced Queries
Figure 6.8
Result of Listing 6.10
6.3.2 Using the ROLL UP Clause
Oracle 9i supports the ROLL UP clause that enables you to calculate multiple-level
subtotal oI speciIied number oI rows. ROLL UP clause can create the subtotal at any
level oI aggregation. This clause can also calculate the grand total. The syntax oI using
ROLL UP clause is:
SELECT ... GROUP BY ROLLUP(grouping_column_reference_list)
Listing 6.11
Syntax of the ROLL UP Clause
6.4 Using Analytic Functions
Analytic Iunctions are the Iunctions that returns the aggregate value based on the group
oI rows. These Iunctions are diIIerent Irom aggregate Iunctions as aggregate Iunctions
returns multiple rows Ior each group. There are Iour types oI analytic Iunctions, which
include:
Ranking Iunctions
Inverse Percentile Iunctions
Copyright 2006, Tata Consultancy Services Limited (TCS). 105
Understanding SQL using ORACLE Database Understanding Advanced Queries
Windowing Iunctions
Reporting Iunctions
6.4.1 Ranking Functions
This Iunction enables you to calculate the rank oI a speciIic record among the records
present in the dataset. The ranking Iunctions include:
rank and denserank
cumedist and percentrank
ntile
6.4.1.1 The rank and dense_rank Functions
Both these Iunctions rank data into groups but as compared to rank Iunction, the
denserank Iunction ranks the data contiguously. The rank and denserank Iunction is
shown with the help oI the given table:
Student Name Marks rank dense_rank
John 29 1 1
Nick 26 2 2
Mike 26 2 2
David 24 4 3
Mac 22 5 4
In this table, the rank oI David is 4 whereas the denserank oI David is 3. The syntax oI
rank Iunction is:
RANK ( ) OVER ( [query_partition_clause] order_by_clause)
Listing 6.12
Syntax of the rank Function
The syntax oI denserank Iunction is:
DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause )
Listing 6.13
Syntax of the dense_rank Function
6.4.1.2 The cume_dist and percent_rank Functions
These Iunctions enable you to examine the percentile calculations. The cumedist
Iunction is the cumulative distribution Iunction that is used to measure the ranking in a
grouped set and the rank value ranges Irom 0 to 1. The percentrank Iunction diIIers Irom
Copyright 2006, Tata Consultancy Services Limited (TCS). 106
Understanding SQL using ORACLE Database Understanding Advanced Queries
cumedist Iunction and is based on the row counts. Oracle 9i calculates the cumedist
Iunction based on the given Iormula:
Number oI values in set coming beIore the value / set size
The syntax oI cumedist is:
CUME_DIST ( ) OVER ( [query_partition_clause] order_by_clause )
Listing 6.14
Syntax of the cume_dist Function
Oracle 9i calculates percentrank Iunction based on the given Iormula:
Rank oI row within the partition 1/ number oI rows in the partition -1.
The syntax oI percentrank is:
PERCENT_RANK ( ) OVER ( [query_partition_clause] order_by_clause )
Listing 6.15
Syntax of the percent_rank Function
6.4.1.3 The NTILE Function
This Iunction enables you to split rows into desired number oI groups, also known as
buckets. For example, Irom the student table, you need to group the names oI all the
students based on their marks. In NTILE (n) Iunction, the rows are divided into buckets
ranging Irom 1 to n. and assigned appropriate bucket number to each row. Take an
example where there are 102 rows and you have mentioned NTILE (5). In this case, the
Iirst and second bucket will contain 21 rows each and third, Iourth, and IiIth bucket will
contain 20 rows each. The syntax oI NTILE Iunction is:
NTILE ( expr ) OVER ( [query_partition_clause] order_by_clause )
Listing 6.16
Syntax of the NTILE Function
6.4.2 The Inverse Percentile Functions
The cumedist Iunction enables you to calculate the percentile oI the set oI values. But it
is a tedious task to calculate the values based on a speciIic percentile. Even, the computed
value is not accurate. ThereIore, you can use inverse percentile Iunctions, such as
PERCENTILECONT and PERCENTILEDISC. These Iunctions take the percentile
value between 0 and 1. The PERCENTILECONT Iunction is a contiguous Iunction that
is calculated by interpolation. The PERCENTILEDISC Iunction proceeds step by step
and takes discrete values. The syntax oI inverse percentile Iunction is:
[PERCENTILE_CONT | PERCENTILE_DISC]( constant expression )
WITHIN GROUP ( ORDER BY single order by expression
Copyright 2006, Tata Consultancy Services Limited (TCS). 107
Understanding SQL using ORACLE Database Understanding Advanced Queries
[ASC|DESC] [NULLS FIRST| NULLS LAST])
Listing 6.17
Syntax of the Inverse Percentile Function
6.4.3 The Windowing Functions
This Iunction enables you to calculate moving and centred aggregates. This Iunction
calculates the values Ior all rows in the resulting data set. Windowing Iunctions include
various Iunctions, such as sum, moving min, moving max, cumulative sum, and statistical
Iunctions. The syntax oI windowing Iunction is:
{SUM|AVG|MAX|MIN|COUNT|STDDEV|VARIANCE|FIRST_VALUE|LAST_VALUE}
({value expression1 | *}) OVER
([PARTITION BY value expression2[,...])
ORDER BY value expression3 [collate clause>]
[ASC| DESC] [NULLS FIRST | NULLS LAST] [,...]
{ ROWS | RANGE }
{ BETWEEN
{ UNBOUNDED PRECEDING
| CURRENT ROW
| value_expr { PRECEDING | FOLLOWING }
}
AND
{ UNBOUNDED FOLLOWING
| CURRENT ROW
| value_expr { PRECEDING | FOLLOWING }
}
| { UNBOUNDED PRECEDING
| CURRENT ROW
| value_expr PRECEDING
}
}
Listing 6.18
Syntax of the Windowing Function
6.4.4 The Reporting Functions
Oracle 9i enables you to obtain the aggregate values aIter the query is being processed.
The aggregate values can include, number oI resulting rows or an average value in a
column. These values can be easily calculated within a partition and made available to
other reporting Iunctions. The reporting aggregate Iunction returns the same aggregated
value Ior each row in a partition. The syntax oI reporting Iunction is:
{SUM | AVG | MAX | MIN | COUNT | STDDEV | VARIANCE}
([ALL | DISTINCT] {<value expression1> | *})
OVER ([PARTITION BY <value expression2>[,...]])
Listing 6.19
Syntax of the Reporting Function
Copyright 2006, Tata Consultancy Services Limited (TCS). 108
Understanding SQL using ORACLE Database Understanding Advanced Queries
SUMMARY
The UNION operator returns all the rows selected by either query excluding
duplicate rows.
The UNION ALL operator returns all the rows selected by either query.
The INTERSECT operator returns all the rows selected Irom both queries.
The MINUS operator returns all the rows selected by Iirst query and exclude all
the rows selected Irom second query.
Oracle 9i has introduced the CASE statement that is alternate to IF.THEN.
ELSE logic in SQL.
Hierarchical query allows you to select data and give the result in hierarchical
order.
The hierarchical query has two types oI clauses:
o START WITH
o CONNECT BY PRIOR
Analytic Iunctions are the Iunctions that returns the aggregate value based on the
group oI rows.
There are Iour types oI analytic Iunctions, which include:
o Ranking Iunctions
o Inverse Percentile Iunctions
o Windowing Iunctions
o Reporting Iunctions
The ranking Iunctions include:
o rank and denserank
o cumedist and percentrank
o ntile
Copyright 2006, Tata Consultancy Services Limited (TCS). 109
Understanding SQL using ORACLE Database Understanding Advanced Queries
SELF ASSESSMENT
I. Fill up the blanks:
a) operator returns all the rows selected by either query excluding
duplicate rows
b) operator returns all the rows selected by either query.
c) operator returns all the rows selected Irom both queries.
d) operator returns all the rows selected by Iirst query and exclude all the
rows selected Irom second query.
e) Iunction enables you to split rows into desired number oI groups, also
known as buckets.
II. State True or False:
a) The ranking Iunction enables you to calculate moving and centred aggregates
b) The reporting aggregate Iunction returns the same aggregated value Ior each row in a
partition.
c) The NTILE Iunction enables you to examine percentile calculations.
d) The START WITH clause allows you to relate one row to another.
Copyright 2006, Tata Consultancy Services Limited (TCS). 110
Understanding SQL using ORACLE Database Managing Views
Managing Views
SCOPE
7.1 Creating and Updating Views
7.1.1 Creating Views
7.1.2 Creating Read-Only Views
7.1.3 Creating Views with Constraints
7.1.4 ModiIying Views
7.1.5 Dropping Views
7.1.6 Creating Views with Errors
7.2 Working with Views
7.2.1 Using Views in SQL Queries
7.2.2 Inserting, Updating, and Deleting Data using Views
7.2.3 Using Join Views
Copyright 2006, Tata Consultancy Services Limited (TCS). 111
Understanding SQL using ORACLE Database Managing Views
7.1 Creating and Updating Views
Large organizations daily access and modiIy diIIerent tables oI their database. In
addition, these tables are accessed and modiIied by multiple users simultaneously. For
example, tables, such as DailySalesReport and EmployeeDetails are accessed and
modiIied daily. To code a query Ior accessing the same data daily is a very tedious and
time-taking process. In addition, as a database administrator, you do not want that the
users should view all the data stored in a speciIic table, instead, the users should be able
to view only some columns oI a table. For such situations, Oracle 9i provides views,
which are logical representations oI data taken Irom one or more tables.
Views can be deIined as virtual tables that consist oI columns Irom one or more tables,
which are known as base tables. A view is called a virtual table, as it does not contain any
data oI its own, it just reIers to the speciIied columns oI the base tables. As a result, a
view does not utilize any storage space oI the database. In addition, views can also be
deIined as queries that are used to retrieve data Irom base tables. These queries are stored
in the Oracle data dictionary. Since, view consists oI columns that are speciIically
required by the users, it is also called customized representation oI data and are used Ior
purposes, such as:
EnIorcing security on the database: Views enable you to enIorce data security by
permitting the users oI the database to view only speciIied columns oI a table.
Improving the perIormance oI the database: Views ensure improved perIormance
oI the database, as views reduce the number oI queries that are directed to the
database.
Hiding the complexity oI the database Irom the users: Views hide the complexity
oI the tables and the database Irom the users and enable them to access only the
data required by them.
Implementing data abstraction: Views help the database administrator in
implementing data abstraction so that only the required data is viewed by the
users. As a result, rest oI the data remains inaccessible and secure.
Enabling customized representation oI data: Views enable the database
administrator to provide customized representation oI data that as is required by
diIIerent users oI the database.
7.1.1 Creating Views
SQL provides the CREATE VIEW statement to create a view. The syntax oI the
CREATE VIEW statement is shown in listing 7.1.
CREATE VIEW <view name>
AS
<Query>
Listing 7.1
Syntax of the CREATE VIEW Statement
Copyright 2006, Tata Consultancy Services Limited (TCS). 112
Understanding SQL using ORACLE Database Managing Views
In the syntax oI the CREATE VIEW statement, the query speciIies the columns and the
tables that are reIerenced by the speciIied view.
For example, as a database administrator, you want that the users should only be able to
view the empid and the empname oI the Employee table. For this need to create a
view, named as empview, as shown in listing 7.2.
CREATE VIEW emp_view
AS
SELECT emp_id, emp_name FROM Employee;
Listing 7.2
Illustration of the CREATE VIEW Statement
The result oI the listing 7.2 is shown in Iigure 7.1.
Figure 7.1
Using the CREATE VIEW Statement
To view the data stored in the view, empview, you can speciIy the SQL query, as shown
in Iigure 7.2.
Figure 7.2
Data Stored in the View, Emp_view
You can define up to 1000 columns for a view.
Copyright 2006, Tata Consultancy Services Limited (TCS). 113
Understanding SQL using ORACLE Database Managing Views
While creating views, vou can specifv the required column names after the view
name so that vou can different column names in the view.
7.1.2 Creating Read-Only Views
In an organization, some oI the data, such as the sales Iigures oI the previous month or
the details oI the employees, is just Ior viewing and cannot be modiIied by all the users.
Such data can only be modiIied either by the database administrator or the users having
the required privileges and rights. However, users may require data only Ior reading or
viewing purpose. As a database administrator, you need to make such data accessible to
other users and ensure that these users do not modiIy the data. For such data, you can
create read-only views.
The syntax to create a read-only view is shown in listing 7.3:
CREATE VIEW <view name>
AS
<Query>
WITH READ ONLY;
Listing 7.3
Syntax for Creating a Read-Only View
For example, you need to create a read-view that is based on the Employee table. The
query Ior this is shown in listing 7.4.
CREATE VIEW emp_view2
AS
SELECT emp_id, dept FROM Employee
WITH READ ONLY;
Listing 7.4
Illustration of Creating a Read-Only View
The result oI the query shown in listing 7.4 is shown in Iigure 7.3.
Figure 7.3
Using the READ-ONLY Option
Copyright 2006, Tata Consultancy Services Limited (TCS). 114
Understanding SQL using ORACLE Database Managing Views
To view the data stored in the read-only view, empview2, you can speciIy the SQL
query, as shown in Iigure 7.4.
Figure 7.4
Data Stored in the Read-Only View, Emp_view2
7.1.3 Creating Views with Constraints
You can create views that have constraints applied on them. However, the constraints
applied on the views are not enIorced constraints, these constraints are declarative
constraints. ThereIore, to enIorce constraints on the views, you need to apply the
constraints on the base table. The base table is the table on which the view is based and
the view reIerences the columns oI this table. In addition, while applying constraints on
the views, you need to use the DISABLE NOVALIDATE clause in the query. You can
deIine the FOREIGN KEY, PRIMARY KEY, and the UNIQUE KEY constraints on the
views. However, the syntax oI creating a constraint Ior a view is same as the syntax oI
creating a constraint Ior a table.
7.1.4 Modifying Views
Oracle 9i enables you to modiIy the existing views, as per the changes in your
requirements. Oracle 9i enables you to modiIy the deIinition oI the existing view using
the CREATE VIEW statement with the OR REPLACE clause. In addition, you can use
the ALTER VIEW statement to compile an invalid view. You can use the ALTER VIEW
statement to add or drop constraints Irom views.
To modiIy the deIinition oI an existing view, you need to use the CREATE VIEW
statement with the OR REPLACE clause. The syntax oI the CREATE VIEW statement
with the OR REPLACE clause is shown in listing 7.5.
Copyright 2006, Tata Consultancy Services Limited (TCS). 115
Understanding SQL using ORACLE Database Managing Views
CREATE OR REPLACE VIEW <view name>
AS
<Query>;
Listing 7.5
Syntax of the CREATE VIEW Statement with the OR REPLACE Clause
When you use the OR REPLACE clause with an existing view, the new deIinition oI the
view replaces the existing deIinition oI the speciIied view. In case the speciIied view
does not exist, a new view will be created. Moreover, when you use the OR REPLACE
clause oI the CREATE VIEW statement, the privileges assigned to the existing view are
automatically assigned to the modiIied view.
For example, you need to modiIy the deIinition oI the view, empview, which is based on
the Employee table. The query Ior this is shown in listing 7.6.
CREATE OR REPLACE VIEW emp_view
AS
SELECT emp_id, dept FROM Employee;
Listing 7.6
Illustration of the CREATE VIEW Statement with the OR REPLACE Clause
The result oI the query shown in listing 7.6 is shown in Iigure 7.5.
Figure 7.5
Using the OR REPLACE Clause of the CREATE VIEW Statement
To view the data stored in the modiIied view, you can speciIy the SQL query, as shown
in Iigure 7.6.
Copyright 2006, Tata Consultancy Services Limited (TCS). 116
Understanding SQL using ORACLE Database Managing Views
Figure 7.6
Data Stored in the Modified View, Emp_view
You can also use the ALTER VIEW statement to recompile an invalid view. Invalid
views are those views whose base tables have been altered. When the base tables are
altered, the views that are based on these tables become invalid. When a view becomes
invalid, Oracle 9i automatically recompiles the invalid view. However, SQL provides the
ALTER VIEW statement to recompile an invalid view.
The syntax oI the ALTER VIEW statement that is used to recompile an invalid view is
shown in listing 7.7.
ALTER VIEW <view name> compile;
Listing 7.7
Syntax of ALTER VIEW Statement
For example, you have modiIied the Employee table, and included a new column named,
Salary. In this situation, the view, empview becomes invalid, as the base table has been
altered. ThereIore, you need to recompile this view to make it a valid view. The query Ior
this is shown in listing 7.8.
ALTER VIEW emp_view compile;
Listing 7.8
Illustration of the ALTER VIEW Statement
The result oI the query shown in listing 7.8 is shown in Iigure 7.7.
Copyright 2006, Tata Consultancy Services Limited (TCS). 117
Understanding SQL using ORACLE Database Managing Views
Figure 7.7
Recompiling an Invalid View
7.1.5 Dropping Views
You can delete views that are not required using the DROP VIEW statement. When a
view is dropped, the deIinition oI the view is dropped Irom the dictionary. In addition, the
privileges and the rights associated with the dropped view are also dropped. However,
when you drop a view, other views that reIer to the dropped view, are rendered invalid.
The syntax oI the DROP VIEW statement is shown in listing 7.9.
DROP VIEW <view name>;
Listing 7.9
Syntax of the DROP VIEW Statement
For example, you need to drop the view, empview2, which is based on the Employee
table. The query Ior this is shown in listing 7.10.
DROP VIEW emp_view2;
Listing 7.10
Illustration of the DROP VIEW Statement
The result oI the query shown in listing 7.10 is shown in Iigure 7.8.
Figure 7.8
Using the DROP VIEW Statement
7.1.6 Creating Views with Errors
Copyright 2006, Tata Consultancy Services Limited (TCS). 118
Understanding SQL using ORACLE Database Managing Views
Oracle 9i provides the Iunctionality to create views with errors. Views with errors are
those views, Ior which the base tables have not been created. Generally, when you create
a view and the table, which the view reIerences, has not been created, the speciIied view
is not created and Oracle generates an error. However, you can create an erroneous view
Ior which the base table has not been created, using the CREATE VIEW statement with
the FORCE clause. However, by deIault, the NO FORCE option is used with the
CREATE VIEW statement. In addition, the view created with the FORCE option will be
invalid till the base tables are created. When the base tables are created, the invalid view
needs to be recompiled to make it a valid view.
For example, you plan to create a table named, Customer, but beIore that you need to
create a view based on the Customer table, named as Custview1. The Iields oI the
Customer table are:
CustID Number(5)
CustName Varchar2(12)
CustAge Number(2)
CustAddress1 Varchar2(12)
CustAddress2 Varchar2(12)
CustCity Varchar2(12)
CustPhoneNo Number(10)
CustMembership Boolean
The Iields oI the view, Custview1 are:
CustID Number(5)
CustName Varchar2(12)
CustPhoneNo Number(10)
CustMembership Boolean
The listing 7.11 shows the SQL query to create a view with errors.
CREATE FORCE VIEW Cust_view1 AS
SELECT Cust_ID, Cust_Name_Cust_PhoneNo, Cust_Membership
FROM Customer;
Listing 7.11
Using the FORCE Option
The result oI the query shown in listing 7.11 is shown in Iigure 7.9.
Copyright 2006, Tata Consultancy Services Limited (TCS). 119
Understanding SQL using ORACLE Database Managing Views
Figure 7.9
Using the FORCE Option
Now, when you try to access the view, Custview1, SQL generates a message, as shown
in Iigure 7.10.
Figure 7.10
Accessing the View, Cust_view1
7.2 Working with Views
Views are used to present a small portion oI data stored in the table. This ensures that the
data in the table is secured Irom unnecessary modiIications. This is because, Oracle is a
multi-user database, and enables multiple users to access the database, simultaneously.
Simultaneous access and modiIication oI data by multiple users can lead to the problem
oI data inconsistency.
Views allow access to only that part oI the data, which is required by the users. As a
result, the data in the tables is secured. In addition, views can be used to hide complex
joins applied on the tables oI the database. This enables the users to view and access the
required data without understanding the joins used on the tables. Views also ensure that
the data in the tables in not modiIied Irequently.
However, like the tables oI a database, views can also be used in queries. In addition, you
can use the views to insert, update, and delete data.
Copyright 2006, Tata Consultancy Services Limited (TCS). 120
Understanding SQL using ORACLE Database Managing Views
7.2.1 Using Views in SQL Queries
Like tables, you can use views in SQL queries and sub-queries. In addition, you can use
all the SQL Iunctions, such as number, character, Date/Time, and conversion, in the SQL
query that retrieves data Irom a view.
For example, you have created a view, as EDetails. The Iields oI this view are:
Empid
Empname
Salary
This view is based on the table, EmpDetails.
Now, you want to view the sum oI the Salary Iield, Ior those employees, whose salary is
greater than 12000. The SQL query Ior this is shown in Iigure 7.12.
SELECT SUM(salary) FROM E_details
WHERE salary > 12000;
Listing 7.12
Using Views in SQL Queries
The result oI the query shown in listing 7.12 is shown in Iigure 7.11.
Figure 7.11
Using Views in SQL Queries
7.2.2 Inserting, Updating, and Deleting Data using Views
You can use views to insert, delete, and update data in the tables. However, inserting,
updating, and deleting data using views has certain restrictions. You can insert, update,
and delete data using views, only iI the view deIinition does not contain the given
clauses:
Copyright 2006, Tata Consultancy Services Limited (TCS). 121
Understanding SQL using ORACLE Database Managing Views
DISTINCT clause
GROUP BY clause
START WITH clause
CONNECT by clause
ROWNUM clause
Set operators, which are UNION, UNION ALL, INTERSECT, or MINUS
Subquery in the SELECT clause
However, the DML operations, such as insert, update, or delete are perIormed on the base
table, on which the view is created. For example, you have created a table, Department,
and the Iields oI this table are:
DeptID, Number(4)
DeptName, Varchar2(10)
Strength, Number(3)
DeptHead, Varchar2(12)
Now, you want to create a view, DeptView1, based on the Department table. The Iields
oI this view are:
DeptID
DeptName
Figure 7.12 displays the SQL query to create the view, DeptView1.
Figure 7.12
Creating the View, Dept_View1
Now, you can use the view, DeptView1 to insert a row in the table, Department. The
SQL query Ior this is shown in listing 7.13.
INSERT INTO Dept_View1
VALUES (2020, `Payroll');
Listing 7.13
Using Views to Insert Data

The query shown in listing 7.14 inserts a new row in the Department table, as shown in
Iigure 7.13.
Copyright 2006, Tata Consultancy Services Limited (TCS). 122
Understanding SQL using ORACLE Database Managing Views
Figure 7.13
Using Views to Insert Data
To view the newly inserted row in the Department table, you need to speciIy the query as
shown in listing 7.14.
SELECT * FROM Department;
Listing 7.14
Viewing the Inserted Row
The result oI the query shown in listing 7.14 is shown in Iigure 7.14.
Figure 7.14
The Records of the Department Table
7.2.3 Using 1oin Views
Join views are views that reIerence two base tables. Join views are based on the Iact that
both the base tables have a common Iield. For example, you have created two tables,
Employee and Department. The primary key oI the Employee table is Empid and is the
Ioreign key oI the Department table. ThereIore, you can create a view that can reIerence
both the Employee and the Department tables.
Join views can also be used to update the base tables. When a join view is used to update
the base tables, it is known as the updatable join view. However, an updatable join view
can only update one base table, in a single SQL query.
For example, you have created two tables, EmpDetails and Department. The Iields oI
the Employee table are:
Copyright 2006, Tata Consultancy Services Limited (TCS). 123
Understanding SQL using ORACLE Database Managing Views
EmpID, which is the primary key oI this table
EmpName
DeptName
Salary
The Iields in the Department table are:
DeptID, which is the primary key oI this table
DeptName
Strength
Now, you need to create a join view that reIerences both the EmpDetails and the
Department table. The SQL query Ior this is shown in listing 7.15.
Create or replace view View1
AS
SELECT a.dept_id, a.dept_name, b.emp_id, b.emp_name
FROM Department a, Emp_Details b
WHERE a.dept_name = b.dept_name
Listing 7.15
Illustration of a 1oin View
The result oI the SQL query shown in listing 7.15 is shown in Iigure 7.15.
Figure 7.15
Creating a 1oin View
To view the data stored in the join view, View1, you need to speciIy the SQL query
shown in Iigure 7.16.
Copyright 2006, Tata Consultancy Services Limited (TCS). 124
Understanding SQL using ORACLE Database Managing Views
Figure 7.16
Viewing a 1oin View, View1
Copyright 2006, Tata Consultancy Services Limited (TCS). 125
Understanding SQL using ORACLE Database Managing Views
SUMMARY
Views can be deIined as virtual tables that consist oI columns Irom one or more
tables, which are known as base tables.
A view is called a virtual table, as it does not contain any data oI its own, it just
reIers to the speciIied columns oI the base tables.
Views cam also be deIined as queries that are used to retrieve data Irom base
tables.
View consists oI columns that are speciIically required by the users, it is also
called customized representation oI data and are used Ior the purposes, such as:
o EnIorcing security on the database
o Improving the perIormance oI the database
o Hiding the complexity oI the database Irom the users
o Implementing data abstraction
o Enabling customized representation oI data
SQL provides the CREATE VIEW statement to create a view.
SQL enables you to create read-only views, which ensure that the users do not
modiIy the data oI the view.
You can create views that have constraints applied on them. However, the
constraints applied on the views are not enIorced constraints, these constraints are
declarative constraints.
To enIorce constraints on the views, you need to apply the constraints on the base
table.
Oracle 9i enables you to modiIy the deIinition oI the existing view using the
CREATE VIEW statement with the OR REPLACE clause.
You can use the ALTER VIEW statement to add or drop constraints Irom views.
You can also use the ALTER VIEW statement to recompile an invalid view.
Invalid views are those views whose base tables have been altered.
When the base tables are altered, the views that are based on these tables become
invalid. When a view becomes invalid, Oracle 9i automatically recompiles the
invalid view.
Copyright 2006, Tata Consultancy Services Limited (TCS). 126
Understanding SQL using ORACLE Database Managing Views
You can delete views that are not required using the DROP VIEW statement.
Views with errors are those views, Ior which the base tables have not been
created.
You can create an erroneous view Ior which the base table has not been created,
using the CREATE VIEW statement with the FORCE clause.
Views are used to present a small portion oI data stored in the table. This ensures
that the data in the table is secured Irom unnecessary modiIications.
Like tables, you can use views in SQL queries and sub-queries.
You can use views to insert, delete, and update data in the tables.
You can insert, update, and delete data using views, only iI the view deIinition
does not contain the given clauses:
o DISTINCT clause
o GROUP BY clause
o START WITH clause
o CONNECT by clause
o ROWNUM clause
o Set operators, which are UNION, UNION ALL, INTERSECT, or MINUS
o Subquery in the SELECT clause
Join views are views that reIerence two base tables. Join views are based on the
Iact that both the base tables have a common Iield.
Copyright 2006, Tata Consultancy Services Limited (TCS). 127
Understanding SQL using ORACLE Database Managing Views
SELF-ASSESMENT
Q1) Fill in the blanks:
1. are views that reIerence two base tables.
2. Views can be deIined as that consist oI columns Irom one or more
tables, which are known as .
3. You can deIine up to columns Ior a view.
4. While applying constraints on the views, you need to use the
clause in the query.
5. Oracle 9i enables you to modiIy the deIinition oI the existing view using the
statement with the clause.
Q2) State true or Ialse:
1. You cannot deIine the PRIMARY KEY constraint on a view.
2. The ALTER VIEW statement is used to recompile an invalid view.
3. You can create a view Ior which the base table has not been created.
4. Character Iunctions cannot be used with views.
5. The DML operations, such as insert, update, or delete are perIormed on the base
table, on which the view is created.
Copyright 2006, Tata Consultancy Services Limited (TCS). 128
Understanding SQL using ORACLE Database Understanding Data Objects
Understanding Database Objects
SCOPE
Creating and Administering Sequences
8.1.1 Creating and Dropping Sequences
8.1.2 Using Sequences
8.1.3 Initialising Sequences
8.1.4 Missing Sequence Values
8.1.5 Minimum and Maximum Values
Creating and Managing Synonyms
8.2.1 Public Synonym
8.2.2 Private Synonym
Resolving Object ReIerences
Creating Indexes
8.4.1 B-Tree Indexes
8.4.2 Bitmap Indexes
Copyright 2006, Tata Consultancy Services Limited (TCS). 129
Understanding SQL using ORACLE Database Understanding Data Objects
8.1 Creating and Administering Sequences
Sequence is a database object that enables you to generate a unique sequence number
corresponding to each row in a table. These sequence numbers act as the primary key Ior
each record in the table. There is another method, called serialization that generates the
sequence number by incrementing the last generated number by 1. But this method
adversely aIIects the perIormance oI an application, as you need to lock the table beIore
generating the sequence number. ThereIore, you can use sequences, in which you do not
need to lock the table while generating the sequence number. These generated numbers
are independent oI any table and exist only in the data dictionary.
8.1.1 Creating and Dropping Sequences
To create a sequence, you need to use the CREATE SEQUENCE statement. The syntax
Ior creating sequence is shown in listing 8.1.
CREATE SEQUENCE Emp_sequence
INCREMENT BY <value>
START WITH <value>
NOMAXVALUE
NOCYCLE
CACHE <value>;
Listing 8.1
Syntax for Creating Sequence
The keywords that are used to create a sequence are:
INCREMENT BY: SpeciIies the value by which the succeeding generated
number will increase or decrease. By deIault, the value is 1. To speciIy the
sequence in descending order, you need to use negative INCREMENT BY value.
START WITH: SpeciIies the value by which the sequence will start. By deIault,
the value is 1.
MINVALUE: SpeciIies the minimum value up to which sequence will be
generated. By deIault, the MINVALUE is NOMINVALUE. The MINVALUE
evaluates to 1 in case oI increasing sequence and -10
26
in case oI decreasing
sequence
MAXVALUE: SpeciIies the maximum value up to which sequence will be
generated. By deIault, MAXVALUE IS NOMAXVALUE. The MAXVALUE
evaluates to 10
27
in case oI increasing sequence and -1 in case oI decreasing
sequence.
CYCLE: Customizes the sequence to start the repetition oI sequence numbers
aIter reaching the deIined value.
NOCYCLE: Customizes the sequence Ior not repeating the numbers aIter
reaching the deIined value.
Copyright 2006, Tata Consultancy Services Limited (TCS). 130
Understanding SQL using ORACLE Database Understanding Data Objects
CACHE: SpeciIies the size oI the block in which sequence numbers are stored.
By deIault, cache size is 20.
NOCACHE: Allows the data dictionary to be automatically updated every time a
sequence number is generated. It also makes sure that there should be no gap in
the generated numbers.
You can also remove the sequence by using the DROP SEQUENCE statement. The
syntax Ior removing sequence is shown in listing 8.2.
DROP SEQUENCE sequence_name
Listing 8.2
Syntax for Dropping a Sequence
8.1.2 Using Sequences
For using sequences, you need to get the last generated number and in continuation with
the last generated number, you need to access the next number in the sequence. You can
get the last generated number using the pseudo-column, CURRVAL. You can also access
the next number in the sequence using the pseudo-column, NEXTVAL.
The syntax Ior accessing the next sequence number is shown in listing 8.3
sequence_name.nextval
Listing 8.3
Syntax for Accessing the Next Sequence Number
The syntax Ior getting the last generated sequence number is shown in listing 8.4.
sequence_name.currval
Listing 8.4
Syntax for Getting the Last Generated Sequence
8.1.3 Initialising Sequences
II a new sequence number has not been generated in a session, then CURRVAL will be
undeIined. ThereIore, you need to initialise the sequence by selecting NEXTVAL beIore
selecting CURRVAL. For example, you need to create the new sequence, seq and select
the CURRVAL Irom that sequence, as shown in the Iigure 8.1.
Copyright 2006, Tata Consultancy Services Limited (TCS). 131
Understanding SQL using ORACLE Database Understanding Data Objects
Figure 8.1
Creating Sequence
ThereIore, while initialising a sequence within a session, you need to select NEXTVAL
beIore selecting CURRVAL, as shown in the Iigure 8.2.
Figure 8.2
Initialising a Sequence
8.1.4 Missing Sequence Values
You might Iace a problem oI losing the sequence values whenever rollback occurs. The
NEXTVAL enables you to access the next sequence number. AIter you rollback the
transaction and again update the database, the last generated sequence values disappear.
This will create a gap between the sequences generated in multiple sessions. For
example, you have the table name, employees with the columns, empid, empname, and
dept, as shown in Iigure 8.3.
Figure 8.3
Employee Table
Generate the sequence corresponding to each row in a table. To do this, enter the query as
shown in listing 8.5.
Update employee SET emp_id = emp_seq.nextval;
Listing 8.5
Copyright 2006, Tata Consultancy Services Limited (TCS). 132
Understanding SQL using ORACLE Database Understanding Data Objects
Generating Sequence
Figure 8.4
Result of Listing 8.5
The sequence will be generated Irom 21 to 25, corresponding to each row in a table, as
shown in Iigure 8.5.
Figure 8.5
Sequence Generated Against Each Row
Let`s suppose, an error has occurred in a database and you need to rollback the
transactions. ThereIore, aIter the transaction is rolled back and when you again generate
the sequence Ior the Employee table, it will generate the sequence Irom 26 to 30, as
shown in Iigure 8.6.
Figure 8.6
New Sequence Generated Against Each Row
Copyright 2006, Tata Consultancy Services Limited (TCS). 133
Understanding SQL using ORACLE Database Understanding Data Objects
8.1.5 Minimum and Maximum Values
There might be situations where the sequence reaches the MAXVALUE or MINVALUE
deIined by you. II a sequence is created with NOCYCLE and you select NEXTVAL aIter
the sequence reaches MAXVALUE, then an error will be generated as shown in Iigure
8.7.
Figure 8.7
Creating Sequence With MAXVALUE 5
8.2 Creating and Managing Synonyms
Synonym is another name used Ior the database objects, such as table, sequence, or view.
Synonyms are used to hide the original name and location oI the database objects. In
addition, you can also assign a synonym to database objects so that their names are easier
to remember. Synonyms are oI two types:
Public synonym
Private synonym
8.2.1 Public Synonym
Public synonym is used to recognize commonly used objects, such as tables, views,
sequences, and Iunctions. Public synonyms are available to all the users and do not
require an owner name attached to them. The syntax Ior creating public synonym is
shown in listing 8.6.
CREATE [PUBLIC] SYNONYM synonym_name
FOR [schema.]object[@db_link];
Listing 8.6
Syntax for Creating a Public Synonym
For example, you want to create a synonym, dept Ior the table, department. To do this,
you need to enter the query shown in listing 8.7.
CREATE PUBLIC SYNONYM dept
Copyright 2006, Tata Consultancy Services Limited (TCS). 134
Understanding SQL using ORACLE Database Understanding Data Objects
FOR department;
Listing 8.7
Illustration for Creating a Public Synonym
To remove the public synonym, you need to use DROP SYNONYM statement. The
syntax Ior dropping a public synonym is shown in listing 8.8.
DROP [PUBLIC] SYNONYM synonym_name;
Listing 8.8
Syntax for Dropping a Public Sequence
8.2.2 Private Synonym
You can create private synonyms on all the objects owned by you or other users. These
synonyms are available to the owner, who have created the synonyms or to the user
having privileges granted by the owner. You can use private synonyms in those cases
where the table is renamed and both the old and new names are required. You can create
synonyms with either old or new name or both that reIer to the same object. The syntax
Ior creating a private synonym is shown in listing 8.9.
CREATE SYNONYM synonym_name FOR tablename;
Listing 8.9
Syntax for Creating a Private Synonym
For example, you want to create a private synonym, empl Ior the table employee. To do
this, you need to enter the query, as shown in listing 8.10.
CREATE SYNONYM empl FOR employee;
Listing 8.10
Illustration for Creating Private Synonym
Figure 8.8
Result of Listing 8.10
8.3 Resolving Object References
There might be situations where you might not be able to reIer an object, such as table,
view, procedure, or Iunction. ThereIore, Oracle 9i allows you to resolve these reIerenced
objects in this order:
Object owned by the current user
Copyright 2006, Tata Consultancy Services Limited (TCS). 135
Understanding SQL using ORACLE Database Understanding Data Objects
Private synonym owned by the current user
Public synonym
8.4 Creating Indexes
Indexes are the schema objects that provide direct and Iast access to rows oI a table.
Indexes speed up the process oI data retrieval that Iurther improves the perIormance oI
the database. Oracle accesses the rows Irom the table by any oI the two methods:
ROWID: Is the physical address oI a row in a table.
Full-table Scan: Is a method oI scanning each row oI the table.
There are two types oI indexing technologies:
B-Tree Indexes
Bitmap Indexes
8.4.1 B-Tree Indexes
B-Tree index is a database object that arranges data in a binary tree Iormat. This
technique is useIul on the columns having distinct values. For example, in the employee
table the column containing phone numbers has the most distinct values. The B-Tree is
built with branch blocks and leaI blocks. The branch block contains the key and the
address to another index block. The leaI block contains the key and the ROWID
corresponding to each row in a table. For example, you want to select the employee name
whose manager id is 7788. To do this, you need to enter the query, as shown in listing
8.11.
Select ename from emp
Where mgr = 7788;
Listing 8.11
Illustration for Searching an Employee Name
Figure 8.9
Result of Listing 8.11
8.4.2 Bitmap Indexes
Bitmap index is a database object that arranges the data in a series oI bitmaps. These
indexes are useIul where there are low-to-medium cardinality columns. The bitmap
Copyright 2006, Tata Consultancy Services Limited (TCS). 136
Understanding SQL using ORACLE Database Understanding Data Objects
indexes can be oI single or multiple columns. The multiple bitmap indexes can be
combined with AND and OR conditions. For each key value there is a bitmap that
contains a TRUE, FALSE, or NULL value corresponding to each row in a table. The
bitmap structure is shown in Iigure 8.10.
Figure 8.10
Bitmap Structure
For example, you, as a database administrator oI an organization want to Iind the name oI
the employees whose job description is either MANAGER or ANALYST and salary oI
that employee is between 2000 and 2500. To do this, you need to enter the query, shown
in listing 8.12.
Select ename from emp
Where job in (`MANAGER', `ANALYST')
AND sal BETWEEN 2000 AND 2500'
Listing 8.12
Illustration for Searching an Employee Name
Copyright 2006, Tata Consultancy Services Limited (TCS). 137
Printer
Monitor
Scanner
Processor
1
1
1
0
0
0
0
0
0
1
1
0
0
0
0
0
0
1
0
0
0
0
0
0
AAAHuCAAAXMFyAAA
AAAHuCAAAXMFyAAB
AAAHuCAAAXMFyAAC
AAAHuCAAAXMFyAAD
AAAHuCAAAXMFyAAE
AAAHuCAAAXMFyAAF
Bitmap
Printer Monitor Scanner Processor
Understanding SQL using ORACLE Database Understanding Data Objects
Figure 8.11
Result of Listing 8.12
Copyright 2006, Tata Consultancy Services Limited (TCS). 138
Understanding SQL using ORACLE Database Understanding Data Objects
SUMMARY
Key points covered in this chapter are:
Sequence is a database object that enables you to generate a unique sequence
number corresponding to each row in a table.
These sequence numbers act as the primary key Ior each record in the table.
To create sequence, you need to use CREATE SEQUENCE statement.
The keywords that are used to create a sequence are:
o INCREMENT BY
o START WITH
o MINVALUE
o MAXVALUE
o CYCLE
o NOCYCLE
o CACHE
o NOCACHE
For using sequences, you need to get the last generated number and in
continuation with the same you need to access the next number in the sequence.
You can get the last generated number using pseudo-column, CURRVAL.
You can also access the next number in the sequence using pseudo-column,
NEXTVAL.
You need to initialise the sequence by selecting NEXTVAL beIore selecting
CURRVAL.
Synonym is another name Ior the database objects, such as table, sequence, or
view.
Synonyms are used to hide the original name and location oI the database objects.
Synonyms are oI two types:
o Public Synonym
o Private Synonym
Public synonym is used to recognize commonly used objects, such as tables,
views, sequences, and Iunctions.
To remove the public synonym, you need to use DROP SYNONYM statement.
You can create private synonyms on all the objects owned by you or other users.
Private synonyms are available to the owner, who have created the synonyms or
to the user having privileges granted by the owner.
Indexes are the schema objects that provide direct and Iast access oI rows Irom
the table.
Copyright 2006, Tata Consultancy Services Limited (TCS). 139
Understanding SQL using ORACLE Database Understanding Data Objects
Oracle accesses the rows Irom the table by any oI the two methods:
o ROWID
o Full-table Scan
B-Tree index is a database object that arranges the data in a binary tree Iormat.
This technique is useIul on the columns having distinct values.
Bitmap index is a database object that arranges the data in a series oI bitmap.
These indexes are useIul where there are low-to-medium cardinality columns.
Copyright 2006, Tata Consultancy Services Limited (TCS). 140
Understanding SQL using ORACLE Database Understanding Data Objects
SELF ASSESSMENT
I. Fill up the blanks:
a) is a database object that enables you to generate a unique sequence
number corresponding to each row in a table.
b) speciIies the value by which the succeeding generated number will
increase or decrease.
c) customizes the sequence to start the repetition oI sequence numbers aIter
reaching the deIined value.
d) are the schema objects that provide direct and Iast access oI rows Irom
the table.
e) synonyms are available to the owner, who have created the synonyms
or to the user having privileges granted by the owner.
II. State True or False:
a) You can remove the sequence by using REMOVE SEQUENCE statement.
b) B-Tree index is a database object that arranges the data in a series oI bitmap.
c) ROWID is the physical address oI a row in a table.
d) Private synonym is used to recognize commonly used objects, such as tables, views,
sequences, and Iunctions.
Copyright 2006, Tata Consultancy Services Limited (TCS). 141
Understanding SQL using ORACLE Database User Access and Security
User Access and Security
SCOPE
User Accounts and Roles
9.1.1 Creating and ModiIying User Accounts
9.1.1.1 ConIiguring Account Authentication
9.1.1.1.1 DeIault Authentication
9.1.1.1.2 External Authentication
9.1.1.1.3 Global Authentication
9.1.1.2 Assigning Attributes
9.1.1.2.1 Assigning a DeIault Tablespace
9.1.1.2.2 Assigning a Temporary Tablespace
9.1.1.2.3 Using ProIiles
9.1.1.3 Account Licensing Controls
9.1.1.4 Creating Roles
Assigning Privileges
9.2.1 Object Privileges
9.2.2 System Privileges
9.2.3 Assigning Privileges
9.2.4 Revoking Privileges
9.2.5 Viewing Privileges
Administering User Groups Using ProIiles
9.3.1 Resource Settings
9.3.2 Creating and Altering ProIiles
9.3.2.1 Kernel Resource Setting
9.3.2.2 Password Resource Setting
Copyright 2006, Tata Consultancy Services Limited (TCS). 142
Understanding SQL using ORACLE Database User Access and Security
9.1 User Accounts and Roles
Oracle 9i is a multi-user database that allows you to restrict or speciIy what a user can do
with the database objects. For this, you need to assign privileges to each user based on
their role in an organization. For example, you, as a database administrator want that only
the HR manager should be able to modiIy records in the employee table and other HR
executives should only be able to view it. In addition, you want that the employees in the
Marketing department should not be able to view the records oI the employee table. So,
you need to create a user account to assign the rights and privileges to speciIic users.
9.1.1 Creating and Modifying User Accounts
Oracle 9i enables you to create a user account. For creating a user account, you need to
use CREATE USER statement. Oracle 9i also enables you to alter the user account by
assigning multiple attributes to the user account. This can be done by using ALTER
USER statement.
9.1.1.1 Configuring Account Authentication
To prevent the unauthorized access, each user must be authenticated beIore being
connected to the database. You can use any one oI the three types oI authentication:
DeIault database authentication
External authentication
Global authentication
9.1.1.1.1 Default Authentication
Using this authentication, Oracle checks Ior the valid user name and password. The
syntax Ior creating the deIault authentication is shown in the listing 9.1.
CREATE USER <user name> IDENTIFIED BY <password>;
Listing 9.1
Syntax for Creating the Default Authentication
For example, you want to create a user account with the name, John and password,
passwd1. To do this, you need to enter the query, shown in the listing 9.2.
CREATE USER john IDENTIFIED BY passwd1;
Listing 9.2
Illustration of Creating a User Account
Copyright 2006, Tata Consultancy Services Limited (TCS). 143
Understanding SQL using ORACLE Database User Access and Security
9.1.1.1.2 External Authentication
Using this authentication, Oracle only checks Ior the user validity but responsibility oI
password checking is on client`s operating system. Initially, the externally authenticated
accounts were introduced in Oracle 6. In Oracle 6, the Oracle account needs to be
preIixed with the key string OPS$. Since then, these externally authenticated accounts are
also known as OPS$ accounts. II the osauthentpreIix parameter deIines the string that
is preIixed with operating system account name Ior the externally identiIied accounts oI
Oracle. II this parameter is set as the deIault oI OPS$ then the operating system user, appl
is created as shown in the listing 9.3.
CREATE USER ops$appl IDENTIFIED EXTERNALLY;
Listing 9.3
Illustration of Creating ops$appl Account
In many cases, the string deIined Ior osauthentpreIix parameter, is leIt blank.
ThereIore, the code Ior creating appl account is shown in the listing 9.4.
CREATE USER appl IDENTIFIED EXTERNALLY;
Listing 9.4
Illustration of Creating appl Account
9.1.1.1.3 Global Authentication
Using this authentication, the responsibility oI checking the validity oI the password is on
X.509 enterprise directory service. Basically, large organizations use this type oI user
accounts. The syntax Ior creating globally authenticated user accounts is shown in the
listing 9.5.
CREATE USER <user name> IDENTIFIED GLOBALLY AS <directory name>
Listing 9.5
Syntax for Creating Globally Authenticated User Accounts
9.1.1.2 Assigning Attributes
You can also assign the attributes to the user accounts with the CREATE or ALTER
USER statements. Oracle 9i allows you to create or alter user accounts to assign deIault
tablespaces, proIiles, and roles.
9.1.1.2.1 Assigning a Default Tablespace
Tablespace is a collection oI one or more data Iiles. A deIault tablespace allow you to
store the user objects, such as tables and indexes. For example, you as a database
administrator want to create the deIault tablespace, userdata while creating a user, Brad.
To do this, you need to enter the query shown in the listing 9.6.
Copyright 2006, Tata Consultancy Services Limited (TCS). 144
Understanding SQL using ORACLE Database User Access and Security
CREATE USER brad IDENTIFIED BY passwd2
DEFAULT TABLESPACE user_data;
Listing 9.6
Illustration of Creating the Default Tablespace
9.1.1.2.2 Assigning a Temporary Tablespace
Temporary Tablespace is a storage area where all the temporary tables and segments
Irom large sorting operations are stored. For example, you as a database administrator
want to create a temporary tablespace, tech while creating a user, John. To do this, you
need to enter the query shown in the listing 9.7.
CREATE USER john IDENTIFIED BY passwd3
TEMPORARY TABLESPACE tech;
Listing 9.7
Illustration of Creating the Temporary Tablespace
9.1.1.2.3 Using Profiles
ProIile is a mechanism within a database that allows you to restrict the resources that are
utilized by the user. For example, using the proIile, you can ensure that the user change
their password every 15 days. The syntax Ior using a proIile is shown in the listing 9.7.
CREATE USER <user name> IDENTIFIED BY <password> PROFILE <profile>;
Listing 9.7
Syntax for Using a Profile
9.1.1.3 Account Licensing Controls
Oracle 9i provides two types oI licensing, such as concurrent user licensing and named
user licensing. It also allows various database controls that enable you to act in
accordance with your license. This enables you to limit the number oI sessions that are
permitted to connect to the database. The three init.ora parameters that enIorce your
licensing restrictions are:
licensemaxusers: This parameter limits the number oI user accounts that can be
created in the database. This is useIul in case you have a named user database.
licensesessionswarning: This parameter is developed to manage concurrent user
licenses. AIter a parameter is placed, Oracle will register a warning in the alert log
Iile whenever the number oI concurrent session exceeds this threshold value.
licensemaxsessions: This parameter is developed to enIorce the concurrent user
licenses. These licenses calculate the number oI users rather than the number oI
sessions that is opened by each user.
Copyright 2006, Tata Consultancy Services Limited (TCS). 145
Understanding SQL using ORACLE Database User Access and Security
9.1.1.4 Creating Roles
Role is a collection oI privileges that is granted to users. All the privileges are granted to
a role. AIter this, a user becomes the member oI the role by inheriting all privileges Irom
a role. The syntax Ior creating role is shown in listing 9.8.
CREATE ROLE <role name> IDENTIFIED [BY <password> | EXTERNALLY |
GLOBALLY];
Listing 9.8
Syntax of Creating a Role
For example, you as a database administrator want to create a role, doctor. To do this,
you need to enter the query shown in the listing 9.9.
CREATE ROLE doctor NOT IDENTIFIED;
Listing 9.9
Illustration for Creating a Role
II you have created a role using IDENTIFIED BY clause then that role is by deIault,
disabled. ThereIore, you need to enable that role using SET ROLE statement. The syntax
Ior enabling a role is shown in listing 9.10.
SET ROLE <role name> IDENTIFIED BY <password>;
Listing 9.10
Syntax for Enabling a Role
9.2 Assigning Privileges
Privileges are the rights assigned by the owner oI the object to other users, allowing them
to work with the owner`s data. Owner can also grant privileges also enable the users to
perIorm system-level operations, such as creating and dropping objects. Oracle 9i
provides multiple types oI privileges, such as object, system, and role.
9.2.1 Object Privileges
These are the privileges assigned to the user on database objects, such as tables, views,
and Iunctions. There are nine types oI object privileges, which include:
ALTER: Allows the user to execute the ALTER TABLE statement on the table.
This statement enables the user to alter the table by renaming the table, adding
and dropping columns, and changing the size oI the columns.
DELETE: Allows the user to execute the DELETE statement. This statement
enables the user to delete rows Irom the table.
Copyright 2006, Tata Consultancy Services Limited (TCS). 146
Understanding SQL using ORACLE Database User Access and Security
EXECUTE: Allows the user to execute a speciIic program. II this privilege is
assigned on a package then the user can use any program or program object, such
as record type or cursor deIined in the package speciIication.
INDEX: Allows the user to create indexes on the table. In addition, it allows the
user to lock that table.
INSERT: Allows the user to create rows in a table or view. You can also assign
this privilege to the user only on a speciIic column.
READ: Allows the user to only read BFILEs in the speciIied directory.
REFERENCE: Allows the user to create integrity constraints that reIer to the table
on which REFERENCE privilege is granted.
SELECT: Allows the user to execute SELECT statement on the table or view.
This enables the user to view the content oI the table or view.
UPDATE: Allows the user to change data values in the table or view.
9.2.2 System Privileges
These privileges are assigned to the users to create, modiIy, and remove database objects
or Ieatures. The types oI system privileges are:
Cluster Privileges: Allows the users to create, modiIy, and remove clusters in their
own schema. These privileges include:
o CREATE ANY CLUSTER: Allows the user to create new cluster in any
schema.
o ALTER ANY CLUSTER: Allows the user to alter cluster in any schema.
o DROP ANY CLUSTER: Allows the user to drop cluster in any schema.
Database Privileges: Allows the user to manage databases. These privileges
include:
o ALTER DATABASE: Allows the user to execute the ALTER
DATABASE statement.
o ALTER SYSTEM: Allows the user to execute the ALTER SYSTEM
statement.
o AUDIT SYSTEM: Allows the user to execute the AUDIT and NOAUDIT
statements.
Index Privileges: Allows the user to manage indexes. These privileges include:
o CREATE ANY INDEX: Allows the user to create indexes in any schema.
o ALTER ANY INDEX: Allows the user to modiIy indexes in any schema.
o DROP ANY INDEX: Allows the user to remove indexes in any schema.
ProIile Privileges: Allows the user to manage proIiles. These privileges include:
o CREATE PROFILE: Allows the user to create new proIile.
o ALTER PROFILE: Allows the user to modiIy existing proIile.
o DROP PROFILE: Allows the user to remove proIile Irom the database.
Copyright 2006, Tata Consultancy Services Limited (TCS). 147
Understanding SQL using ORACLE Database User Access and Security
View Privileges: Allows the user to manage views. These privileges include:
o CREATE VIEW: Allows the user to create, modiIy, and drop views in
their own schema.
o CREATE ANY VIEW: Allows the user to create views in any schema.
o CREATE ANY VIEW: Allows the user to remove views Irom any
schema.
9.2.3 Assigning Privileges
Oracle 9i also allows you to grant privileges to a user. To do this, you need to use the
GRANT statement. You can grant system privileges or object privileges. To grant a
system privilege, you must have been granted the system privileges with the ADMIN
OPTION. On the other hand, to grant an object privilege, the owner oI the object must
have granted you object privileges with the GRANT OPTION. The syntax oI GRANT
statement is shown in the listing 9.11.
GRANT ( grant_system_privileges | grant_object_privileges);
Listing 9.11
Syntax of GRANT Statement
9.2.4 Revoking Privileges
To withdraw the assigned privileges, you need to use the REVOKE statement. To revoke
a system privilege or a role, you must have been granted the privilege with the ADMIN
OPTION. On the other hand, to revoke an object privilege, you must have assigned the
object privileges to a user and a role. The syntax Ior revoking privileges is shown in the
listing 9.12.
REVOKE
{ revoke_system_privileges
| revoke_object_privileges
}
[, { revoke_system_privileges
| revoke_object_privileges
}
]... ;
Listing 9.12
Syntax for Revoking Privileges
9.2.5 Viewing Privileges
Oracle 9i allows you to view all the privileges that are granted, in the data dictionary.
There are multiple data dictionary views related to privileges and their contents, which
include:
Copyright 2006, Tata Consultancy Services Limited (TCS). 148
Understanding SQL using ORACLE Database User Access and Security
ALLCOLPRIVS: Contains the column privileges that have been granted to the
user. The column privileges can also be granted to PUBLIC Ior which the user is
the owner.
ALLCOLPRIVSMADE: Contains the column privileges that have been
granted on tables and views.
ALLTABMADE: Contains the object privileges that have been granted to the
user. The object privileges can also be granted to PUBLIC Ior which the user is
the owner.
DBACOLPRIVS: Contains all the column privileges that have been granted.
DBAROLEPRIVS: Contains all the roles that have been granted to users or to
other roles.
DBATABPRIVS: Contains all the object privileges that have been granted.
ROLESYSPRIVS: Contains all the system privileges that are granted to the
user, directly or indirectly through roles.
ROLETABPRIVS: Contains all the object privileges that are granted to the
user, directly or indirectly through roles.
USERSYSPRIVS: Contains system privileges that are granted directly to the
user.
USERTABPRIVS: Contains object privileges that are granted directly to the
user.
9.3 Administering User Groups Using Profiles
A proIile is a technique within a database that allows you to manage the amount oI
resources Ior a user. For example, using a proIile, you can ensure that users change their
passwords every 15 days. All user accounts have a proIile. II a proIile is not explicitly
assigned to the user account then the deIault proIile is used.
9.3.1 Resource Settings
ProIile setting is classiIied in one oI the two groups:
Password resource settings: Includes Iailedlogonattempts or
passwordliIetime.
Kernel resource: Includes settings like idletime and logicalreadspersession.
To enable kernel resource limits, set the init.ora parameter resourcelimitTRUE.
9.3.2 Creating and Altering Profiles
By deIault, database has one proIile that has all the parameters set to unlimited values. To
create a new proIile, you need to use the CREATE PROFILE statement. The syntax Ior
creating a new proIile is shown in the listing 9.13.
CREATE PROFILE <profile name>
LIMIT [CONNECT_TIME | IDLE_TIME | CPU_PER_CALL | CPU_PER_SESSION |
LOGICAL_READS_PER_CALL | LOGICAL_READS_PER_SESSION | PASSWORD_LIFE_TIME
Copyright 2006, Tata Consultancy Services Limited (TCS). 149
Understanding SQL using ORACLE Database User Access and Security
| PASSWORD_LOCK_TIME | PASSWWORD_REUSE_TIME | PASSWORD_REUSE_MAX]
<DEFAULT | integer value>;
Listing 9.13
Syntax for Creating a New Profile
For example, you as a database administrator want to create a proIile, users and limit the
PASSWORDLIFETIME as deIault. To do this, you need to enter the query, shown in
the listing 9.14.
CREATE PROFILE users LIMIT PASSWORD_LIFE_TIME default;
Listing 9.14
Illustration for Creating a Profile
You can also alter the proIile using the ALTER PROFILE statement. The syntax Ior
altering proIile is shown in the listing 9.15.
ALTER PROFILE <profile name>
LIMIT [CONNECT_TIME | IDLE_TIME | CPU_PER_CALL | CPU_PER_SESSION |
LOGICAL_READS_PER_CALL | LOGICAL_READS_PER_SESSION | PASSWORD_LIFE_TIME
| PASSWORD_LOCK_TIME | PASSWORD_REUSE_TIME | PASSWORD_REUSE_MAX]
<DEFAULT | integer value>;
Listing 9.15
Syntax for Altering a Profile
For example, you as a database administrator want to alter a proIile, named users by
changing the idle time limit to 10 minutes. To do this, you need to enter the query, shown
in the listing 9.16.
ALTER PROFILE users LIMIT IDLE_TIME 10;
Listing 9.16
Illustration for Altering a Profile
9.3.2.1 Kernel Resource Setting
The parameters Ior setting the kernel resource limits are described in the given table:
Parameters Description
CONNECTTIME Limits a session to a speciIied number oI
minutes.
IDLETIME Sets the maximum number oI minutes that
Oracle will wait between calls.
CPUPERCALL Limits the amount oI CPU time that each
database call can use. This amount is in
hundredths oI a second.
CPUPERSESSION Limits the amount oI CPU time that each
session call can use. This amount is in
hundredths oI a second.
Copyright 2006, Tata Consultancy Services Limited (TCS). 150
Understanding SQL using ORACLE Database User Access and Security
LOGICALREADSPERCALL Limits the number oI logical reads that
each database call can perIorm.
LOGICALREADSPERSESSION Limits the number oI logical reads that a
session can perIorm.
9.3.2.2 Password Resource Setting
The parameters oI password resource settings are used Ior enhancing password security.
The parameters Ior setting password resource limits are described in the given table:
Parameters Description
PASSWORDLIFETIME Limits the number oI days that a password
will remain valid.
PASSWORDLOCKTIME Sets the number oI days aIter which a
locked password will automatically
unlock.
PASSWORDREUSETIME Sets the minimum number oI days beIore
which a password can be reused.
PASSWORDREUSEMAX Sets the minimum number oI days beIore
which a password can be reused.
Copyright 2006, Tata Consultancy Services Limited (TCS). 151
Understanding SQL using ORACLE Database User Access and Security
SUMMARY
Oracle 9i is a multi-user database that allows you to restrict or speciIy what a user
can do with the database objects.
Oracle 9i enables you to create a user account. For creating a user account, you
need to use CREATE USER statement.
Oracle 9i also enables you to alter the user account by assigning multiple
attributes to the user account. This can be done by using ALTER USER
statement.
To prevent the unauthorized access, each user must be authenticated beIore being
connected to the database.
You can use any one oI the three types oI authentication:
o DeIault database authentication
o External authentication
o Global authentication
Oracle 9i allows you to create or alter user accounts to assign deIault tablespaces,
proIiles, and roles.
Tablespace is a collection oI one or more data Iiles.
A deIault tablespace allow you to store the user objects, such as tables and
indexes.
ProIile is a mechanism within a database that allows you to restrict the resources
that are consumed by the user.
Role is a collection oI privileges that are granted to a user.
You can set the role attribute only with the ALTER USER statement.
Oracle 9i provides two types oI licensing, such as concurrent user licensing and
named user licensing.
The three init.ora parameters that enIorce your licensing restrictions are:
o licensemaxusers
o licensesessionswarning
o licensemaxsessions
Role is a collection oI privileges that is granted to users.
Privileges are the rights assigned by the owner oI the object to other users,
allowing them to work with the owner`s data.
Oracle 9i provides multiple types oI privileges, such as object privileges, system
privileges, and role privileges.
To withdraw the privileges, you need to use the REVOKE statement.
Oracle 9i allows you to view all the privileges that are granted in the data
dictionary.
A proIile is a technique within a database that allows you to manage the amount
oI resources Ior a user.
To create a new proIile, you need to use the CREATE PROFILE statement.
Copyright 2006, Tata Consultancy Services Limited (TCS). 152
Understanding SQL using ORACLE Database User Access and Security
You can also alter the proIile using the ALTER PROFILE statement.
SELF ASSESSMENT
I. Fill up the blanks:
a) For creating a user account, you need to use USER statement.
b) is a collection oI one or more data Iiles.
c) is a collection oI privileges that are granted to a user.
d) are the rights assigned by the owner oI the object to other users,
allowing them to work with the owner`s data.
e) A is a technique within a database that allows you to manage the amount
oI resources Ior a user.
II. State True or False:
a) CONNECTTIME sets the maximum number oI minutes that Oracle will wait
between calls
b) CPUPERSESSION limits the amount oI CPU time that each session call can use.
c) Using DeIault authentication, Oracle only checks Ior the user validity but
responsibility oI password checking is on client`s operating system.
d) Using Global authentication, the responsibility oI checking the validity oI the
password is on X.509 enterprise directory service.
Copyright 2006, Tata Consultancy Services Limited (TCS). 153
Understanding SQL using ORACLE Database Understanding SQL Tuning

Understanding SQL Tuning
SCOPE
10.1 Tuning SQL PerIormance
10.1.1 EXPLAIN PLAN
10.1.2 AUTOTRACE
10.2 Using BIND Variables
Copyright 2006, Tata Consultancy Services Limited (TCS). 154
Understanding SQL using ORACLE Database Understanding SQL Tuning
10.1 Tuning SQL Performance
Oracle 9i is a multi-user database, and enables multiple users to access the database
simultaneously. As a result, the database application undergoes wear and tear, which
decreases the perIormance oI the database. As the number oI queries that have to be
processed by the database application increase, the load on the database increases, which
aIIects the perIormance oI the database.
Due to decrease in the perIormance oI the database, the query processing time increases.
In addition, decrease in perIormance may cause the database to provide inaccurate
results.
However, as a database administrator, you need to monitor the perIormance oI the
database application to identiIy a decrease in the perIormance. AIter identiIying that the
perIormance oI the database has decreased, you need to identiIy the reasons Ior the
decrease in perIormance. There can be various reasons Ior the decrease in the
perIormance, such as increase in number oI queries or improper load balancing.
AIter identiIying the appropriate reason Ior the decrease in perIormance, you need to
deIine a strategy Ior improving the perIormance and the eIIiciency oI the database.
The Iollowing are the main characteristics oI perIormance tuning:
PerIormance tuning is a constant process, and should be conducted continuously.
This is because, the perIormance oI the database application starts undergoing
wear-tear Irom the time it is Iirst used. In addition, the eIIiciency oI the database
continues to decrease as multiple users use it.
Depending on the type oI problem, the approach to improve the perIormance and
the eIIiciency oI the database changes. This is because; diIIerent problems have
diIIerent solutions and aIIect the perIormance oI the database in diIIerent ways.
PerIormance greatly depends on the type oI SQL queries issued by the users.
Some queries increase the processing load on the database; as such queries require
more system resources as compared to other queries. As a database administrator,
you need to identiIy such queries and ensure that such queries should not be used
Irequently.
To improve the perIormance and the eIIiciency oI the database, you need to
constantly monitor the perIormance oI the database. This will enable you to
identiIy any abnormal activity that can cause a decrease in perIormance.
To monitor the perIormance oI the database, you can deIine perIormance metrics
that can be used to deIine and monitor the perIormance oI the database
application.
SQL provides various commands and Iacilities that can be used to monitor the
perIormance oI the database. Based on the inIormation generated by these commands and
Copyright 2006, Tata Consultancy Services Limited (TCS). 155
Understanding SQL using ORACLE Database Understanding SQL Tuning
Iacilities, you can improve the perIormance and the eIIiciency oI the database. These
commands and Iacilities are:
EXPLAIN PLAN
AUTOTRACE
10.1.1 EXPLAIN PLAN
EXPLAIN PLAN is a SQL command that is used to view the optimal query plan, which
Oracle 9i will use to execute a given query. In addition, you can use the EXPLAIN
PLAN command to view the execution plan oI the query, even without executing the
query. This will enable you to optimise the execution oI the query beIore actually
executing the query.
However, beIore executing the EXPLAIN PLAN command, you need to create a
PLANTABLE table. This is a normal database table, created using the CREATE
TABLE command. The PLANTABLE table will contain the data generated by the
EXPLAIN PLAN command.
The PLANTABLE table contains the various Iields, which are:
Operation: Indicates the Iunction being perIormed by the EXPLAIN PLAN
command.
Name: Indicates the name oI the database object on which the EXPLAIN PLAN
command is being executed.
Rows: Indicates the numbers oI rows that will result Irom executing a speciIic
statement oI the query Ior which the EXPLAIN PLAN command is being
executed.
Bytes: Indicates the number oI bytes that will result Irom executing a speciIic
statement oI the query Ior which the EXPLAIN PLAN command is being
executed.
Cost: Indicates the relative cost oI executing a speciIic statement oI the query Ior
which the EXPLAIN PLAN command is being executed.
Pstart: Indicates the starting partition oI the query being executed. This Iield is
only available when the EXPLAIN PLAN command is being executed on a
partitioned table.
Pstop: Indicates the ending partition oI the query being executed. This Iield is
only available when the EXPLAIN PLAN command is being executed on a
partitioned table.
To create the PLANTABLE table, you need to execute the deIault script, which is,
utlxplan.sql.
The location oI this script is, ORACLEHOME\rdbms\admin\utlxplan.sql. When this
script is executed, the PLANTABLE table is created. AIter the table is created, you can
execute the EXPLAINPLAN command to generate the required inIormation.
The syntax oI the EXPLAINPLAN command is:
Copyright 2006, Tata Consultancy Services Limited (TCS). 156
Understanding SQL using ORACLE Database Understanding SQL Tuning
EXPLAIN PLAN
SET STATEMENT ID = <ID_name>
FOR <SQL Query>
Listing 10.1
Syntax of the EXPLAIN PLAN Command
In the listing 10.1, IDname reIers to a name that is assigned to the SQL query speciIied
with the EXPLAIN PLAN command. This name is used to identiIy the query speciIied in
EXPLAIN PLAN command in the PLANTABLE table.
10.1.2 AUTOTRACE
Since the EXPLAIN PLAN command does not provide inIormation regarding which
query can be optimally executed. This is because; the EXPLAIN PLAN command does
not actually execute the query. For getting the inIormation about the actual execution
plan oI a query, you can use the AUTOTRACE tool.
The AUTOTRACE tool is a SQL*Plus Iacility that is used to provide the actual
execution plan inIormation about a SQL query. You can use this inIormation to analyse
the current perIormance oI the database, and implement strategies to improve the
perIormance oI the database. In addition, the AUTOTRACE tool is used to compare the
perIormance oI a query under diIIerent circumstances. You can also use the
AUTOTRACE tool to analyse the perIormance oI similarly written queries.
You need to run the AUTOTRACE Iacility, Ior which you need to have the
administration rights. To run the AUTOTRACE Iacility, you need to perIorm the
Iollowing steps:
Log into SQL *Plus as SYSDBA
Execute the script, ORACLEHOME/sqlplus/admin/plustrace
Grant PLUSTRACE to PUBLIC (or to a speciIic user or role)
AIter executing these steps, you need to create a PLUSTRACE role. The PLUSTRACE
role enables you to access various system tables that are used in perIormance testing.
These tables are:
V$sesstat: Is the table oI statistics on the basis on each session.
V$statname: Is the table that consists oI the mapping oI the statistics number with
the query name
However, beIore you start using the AUTOTRACE tool, you need to ensure that the
PLUSTRACE role is installed and granted to you. In addition, you need to ensure that the
PLANTABLE table is installed in your database schema.
You can start using the AUTOTRACE Iacility by executing the command shown in
listing 10.2.
Copyright 2006, Tata Consultancy Services Limited (TCS). 157
Understanding SQL using ORACLE Database Understanding SQL Tuning
SET AUTOTRACE ON
Listing 10.2
Command to Start the AUTOTRACE Tool
AIter executing the command shown in listing 10.2, you can execute a SQL query. AIter
the execution oI the SQL query, the AUTOTRACE tool will display the result oI the SQL
query, EXPLAIN PLAN oI the SQL query, and the session statistics.
The AUTOTRACE tool displays the Iollowing inIormation along with the query result
set:
Recursive calls: This indicates the number oI recursive calls that were perIormed
by Oracle to process the given SQL query. These recursive calls might be
perIormed due to many reasons, such as hard parsing or allocating additional
space to enable an insert operation.
Db block Gets: This indicates the total block reads in the current mode Irom the
database.
Consistent Gets: This indicates the total blocks read in the consistent mode. In
case oI queries, most oI the blocks are read in the consistent mode. Similarly, Ior
the DML operations, the query` portion oI the DML statement will read the
blocks in the consistent mode, whereas the write` operation will modiIy the
blocks in the current mode.
Physical reads: This indicates the total number oI blocks that needed to be read to
process the given SQL query.
Redo Size: This indicates the amount oI redo generated by the query. Redo is
generated on the statements that modiIy the database, such as the UPDATE
statement.
Bytes sent via SQL*Net to client: This indicates the size oI the data sent Irom the
database server to the client. This data is measured in bytes.
Bytes received via SQL *Net Irom client: This indicates the size oI the data that is
received by the database server Irom the client.
Sorts: This indicates the number oI sorts made by Oracle while processing the
query.
Sorts (Disk): This indicates the number oI sorts perIormed by Oracle while
processing the query. However, these sorts could not Iit in the memory, as their
size was large.
Copyright 2006, Tata Consultancy Services Limited (TCS). 158
Understanding SQL using ORACLE Database Understanding SQL Tuning
Rows Processed: This indicates the total number oI rows that were returned by
Oracle aIter processing the given SQL query.
There are various methods in which the AUTOTRACE tool can be used. These methods
are:
SET AUTOTRACE ON: This is the simplest method to use the AUTOTRACE
tool. This method, on execution displays the result oI the SQL query, EXPLAIN
PLAN oI the SQL query, and the session statistics.
SET AUTOTRACE TRACEONLY: This method is used when you need to view
the perIormance related inIormation oI the SQL query. This method on execution,
displays the EXPLAIN PLAN and the session statistics, but suppresses the
display oI the query result set.
SET AUTOTRACE ON EXPLAIN: This method on execution, displays the
query result set and the EXPLAIN PLAN. However, this method suppresses the
display oI the session statistics.
SET AUTOTRACE ON STATISTICS: This method on execution, displays the
query result set and the session statistics. However, this method suppresses the
display oI the EXPLAIN PLAN.
SET AUTOTRACE TRACEONLY EXPLAIN: This method on execution,
displays only the EXPLAIN PLAN Ior the executed SQL query. However, this
method suppresses the display oI the query result set and the session statistics.
SET AUTOTRACE TRACEONLY STATISTICS: This method, on execution
displays the run-time statistics oI the executed SQL query, and suppresses the
display oI the query result set and the EXPLAIN PLAN.
10.2Using BIND Variables
When you execute a SQL query, Oracle searches Ior this type oI query in the shared pool
oI queries. II the query that needs to be executed is Iound in the shared pool, Oracle saves
on multiple processes oI Iully parsing the query and optimising the execution plan.
However, iI the query that needs to be executed is not located in the shared pool, Oracle
needs to run multiple processes, such as Iully parsing the query and optimising the
execution plan. This overloads the processing system and may result in decrease in the
perIormance oI the database.
ThereIore, reuse oI queries is recommended to optimise the perIormance oI the database
and save the time and resources utilized in additional processes, such as parsing.
Generally, the queries diIIer in the terms oI the WHERE clause. ThereIore, to create
generalized queries, which can be reused whenever required, Oracle provide the BIND
Copyright 2006, Tata Consultancy Services Limited (TCS). 159
Understanding SQL using ORACLE Database Understanding SQL Tuning
variables. Using BIND variables ensure that Oracle does not have to hard parse the
executed query, which results in optimising the use oI processing resources.
BIND variables can be deIined as placeholders that are used to provide inputs and
generate outputs Irom SQL. The values Ior the BIND variables are provided at a later
stage. For example, the query shown in listing 10.3 displays the use oI a BIND variable.
SELECT * FROM Employee WHERE Emp_Fname = :bv;
Listing 10.3
Using a BIND Variable
The query shown in listing 10.3 shows the use oI a BIND variable, :bv, which makes this
query, a generic query. Due to this, this query is can be reused and its execution will not
result in overloading the processing system oI the database. This query can be used to
search any employee, which saves the time and resources that would have been utilized
to execute this query multiple times.
Copyright 2006, Tata Consultancy Services Limited (TCS). 160
Understanding SQL using ORACLE Database Understanding SQL Tuning
SUMMARY
As the number oI queries that have to be processed by the database application
increase, the load on the database increases, which aIIects the perIormance oI the
database.
Due to decrease in the perIormance oI the database, the query processing time
increases.
As a database administrator, you need to monitor the perIormance oI the database
application to identiIy a decrease in the perIormance.
The Iollowing are the main characteristics oI perIormance tuning:
o PerIormance tuning is a constant process, and should be conducted
continuously.
o Depending on the type oI problem, the approach to improve the perIormance
and the eIIiciency oI the database changes.
o PerIormance greatly depends on the type oI SQL queries issued by the users.
o To improve the perIormance and the eIIiciency oI the database, you need to
constantly monitor the perIormance oI the database.
o To monitor the perIormance oI the database, you can deIine perIormance
metrics that can be used to deIine and monitor the perIormance oI the
database application.
SQL provides various commands and Iacilities that can be used to monitor the
perIormance oI the database. These commands and Iacilities are:
o EXPLAIN PLAN
o AUTOTRACE
EXPLAIN PLAN is a SQL command that is used to view the optimal query plan,
which Oracle 9i will use to execute a given query.
You can use the EXPLAIN PLAN command to view the execution plan oI the
query, even without executing the query.
However, beIore executing the EXPLAIN PLAN command, you need to create a
PLANTABLE table.
The PLANTABLE table contains the various Iields, which are:
o Operation
o Name
o Rows
o Bytes
o Cost
o Pstart
o Pstop
The AUTOTRACE tool is a SQL*Plus Iacility that is used to provide the actual
execution plan inIormation about a SQL query.
The AUTOTRACE tool is used to compare the perIormance oI a query under
diIIerent circumstances.
Copyright 2006, Tata Consultancy Services Limited (TCS). 161
Understanding SQL using ORACLE Database Understanding SQL Tuning
The AUTOTRACE tool displays the Iollowing inIormation along with the query
result set:
o Recursive calls
o Db block Gets
o Consistent Gets
o Physical reads
o Redo Size
o Bytes sent via SQL*Net to client
o Bytes sent via SQL*Net to client
o Sorts
o Sorts (Disk)
o Rows Processed
Using BIND variables ensure that Oracle does not have to hard parse the executed
query, which results in optimising the use oI processing resources.
Copyright 2006, Tata Consultancy Services Limited (TCS). 162
Understanding SQL using ORACLE Database Understanding SQL Tuning
SELF ASSESSMENT
I. Fill up the blanks:
a) The is a Iacility that is used to provide the actual
execution plan inIormation about a SQL query.
b) indicates the number oI sorts perIormed by Oracle while processing the
query, but these sorts could not Iit in the memory, as their size was large.
c) indicates the total number oI blocks that needed to be read to process the
given SQL query.
d) indicates the total block reads in the current mode Irom the database.
e) BeIore you start using the AUTOTRACE tool, you need to ensure that the
role is installed and granted to you.
II. State True or False:
a) The location oI utlxplan.sql script is, ORACLEHOME
\rdbms\administration\utlxplan.sql.
b) Operation indicates the Iunction being perIormed by the PLUSTRACE command.
c) Pstop is one oI the Iields oI the PLANTABLE table.
d) Rows Processed indicates the total number oI rows that were returned by Oracle aIter
processing the given SQL query.
Copyright 2006, Tata Consultancy Services Limited (TCS). 163