Oracle SQL PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 171

Prepared by Muhammad Raheem

Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

What is a Database?

A database is a collection of information that is organized so that it can easily be accessed,


managed, and updated.

OR

A collection of information organized in such a way that a computer program can quickly select
desired pieces of data. You can think of a database as an electronic filing system.

Traditional databases are organized by fields, records, and files/table. A field is a single piece of
information; a record is one complete set of fields; and a file is a collection of records/table.

For example, a telephone book is analogous to a file. It contains a list of records, each of which
consists of three fields: name, address, and telephone number.

OR

The definition of a database is a structured collection of records or data that is stored in a


computer system. In order for a database to be truly functional, it must not only store large
amounts of records well, but be accessed easily. In addition, new information and changes
should also be fairly easy to input. In order to have a highly efficient database system, you
need to incorporate a program that manages the queries and information stored on the system.
This is usually referred to as DBMS or a Database Management System. Besides these features,
all databases that are created should be built with high data integrity.

Database Management System (DBMS)

A collection of programs that enables you to store, modify, and extract information from a
database. There are many different types of DBMSs, ranging from small systems that run on
personal computers to huge systems that run on mainframes. The following are examples of
database applications:
• computerized library systems
• automated teller machines
• flight reservation systems
• computerized parts inventory systems

Requests for information from a database are made in the form of a query

1 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Types of Databases

There are several common types of databases; each type of database has its own data model
(how the data is structured). They include; Flat Model, Hierarchical Model, Relational Model and
Network Model.

The Flat Model Database


In a flat model database, there is a two dimensional (flat structure) array of data. For instance,
there is one column of information and within this column it is assumed that each data item will
be related to the other. For instance, a flat model database includes only zip codes. Within the
database, there will only be one column and each new row within that one column will be a new
zip code.

The Hierarchical Model Database


The hierarchical model database resembles a tree like structure, such as how Microsoft
Windows organizes folders and files. In a hierarchical model database, each upward link is
nested in order to keep data organized in a particular order on a same level list. For instance, a
hierarchal database of sales, may list each days sales as a separate file. Within this nested file
are all of the sales (same types of data) for the day.

The Network Model


In a network model, the defining feature is that a record is stored with a link to other records -
in effect networked. These networks (or sometimes referred to as pointers) can be a variety of
different types of information such as node numbers or even a disk address.

The Relational Model


The relational model is the most popular type of database and an extremely powerful tool, not
only to store information, but to access it as well. Relational databases are organized as tables.
The beauty of a table is that the information can be accessed or added without reorganizing the
tables. A table can have many records and each record can have many fields.
Tables are sometimes called a relation. For instance, a company can have a database called
customer orders, within this database will be several different tables or relations all relating to
customer orders. Tables can include customer information (name, address, contact, info,
customer number, etc) and other tables (relations) such as orders that the customer previously
bought (this can include item number, item description, payment amount, payment method,
etc). It should be noted that every record (group of fields) in a relational database has its own
primary key. A primary key is a unique field that makes it easy to identify a record.
Relational databases use a program interface called SQL or Standard Query Language. SQL is
currently used on practically all relational databases. Relational databases are extremely easy
to customize to fit almost any kind of data storage. You can easily create relations for items
that you sell, employees that work for your company, etc.

Accessing Information Using a Database


While storing data is a great feature of databases, for many database users the most important
feature is quick and simple retrieval of information. In a relational database, it is extremely
easy to pull up information regarding an employee, but relational databases also add the power
of running queries. Queries are requests to pull specific types of information and either show
them in their natural state or create a report using the data. For instance, if you had a database
of employees and it included tables such as salary and job description, you can easily run a
query of which jobs pay over a certain amount. No matter what kind of information you store
on your database, queries can be created using SQL to help answer important questions.

2 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Storing a Database
Databases can be very small (less than 1 MB) or extremely large and complicated (terabytes as
in many government databases), however all databases are usually stored and located on hard
disk or other types of storage devices and are accessed via computer. Large databases may
require separate servers and locations, however many small databases can fit easily as files
located on your computer's hard drive.

Securing a Database
Obviously, many databases store confidential and important information that should not be
easily accessed by just anyone. Many databases require passwords and other security features
in order to access the information. While some databases can be accessed via the internet
through a network, other databases are closed systems and can only be accessed on site.

Field / Column
A space allocated for a particular item of information. Admission form, for example, contains a
number of fields: one for your name, one for your Father Name, one for your date of birth, and
so on. In database systems, fields are the smallest units of information you can access.
In spreadsheets, fields are called cells.

Record
A collection of fields is called a record.

Table
Collection of related records is called a table.
Or
Table is a storage object of a database.

Oracle Tables

Oracle stores records relating to each other in a table. For example, all the records for
employees of a company would be stored by Oracle in one table, the employee table.

EMP TABLE

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
EMPNO is a primary key in EMP Table.
DEPTNO is a foreign key in EMP Table.

A table consists of a number of records. The field names of each record in the table are the
same, although the field values may differ. Every employee record has a salary field, called
SAL. The values in the SAL field can be different for each employee.

3 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Each field occupies one column and each record occupies one row. In each column of the table,
you put a specific category of information for the employees, such as their employee number,
name, and job. Each row in the table contains the information relating to a specific employee,
together as one record. Each record is a unique entry and is independent of any other record in
the table. The EMP table, for example, contains records for SMITH and ALLEN. Although both
records are part of the EMP table, the data contained within them is independent of each other.
There is no relationship between SMITH's andALLEN's salaries.
After the analysis of the business requirements, the database design team defines the
necessary tables. Different tables are created for the various groups of information. An EMP
table is created for employee information, a DEPT table is created for department information.
Related tables are grouped together to form a database. For example, a personnel or human
resources application database includes both the EMP and DEPT tables and all other tables
involved in the application.

DEPT TABLE

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
DEPTNO is a primary key in DEPT Table.

Primary Keys
Every table in Oracle has a field or a combination of fields that uniquely identifies each record in
the table. This unique identifier is called the primary key, or simply the key.
* Primary Key is used to identify a record in a table.
* No Duplication
* NULL is not allowed (must provide a value)
* Only one Primary Key in a table
* May be composite Primary Key
* Table in which Primary Key exists normally called parent table

Foreign Key
Remember that every table in ORACLE has a primary key a field or fields making each record
unique. In the employee table, the primary key is the employee ID number, and it is stored in
the EMPNO field. In the DEPT table, the department number is the primary key and is stored in
the DEPTNO field.
The department number is also stored in a field in the EMP table - the DEPTNO field. The
department number field links the EMP table to the DEPT table. This relationship is based on the
department number field.
Employee SMITH works in department number 20, ALLEN works in department 30.
When a field in one table matches the primary key of another table, the field is referred to as a
foreign key. A foreign key is a field or a group of fields in one table whose values match those
of the primary key of another table. You can think of a foreign key as the primary key of a
foreign table. In the personnel database example, the DEPTNO field in the EMP table is a
foreign key. The DEPTNO field is still the primary key of the DEPT table.
* Comes from an other table
* Duplication allowed
* Null is allowed
* There may be multiple foreign Key in a table
* Table in which Foreign Key exists normally called child table

4 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Relational Databases

Oracle makes it very easy to link the data in multiple tables: matching an employee to the
department in which they work is one example. This is a key feature of a relational database
management system, or RDBMS. They store data in two or more tables and enable you to
define relationships between the tables. The link between the tables is based on one or more
field values common to both tables.

For example, the following diagram represents part of the EMP table and the entire DEPT table:

DEPT

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

EMP

EMPNO ENAME DEPTNO


--------- ---------- ---------
7369 SMITH 20
7499 ALLEN 30
7521 WARD 30
7566 JONES 20
7654 MARTIN 30
7698 BLAKE 30
7782 CLARK 10
7788 SCOTT 20
7839 KING 10
7844 TURNER 30
7876 ADAMS 20
7900 JAMES 30
7902 FORD 20
7934 MILLER 10

There is a department number field in both the EMP and DEPT tables. In the EMP table, the
department number represents the department in which the employee works. In the DEPT
table, the department number represents a valid department within the business. In both
tables, they are department numbers; in essence, the contents of the DEPTNO field in the EMP
table represents the same thing as the contents of the DEPTNO field in the DEPARTMENT table.
It's not necessary that the linking fields have the same field names. What's important is their
value and what they represent.

The business is divided into departments. The departments are identified and stored in the
DEPT table. Each department is assigned a department number. The relationship between the
EMP and DEPT tables is based on the department number. Each employee works in one specific
department. The employee's department number is stored in the DEPTNO field of the EMP
table. An employee cannot be assigned to a department that is not defined in the DEPT table. A
department can be defined in the DEPT table, yet have no employees assigned to it.

5 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Data Storage on Different Media

Electronic Filling cabinet Database


Spreadsheet

Storing Information

Every organization has some information needs. A library keeps a list of members, books, due
dates, and fines. A company needs to save information about employees, departments, and
salaries. These pieces of information are called data.

Organizations can store data on various media and in different formats, such as a hard-copy
document in a filing cabinet or data stored in electronic spreadsheets or in databases.
A database is an organized collection of information.

To manage databases, you need database management systems (DBMS). A DBMS is a program
that stores, retrieves, and modifies data in the database on request. There are four main types
of databases: hierarchical, network, relational, and more recently object relational.

6 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 1
Writing Basic SQL SELECT Statements
SQL is an ANSI (American National Standards Institute) standard computer language for
accessing and manipulating databases. SQL statements are used to retrieve and update data in
a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL Server,
Oracle, Sybase, etc.

What is SQL?
SQL stands for Structured Query Language
SQL allows you to access a database
SQL is an ANSI standard computer language
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert new records in a database
SQL can delete records from a database
SQL can update records in a database
SQL is easy to learn

SQL Queries
With SQL, we can query a database and have a result set returned.

A query like this:


SELECT EMPNO, ENAME, JOB, SAL FROM EMP;

SQL Query is also called SQL statement.

Result of the above query:

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

Almost all modern Relational Database Management Systems like MS SQL Server, Microsoft
Access, MSDE, Oracle, DB2, Sybase, MySQL, Postgres and Informix use SQL as standard
database language.

There are three types of SQL Statements:

1. Data Manipulation Language (DML)


2. Data Manipulation Language (DDL)
3. Data Control Language (DCL)

7 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

What is SQL*Plus?

SQL*Plus is an interactive and batch query tool that is installed with every Oracle Database
Server or Client installation. It has a command-line user interface, a Windows Graphical User
Interface (GUI) and the iSQL*Plus web-based user interface.

SQL*Plus has its own commands and environment, and it provides access to the Oracle
Database. It enables you to enter and execute SQL, PL/SQL, SQL*Plus and operating system
commands.

What is iSQL*Plus?

iSQL*Plus is a browser-based interface which uses the SQL*Plus processing engine in a three-
tier model comprising:

• Client (Web browser).


• Middle tier (Application Server).
• Database (Oracle Database).

8 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The Oracle Product Family

As an Oracle database administrator, you may be responsible for a database that is


actually part of another Oracle product or that complements or is relied upon by that
other product. Oracle has long since become more than just a database company—
though the Oracle database is at the heart of what Oracle Corporation does best. In
addition to the database, Oracle Corporation also offers these products, among others:

• Oracle E-Business Suite


Also referred to as Oracle Applications, the E-Business Suite is the premier enterprise resource
planning (ERP) suite in the industry. Encompassing many modules, including financials, human
resources, distribution, manufacturing, and many others, the E-Business Suite allows
organizations to leverage Oracle technology to better run their businesses and increase
profitability and customer satisfaction. Oracle E-Business Suite makes use of the Oracle
database, Application Server, and Developer Suite to run and enhance the application.

• Oracle Collaboration Suite


One of Oracle’s newest products, Collaboration Suite encompasses e-mail, fax, calendaring,
web conferencing, a files repository, voice mail, and other modules to provide a single
integrated platform for an organization’s collaboration and communication infrastructure. Like
Oracle E-Business Suite, Collaboration Suite also incorporates the Oracle database
and Application Server as its foundation.

• Oracle Application Server


A Java 2 Enterprise Edition (J2EE)–certified server platform, Oracle Application Server
integrates everything you need to deploy and develop web-based applications. Oracle
Application Server includes a portal server and tools to develop portlets, Web Services
capabilities, content management, support for forms-based applications using Oracle Forms,
reporting using Oracle Reports, development using PL/SQL or Java, and many other features. It
also includes the capability to configure and use a single sign-on server that interfaces with
other thirdparty directory services such as Microsoft’s Active Directory, Novell’s NDS, and Sun’s
iPlanet.

• Oracle Developer Suite


If you need to develop applications for the Oracle database or Application Server, Oracle
Developer Suite provides tools for the development of Java, PL/SQL, business intelligence, data
warehousing, and other applications.

• Oracle Consulting
When you need assistance in your Oracle deployment, Oracle Consulting can provide the
expertise and individuals to help your projects succeed.

• Oracle University
The training of customers and partners on Oracle products and technologies is the responsibility
of Oracle University and its partners. Instructor-led and online courses are available. More
information on the products available from Oracle Corporation can be found on the Oracle web
site at www.oracle.com.

9 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Connecting to database

You can connect to the database by using different tools. I am using SQL*Plus to connect to the
database. SQL*Plus is Oracle provided tool for accessing database.

In order to connect to database, you must provide:

SQL prompt is appeared after successful login.

SQL statements are used to access database. There are three types of SQL statements.
• Data Manipulation Language (DML)
• Data Definition Language (DDL)
• Data Control Language (DCL)

10 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP;

1 2 4

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 5 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 5 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
1 7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

1. A single row or tuple representing all data required for a particular employee. Each row
in a table should be identified by a primary key, which allows no duplicate rows. The
order of rows is insignificant; specify the row order when the data is retrieved.
2. A column or attribute containing the employee number. The employee number identifies
a unique employee in the EMP table. In this example, the employee number column is
designated as the primary key. A primary key must contain a value, and the value must
be unique.
3. A column that is not a key value. A column represents one kind of data in a table; in the
example, the name of all the employees. Column order is insignificant when storing
data; specify the column order when the data is retrieved.
4. A column containing the department number, which is also a foreign key. A foreign key
is a column that defines how tables relate to each other. A foreign key refers to a
primary key or a unique key in the same table or in another table. In the example,
DEPTNO uniquely identifies a department in the DEPT table.
5. A field may have no value in it. This is called a null value. In the EMP table, only
employees who have a role of salesman have a value in the COMM (commission) field.
6. A field can be found at the intersection of a row and a column. There can be only one
value in it.

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

11 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

What is Keyword? What is Clause?


SELECT SELECT ...
FROM FROM ...
WHERE WHERE ...
ORDER BY ORDER BY ...
GROUP BY GROUP BY ...
etc. etc.

What is SQL Statement?


SELECT * FROM EMP;
SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP;
SELECT * FROM EMP WHERE SAL>2000;
etc.

SELECT & FROM Keywords


Specify number of columns just after SELECT.
Specify table name just after FROM keyword.

Solve the following:

Display all columns and all rows of EMP table.


SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

Display all columns and all rows of DEPT table.


SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

12 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Display employee number, name, and salary of all employees.


SQL> SELECT EMPNO, ENAME, SAL FROM EMP;

EMPNO ENAME SAL


--------- ---------- ---------
7369 SMITH 800
7499 ALLEN 1600
7521 WARD 1250
7566 JONES 2975
7654 MARTIN 1250
7698 BLAKE 2850
7782 CLARK 2450
7788 SCOTT 3000
7839 KING 5000
7844 TURNER 1500
7876 ADAMS 1100
7900 JAMES 950
7902 FORD 3000
7934 MILLER 1300

14 rows selected.

Above query can be written as follows:


SQL> SELECT
2 EMPNO,
3 ENAME,
4 SAL
5 FROM
6 EMP;

EMPNO ENAME SAL


--------- ---------- ---------
7369 SMITH 800
7499 ALLEN 1600
7521 WARD 1250
7566 JONES 2975
7654 MARTIN 1250
7698 BLAKE 2850
7782 CLARK 2450
7788 SCOTT 3000
7839 KING 5000
7844 TURNER 1500
7876 ADAMS 1100
7900 JAMES 950
7902 FORD 3000
7934 MILLER 1300

14 rows selected.

It is good habit to write each clause in separate line. i.e.


SQL> SELECT EMPNO, ENAME, SAL
2 FROM EMP;

Result of above three queries is same.

13 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Remember about SQL statements


SQL statements are not case sensitive.
SQL statements can be on one or more lines.
Keywords cannot be abbreviated or split across lines.
Clauses are usually placed on separate lines.
Indents are used to enhance readability

-- IN ABOVE SQL STATEMENTS [SELECT , FROM ] ARE KEY WORDS


-- IN ABOVE SQL STATEMENTS [SELECT .. , FROM .. ] ARE clauses.

* Means All Columns

How to display structure of a table?


Mean how many columns are there in a table, data type, width and either null is allowed or not.

User DESCRIBE / DESC command

SQL> DESC EMP


Name Null? Type
------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

There are eight columns in EMP table. Data type and width of each column is also displayed.
NOT NULL is written in front of EMPNO.

SQL> DESC DEPT


Name Null? Type
------------------------------- -------- ----
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

What is Data Type?


Classification of a particular type of information. It is easy for humans to distinguish between
different types of data.

Some data types are as follows:

NUMBER Accepts 0 to 9, decimal point, positive or negative sign


CHAR Accepts 0 to 9, alpha bets and special characters
VARCHAR2 Accepts 0 to 9, alpha bets and special characters
DATE Accepts Date

Example of Numbers Salary, Commission, Fee, Charges, Amount etc


Example of VARCHAR2 Name, Father Name, Job, Address etc.
Example of DATE Date of Birth, Admission Date, Resignation Date etc.

14 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Selecting specific columns and notice the heading of each column.


SQL> SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

SQL> SELECT ENAME, JOB, SAL, DEPTNO FROM EMP;


ENAME JOB SAL DEPTNO
---------- --------- --------- ---------
SMITH CLERK 800 20
ALLEN SALESMAN 1600 30
WARD SALESMAN 1250 30
JONES MANAGER 2975 20
MARTIN SALESMAN 1250 30
BLAKE MANAGER 2850 30
CLARK MANAGER 2450 10
SCOTT ANALYST 3000 20
KING PRESIDENT 5000 10
TURNER SALESMAN 1500 30
ADAMS CLERK 1100 20
JAMES CLERK 950 30
FORD ANALYST 3000 20
MILLER CLERK 1300 10

14 rows selected.

SQL> SELECT JOB, SAL FROM EMP;


JOB SAL
--------- ---------
CLERK 800
SALESMAN 1600
SALESMAN 1250
MANAGER 2975
SALESMAN 1250
MANAGER 2850
MANAGER 2450
ANALYST 3000
PRESIDENT 5000
SALESMAN 1500
CLERK 1100
CLERK 950
ANALYST 3000
CLERK 1300
15 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT ENAME FROM EMP;


ENAME
----------
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

SQL> SELECT DEPTNO, DNAME, LOC FROM DEPT;


DEPTNO DNAME LOC
--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL> SELECT DEPTNO, DNAME FROM DEPT;


DEPTNO DNAME
--------- --------------
10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS

SQL> SELECT DNAME FROM DEPT;


DNAME
--------------
ACCOUNTING
RESEARCH
SALES
OPERATIONS

What is DUAL Table?


The DUAL table is owned by the user SYS and can be accessed by all users. It contains one
column, DUMMY, and one row with the value X. The DUAL table is useful when you want to
return a value once only, for instance, the value of a constant, pseudocolumn, or expression
that is not derived from a table with user data. The DUAL table is generally used for SELECT
clause syntax completeness, because both SELECT and FROM clauses are mandatory, and
several calculations do not need to select from actual tables.

SQL> DESC DUAL


Name Null? Type
------------------------------- -------- ----
DUMMY VARCHAR2(1)

SQL> SELECT * FROM DUAL;

D
-
X
16 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Display Current Date using DUAL Table


SQL> SELECT SYSDATE FROM DUAL;

SYSDATE
---------
14-JUL-08

Display Current User using DUAL Table


SQL> SELECT USER FROM DUAL;

USER
------------------------------
SCOTT

SQL>

Arithmetic operators and precedence


+ Addition
- Subtraction
* Multiplication
/ Division

PRECEDENCE
1. ( ) Parenthesis has the highest precedence
2. * / Multiplication and Division have the same precedence
3. + - Addition and Subtraction have the same precedence

Performing calculation in using SQL


SQL> SELECT 7+10 FROM DUAL;

7+10
----------
17

SQL> SELECT 7+10-2+5 FROM DUAL;

7+10-2+5
----------
20

SQL> SELECT 7+10*2+5 FROM DUAL;

7+10*2+5
----------
32

SQL> SELECT 7+10-2*5 FROM DUAL;

7+10-2*5
----------
7

17 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT 7*10-2+5 FROM DUAL;

7*10-2+5
----------
73

SQL> SELECT 7*10-2*5 FROM DUAL;

7*10-2*5
----------
60

SQL> SELECT 7+10/2+5 FROM DUAL;

7+10/2+5
----------
17

SQL> SELECT 7*10/2+5 FROM DUAL;

7*10/2+5
----------
40

SQL> SELECT 7*10/2*5 FROM DUAL;

7*10/2*5
----------
175

SQL> SELECT 7+10/2*5 FROM DUAL;

7+10/2*5
----------
32

SQL> SELECT 7*10/(2+5) FROM DUAL;

7*10/(2+5)
----------
10

SQL> SELECT 7*10+2+5 FROM DUAL;

7*10+2+5
----------
77

SQL> SELECT 7*(10+2)+5 FROM DUAL;

7*(10+2)+5
----------
89

18 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Performing calculations with columns, Notice heading of each column


WITH NUMBER COLUMNS

SQL> SELECT EMPNO, ENAME, SAL, SAL+100, SAL-100, SAL*12 FROM EMP;

EMPNO ENAME SAL SAL+100 SAL-100 SAL*12


--------- ---------- --------- --------- --------- ---------
7369 SMITH 800 900 700 9600
7499 ALLEN 1600 1700 1500 19200
7521 WARD 1250 1350 1150 15000
7566 JONES 2975 3075 2875 35700
7654 MARTIN 1250 1350 1150 15000
7698 BLAKE 2850 2950 2750 34200
7782 CLARK 2450 2550 2350 29400
7788 SCOTT 3000 3100 2900 36000
7839 KING 5000 5100 4900 60000
7844 TURNER 1500 1600 1400 18000
7876 ADAMS 1100 1200 1000 13200
7900 JAMES 950 1050 850 11400
7902 FORD 3000 3100 2900 36000
7934 MILLER 1300 1400 1200 15600

SQL> SELECT EMPNO, ENAME, SAL, SAL*12, SAL+100*12, (SAL+100)*12 FROM EMP;

EMPNO ENAME SAL SAL*12 SAL+100*12 (SAL+100)*12


--------- ---------- --------- --------- ---------- ------------
7369 SMITH 800 9600 2000 10800
7499 ALLEN 1600 19200 2800 20400
7521 WARD 1250 15000 2450 16200
7566 JONES 2975 35700 4175 36900
7654 MARTIN 1250 15000 2450 16200
7698 BLAKE 2850 34200 4050 35400
7782 CLARK 2450 29400 3650 30600
7788 SCOTT 3000 36000 4200 37200
7839 KING 5000 60000 6200 61200
7844 TURNER 1500 18000 2700 19200
7876 ADAMS 1100 13200 2300 14400
7900 JAMES 950 11400 2150 12600
7902 FORD 3000 36000 4200 37200
7934 MILLER 1300 15600 2500 16800

SQL> SELECT EMPNO, ENAME, COMM, COMM+100, COMM-100, COMM*12 FROM EMP;

EMPNO ENAME COMM COMM+100 COMM-100 COMM*12


--------- ---------- --------- --------- --------- ---------
7369 SMITH
7499 ALLEN 300 400 200 3600
7521 WARD 500 600 400 6000
7566 JONES
7654 MARTIN 1400 1500 1300 16800
7698 BLAKE
7782 CLARK
7788 SCOTT ?
7839 KING
7844 TURNER 0 100 -100 0
7876 ADAMS
7900 JAMES
7902 FORD ?
7934 MILLER

19 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM FROM EMP;

EMPNO ENAME SAL COMM SAL+COMM


--------- ---------- --------- --------- ---------
7369 SMITH 800
7499 ALLEN 1600 300 1900
7521 WARD 1250 500 1750
7566 JONES 2975
7654 MARTIN 1250 1400 2650
7698 BLAKE 2850
7782 CLARK 2450
7788 SCOTT 3000 ?
7839 KING 5000
7844 TURNER 1500 0 1500
7876 ADAMS 1100
7900 JAMES 950
7902
7934
FORD
MILLER
3000
1300
?
14 rows selected.

SQL> SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM*12, (SAL+COMM)*12 FROM EMP;

EMPNO ENAME SAL COMM SAL+COMM*12 (SAL+COMM)*12


--------- ---------- --------- --------- ----------- -------------
7369 SMITH 800
7499 ALLEN 1600 300 5200 22800
7521 WARD 1250 500 7250 21000
7566 JONES 2975
7654 MARTIN 1250 1400 18050 31800
7698 BLAKE 2850
7782 CLARK 2450
7788 SCOTT 3000
7839 KING 5000
7844 TURNER 1500 0 1500 18000
7876 ADAMS 1100
7900 JAMES 950
7902 FORD 3000
7934 MILLER 1300

In above result notice calculation with NULL values


• A null is a value that is unavailable, unassigned, unknown or inapplicable.
• A null is not the same as zero or a blank space.

If you add, subtract, multiply or divided a value with null, the whole result becomes null.

20 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

NULL value can be controlled with NVL() function


NVL (column_name, replaced_value)

SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,0) FROM EMP;


NULL will be replaced with 0

SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,100) FROM EMP;


NULL will be replaced with 100

Notice the result of column number 3, 4 and 5


SQL> SELECT EMPNO, ENAME, COMM, NVL(COMM,0), NVL(COMM,50) FROM EMP;

EMPNO ENAME COMM NVL(COMM,0) NVL(COMM,50)


--------- ---------- --------- ----------- ------------
7369 SMITH 0 50
7499 ALLEN 300 300 300
7521 WARD 500 500 500
7566 JONES 0 50
7654 MARTIN 1400 1400 1400
7698 BLAKE 0 50
7782 CLARK 0 50
7788 SCOTT 0 50
7839 KING 0 50
7844 TURNER 0 0 0
7876 ADAMS 0 50
7900 JAMES 0 50
7902 FORD 0 50
7934 MILLER 0 50

14 rows selected.

Notice the result of column number 6 and 7


SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM, SAL+COMM, SAL+NVL(COMM,0) FROM EMP;

EMPNO ENAME JOB SAL COMM SAL+COMM SAL+NVL(COMM,0)


--------- ---------- --------- --------- --------- --------- ---------------
7369 SMITH CLERK 800 800
7499 ALLEN SALESMAN 1600 300 1900 1900
7521 WARD SALESMAN 1250 500 1750 1750
7566 JONES MANAGER 2975 2975
7654 MARTIN SALESMAN 1250 1400 2650 2650
7698 BLAKE MANAGER 2850 2850
7782 CLARK MANAGER 2450 2450
7788 SCOTT ANALYST 3000 3000
7839 KING PRESIDENT 5000 5000
7844 TURNER SALESMAN 1500 0 1500 1500
7876 ADAMS CLERK 1100 1100
7900 JAMES CLERK 950 950
7902 FORD ANALYST 3000 3000
7934 MILLER CLERK 1300 1300

14 rows selected.

21 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Performing calculations with columns, Notice heading of each column

WITH DATE COLUMNS

SQL> SELECT SYSDATE, SYSDATE+1, SYSDATE-1 FROM DUAL;

SYSDATE SYSDATE+1 SYSDATE-1


--------- --------- ---------
14-JUL-08 15-JUL-08 13-JUL-08

SQL> SELECT SYSDATE, SYSDATE+7, SYSDATE+30, SYSDATE+365 FROM DUAL;

SYSDATE SYSDATE+7 SYSDATE+3 SYSDATE+3


--------- --------- --------- ---------
14-JUL-08 21-JUL-08 13-AUG-08 14-JUL-09

SQL> SELECT EMPNO, ENAME, HIREDATE, HIREDATE+1, HIREDATE+7 FROM EMP;

EMPNO ENAME HIREDATE HIREDATE+ HIREDATE+


--------- ---------- --------- --------- ---------
7369 SMITH 17-DEC-80 18-DEC-80 24-DEC-80
7499 ALLEN 20-FEB-81 21-FEB-81 27-FEB-81
7521 WARD 22-FEB-81 23-FEB-81 01-MAR-81
7566 JONES 02-APR-81 03-APR-81 09-APR-81
7654 MARTIN 28-SEP-81 29-SEP-81 05-OCT-81
7698 BLAKE 01-MAY-81 02-MAY-81 08-MAY-81
7782 CLARK 09-JUN-81 10-JUN-81 16-JUN-81
7788 SCOTT 19-APR-87 20-APR-87 26-APR-87
7839 KING 17-NOV-81 18-NOV-81 24-NOV-81
7844 TURNER 08-SEP-81 09-SEP-81 15-SEP-81
7876 ADAMS 23-MAY-87 24-MAY-87 30-MAY-87
7900 JAMES 03-DEC-81 04-DEC-81 10-DEC-81
7902 FORD 03-DEC-81 04-DEC-81 10-DEC-81
7934 MILLER 23-JAN-82 24-JAN-82 30-JAN-82

14 rows selected.

SQL> SELECT EMPNO, ENAME, HIREDATE, HIREDATE-7 FROM EMP;

EMPNO ENAME HIREDATE HIREDATE-


--------- ---------- --------- ---------
7369 SMITH 17-DEC-80 10-DEC-80
7499 ALLEN 20-FEB-81 13-FEB-81
7521 WARD 22-FEB-81 15-FEB-81
7566 JONES 02-APR-81 26-MAR-81
7654 MARTIN 28-SEP-81 21-SEP-81
7698 BLAKE 01-MAY-81 24-APR-81
7782 CLARK 09-JUN-81 02-JUN-81
7788 SCOTT 19-APR-87 12-APR-87
7839 KING 17-NOV-81 10-NOV-81
7844 TURNER 08-SEP-81 01-SEP-81
7876 ADAMS 23-MAY-87 16-MAY-87
7900 JAMES 03-DEC-81 26-NOV-81
7902 FORD 03-DEC-81 26-NOV-81
7934 MILLER 23-JAN-82 16-JAN-82

14 rows selected.

22 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Column Alias / Column Heading


When displaying the result of a query, SQL*Plus normally uses the name of the selected column
as the column heading. This heading may not be descriptive and hence may be difficult to
understand. You can change a column heading by using a column alias.
Specify the alias after the column in the SELECT list using a space as a separator. By default,
alias headings appear in uppercase. If the alias contains spaces or special characters (such as #
or $), or is case sensitive, enclose the alias in double quotation marks (" ").

AS is optional

SQL> SELECT EMPNO, ENAME, JOB AS DESIGNATION, SAL AS SALARY, COMM COMMISSION
FROM EMP;

EMPNO ENAME DESIGNATI SALARY COMMISSION


--------- ---------- --------- --------- ----------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600 300
7521 WARD SALESMAN 1250 500
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250 1400
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500 0
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

14 rows selected.

SQL> SELECT EMPNO, ENAME, SAL, SAL*12 ANN_SAL FROM EMP;

EMPNO ENAME SAL ANN_SAL


--------- ---------- --------- ---------
7369 SMITH 800 9600
7499 ALLEN 1600 19200
7521 WARD 1250 15000
7566 JONES 2975 35700
7654 MARTIN 1250 15000
7698 BLAKE 2850 34200
7782 CLARK 2450 29400
7788 SCOTT 3000 36000
7839 KING 5000 60000
7844 TURNER 1500 18000
7876 ADAMS 1100 13200
7900 JAMES 950 11400
7902 FORD 3000 36000
7934 MILLER 1300 15600

14 rows selected.

SQL>

23 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME, JOB, SAL MONTHLY_SALARY, SAL+NVL(COMM,0) GROSS_SALARY,


2 SAL*12 ANNUAL_SALARY FROM EMP;

EMPNO ENAME JOB MONTHLY_SALARY GROSS_SALARY ANNUAL_SALARY


--------- ---------- --------- -------------- ------------ -------------
7369 SMITH CLERK 800 800 9600
7499 ALLEN SALESMAN 1600 1900 19200
7521 WARD SALESMAN 1250 1750 15000
7566 JONES MANAGER 2975 2975 35700
7654 MARTIN SALESMAN 1250 2650 15000
7698 BLAKE MANAGER 2850 2850 34200
7782 CLARK MANAGER 2450 2450 29400
7788 SCOTT ANALYST 3000 3000 36000
7839 KING PRESIDENT 5000 5000 60000
7844 TURNER SALESMAN 1500 1500 18000
7876 ADAMS CLERK 1100 1100 13200
7900 JAMES CLERK 950 950 11400
7902 FORD ANALYST 3000 3000 36000
7934 MILLER CLERK 1300 1300 15600

14 rows selected.

By default, alias headings appear in uppercase. If the alias contains spaces or special
characters (such as # or $), or is case sensitive, enclose the alias in double quotation
marks (" ").

SQL> SELECT EMPNO, ENAME, JOB "JOB TITLE", SAL "salary", COMM COMMISSION
2 FROM EMP;

EMPNO ENAME JOB TITLE salary COMMISSION


--------- ---------- --------- --------- ----------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600 300
7521 WARD SALESMAN 1250 500
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250 1400
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500 0
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

14 rows selected.

SQL>

24 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Concatenation Operator
You can link columns to other columns, arithmetic expressions, or constant values to create a
character expression by using the concatenation operator (||). Columns on either side of the
operator are combined to make a single output column.

SQL> SELECT EMPNO||ENAME FROM EMP;

EMPNO||ENAME
--------------------------------------------------
7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
7934MILLER

14 rows selected.

SQL> SELECT EMPNO||ENAME||JOB EMPLOYEE_INFO FROM EMP;

EMPLOYEE_INFO
-----------------------------------------------------------
7369SMITHCLERK
7499ALLENSALESMAN
7521WARDSALESMAN
7566JONESMANAGER
7654MARTINSALESMAN
7698BLAKEMANAGER
7782CLARKMANAGER
7788SCOTTANALYST
7839KINGPRESIDENT
7844TURNERSALESMAN
7876ADAMSCLERK
7900JAMESCLERK
7902FORDANALYST
7934MILLERCLERK

14 rows selected.

SQL>

SQL> SELECT SAL||COMM SALARY FROM EMP;

25 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Literal Character Strings


A literal is a character, a number, or a date that is included in the SELECT list and that is not a
column name or a column alias. It is printed for each row returned. Literal strings of free-
format text can be included in the query result and are treated the same as a column in the
SELECT list.

Date and character literals must be enclosed within single quotation marks (' '); number literals
need not.

SQL> SELECT EMPNO, ENAME, JOB, 5000, 'KARACHI', '14-AUG-1947' FROM EMP;

EMPNO ENAME JOB 5000 'KARACH '14-AUG-194


--------- ---------- --------- --------- ------- -----------
7369 SMITH CLERK 5000 KARACHI 14-AUG-1947
7499 ALLEN SALESMAN 5000 KARACHI 14-AUG-1947
7521 WARD SALESMAN 5000 KARACHI 14-AUG-1947
7566 JONES MANAGER 5000 KARACHI 14-AUG-1947
7654 MARTIN SALESMAN 5000 KARACHI 14-AUG-1947
7698 BLAKE MANAGER 5000 KARACHI 14-AUG-1947
7782 CLARK MANAGER 5000 KARACHI 14-AUG-1947
7788 SCOTT ANALYST 5000 KARACHI 14-AUG-1947
7839 KING PRESIDENT 5000 KARACHI 14-AUG-1947
7844 TURNER SALESMAN 5000 KARACHI 14-AUG-1947
7876 ADAMS CLERK 5000 KARACHI 14-AUG-1947
7900 JAMES CLERK 5000 KARACHI 14-AUG-1947
7902 FORD ANALYST 5000 KARACHI 14-AUG-1947
7934 MILLER CLERK 5000 KARACHI 14-AUG-1947

14 rows selected.

SQL> SELECT 'Mr. '||ENAME EMPLOYEE FROM EMP;

EMPLOYEE
--------------
Mr. SMITH
Mr. ALLEN
Mr. WARD
Mr. JONES
Mr. MARTIN
Mr. BLAKE
Mr. CLARK
Mr. SCOTT
Mr. KING
Mr. TURNER
Mr. ADAMS
Mr. JAMES
Mr. FORD
Mr. MILLER

14 rows selected.

SQL> SELECT 'Rs. '||SAL SALAR FROM EMP;


SQL> SELECT ENAME||' WORKS IN DEPARTMENT NUMBER '||DEPTNO EMPLOYEE FROM EMP;
SQL> SELECT ENAME||' IS EARNING '||SAL||' PER MONTH' SALARY FROM EMP;

26 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT ENAME||' works as '||JOB||' in Dept No. '||DEPTNO


"Employee Information" FROM EMP;

Employee Information
--------------------------------------------------------------------------------
SMITH works as CLERK in Dept No. 20
ALLEN works as SALESMAN in Dept No. 30
WARD works as SALESMAN in Dept No. 30
JONES works as MANAGER in Dept No. 20
MARTIN works as SALESMAN in Dept No. 30
BLAKE works as MANAGER in Dept No. 30
CLARK works as MANAGER in Dept No. 10
SCOTT works as ANALYST in Dept No. 20
KING works as PRESIDENT in Dept No. 10
TURNER works as SALESMAN in Dept No. 30
ADAMS works as CLERK in Dept No. 20
JAMES works as CLERK in Dept No. 30
FORD works as ANALYST in Dept No. 20
MILLER works as CLERK in Dept No. 10

14 rows selected.

SQL>

SQL> SELECT ENAME||' Earn Monthly '||SAL||' And His Annual Salary Is '||SAL*12
"Employee Salary Info..." FROM EMP;

Employee Salary Info...


--------------------------------------------------------------------------------
--------------------
SMITH Earn Monthly 800 And His Annual Salary Is 9600
ALLEN Earn Monthly 1600 And His Annual Salary Is 19200
WARD Earn Monthly 1250 And His Annual Salary Is 15000
JONES Earn Monthly 2975 And His Annual Salary Is 35700
MARTIN Earn Monthly 1250 And His Annual Salary Is 15000
BLAKE Earn Monthly 2850 And His Annual Salary Is 34200
CLARK Earn Monthly 2450 And His Annual Salary Is 29400
SCOTT Earn Monthly 3000 And His Annual Salary Is 36000
KING Earn Monthly 5000 And His Annual Salary Is 60000
TURNER Earn Monthly 1500 And His Annual Salary Is 18000
ADAMS Earn Monthly 1100 And His Annual Salary Is 13200
JAMES Earn Monthly 950 And His Annual Salary Is 11400
FORD Earn Monthly 3000 And His Annual Salary Is 36000
MILLER Earn Monthly 1300 And His Annual Salary Is 15600

14 rows selected.

SQL>

27 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Duplicate Rows
SQL> SELECT DEPTNO FROM EMP;

DEPTNO
---------
20
30
30
20
30
30
10
20
10
30
20
30
20
10

14 rows selected.

Eliminating Duplicate Rows


To eliminate duplicate rows in the result, include the DISTINCT keyword in the SELECT clause
immediately after the SELECT keyword. In the example on the slide, the EMPLOYEES table
actually contains 20 rows but there are only seven unique department numbers in the table.
You can specify multiple columns after the DISTINCT qualifier. The DISTINCT qualifier affects
all the selected columns, and the result is every distinct combination of the columns.
SQL> SELECT DISTINCT DEPTNO FROM EMP;

DEPTNO
---------
30
20
10

SQL> SELECT DISTINCT JOB FROM EMP;

JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST

SQL> SELECT DISTINCT DEPTNO, JOB FROM EMP;

DEPTNO JOB
--------- ---------
20 CLERK
30 SALESMAN
20 MANAGER
30 CLERK
10 PRESIDENT
30 MANAGER
10 CLERK
10 MANAGER
20 ANALYST

9 rows selected.

SQL>
28 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 2
Restricting Data
There are two types of queries

• Restricted queries (Limiting the rows)


• Unrestricted queries

Limiting the Rows Selected

You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause
contains a condition that must be met, and it directly follows the FROM clause. If the condition
is true, the row meeting the condition is returned.

In the following example, the SELECT statement retrieves records of all


employees who belong to department number 10.
SQL> SELECT * FROM EMP WHERE DEPTNO=10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL>

Display all employees who are earning more then 2000.


SQL> SELECT * FROM EMP WHERE SAL>3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10

SQL>

The following query retrieves records of all employees who are working
as CLERK.
SQL> SELECT * FROM EMP WHERE JOB='CLERK';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

Note that the job title CLERK has been specified in uppercase to ensure that it matches the job
column in the EMP table. Character strings are case sensitive. If data is stored in uppercase and
you specify condition in lowercase then the result retrieve no record.

SQL> SELECT * FROM EMP WHERE JOB='clerk';

no rows selected

SQL>
29 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Retrieve all employees who were hired on 03-DEC-1981


SQL> SELECT * FROM EMP WHERE HIREDATE='03-DEC-1981';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL>

Character Strings and Dates

Character strings and dates in the WHERE clause must be enclosed in single quotation marks
(''). Number constants, however, should not be enclosed in single quotation marks.
All character searches are case sensitive. In the following example, no rows are returned
because the EMP table stores all names in upper case:

SELECT * FROM EMP WHERE JOB='clerk';

Oracle databases store dates in an internal numeric format, representing the century, year,
month, day, hours, minutes, and seconds. The default date display is DD-MON-RR.

Comparison Conditions

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to

Comparison Conditions
Comparison conditions are used in conditions that compare one expression to another value or
expression.

SELECT EMPNO, ENAME, JOB FROM EMP WHERE DEPTNO=20;


SELECT * FROM EMP WHERE SAL<2000;
SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE SAL>3000;
SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE SAL>=3000;
SELECT EMPNO, ENAME, JOB, SAL, SAL*12 FROM EMP WHERE SAL*12>30000;
SELECT * FROM EMP WHERE SAL<=COMM;
SELECT * FROM EMP WHERE HIREDATE>'22-FEB-1981';
SELECT ENAME, HIREDATE, HIREDATE+10 FROM EMP WHERE HIREDATE+15>'01-MAR-1981';
SELECT EMPNO, ENAME FROM EMP WHERE ENAME='SMITH';
SELECT EMPNO, ENAME FROM EMP WHERE ENAME>'SMITH';
SELECT EMPNO, ENAME FROM EMP WHERE ENAME>'S';
SELECT EMPNO, ENAME FROM EMP WHERE ENAME<'C';
SELECT EMPNO, ENAME FROM EMP WHERE ENAME<>'SMITH';
SELECT EMPNO, ENAME FROM EMP WHERE SAL<>3000;
SELECT EMPNO, ENAME FROM EMP WHERE SAL!=3000;

30 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Other Comparison Conditions

Operator Meaning
BETWEEN ...AND... Between two values (inclusive),
IN(set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value

BETWEEN ... AND ...


SQL> SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20

Retrieve all employees who were hired in Feb 1981


SQL> SELECT * FROM EMP WHERE HIREDATE BETWEEN '01-FEB-1981' AND '28-FEB-1981';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

SQL> SELECT EMPNO, ENAME, JOB FROM EMP WHERE ENAME BETWEEN 'K' AND 'P';

EMPNO ENAME JOB


--------- ---------- ---------
7654 MARTIN SALESMAN
7839 KING PRESIDENT
7934 MILLER CLERK

IN ( )
SQL> SELECT * FROM EMP WHERE EMPNO IN(7788,7839,7968,7654) ;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10

SQL> SELECT * FROM EMP WHERE ENAME IN ('SCOTT','MARTIN','ALLEN','ASLAM', 'ZIA');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20

31 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The LIKE Condition

You may not always know the exact value to search for. You can select rows that match a
character pattern by using the LIKE condition. The character pattern-matching operation is
referred to as a wildcard search. Two symbols can be used to construct the search string.
% denotes zero or many characters.
_ denotes one character.

Retrieve all employees whose name begins with A


SQL> SELECT * FROM EMP WHERE ENAME LIKE 'A%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20

Retrieve all employees whose name ends with S


SQL> SELECT * FROM EMP WHERE ENAME LIKE '%S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30

Retrieve all employees who contain M anywhere in their name


SQL> SELECT * FROM EMP WHERE ENAME LIKE '%M%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

Retrieve all employees who contain sequentially A and then M in their name

SQL> SELECT * FROM EMP WHERE ENAME LIKE '%A%M%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30

Retrieve all employees who contain second character as A in their name

SQL> SELECT * FROM EMP WHERE ENAME LIKE '_A%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

32 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Retrieve all employees who contain second last character as E in their name
SQL> SELECT * FROM EMP WHERE ENAME LIKE '%E_';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

Retrieve all employees who contain first character A and third character L in
their name
SQL> SELECT * FROM EMP WHERE ENAME LIKE 'A_L%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Retrieve all employees who were hired in 87

SQL> SELECT * FROM EMP WHERE HIREDATE LIKE '%87';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20

Retrieve all employees who contains only 4 characters in their name

SQL> SELECT * FROM EMP WHERE ENAME LIKE '____';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

Checking null values


SQL> SELECT * FROM EMP WHERE MGR IS NULL;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10

SELECT * FROM EMP WHERE HIREDATE BETWEEN '01-JAN-1981' AND '31-DEC-1981';


SELECT * FROM EMP WHERE ENAME LIKE 'KHAN%';
SELECT * FROM EMP WHERE ENAME LIKE '%KHAN';
SELECT * FROM EMP WHERE ENAME LIKE '%KHAN%';
SELECT * FROM EMP WHERE ENAME LIKE '__R%';
SELECT * FROM EMP WHERE COMM IS NULL;

33 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Logical Conditions
A logical condition combines the result of two component conditions to produce a single result
based on them or inverts the result of a single condition. A row is returned only if the overall
result of the condition is true. Three logical operators are available in SQL:
• AND
• OR
• NOT
All the examples so far have specified only one condition in the WHERE clause. You can use
several conditions in one WHERE clause using the AND and OR operators.

Operator Meaning
AND Returns TRUE if both component conditions are true
OR Returns TRUE if either component condition is true
NOT Returns TRUE if the following condition is false

Using the AND Operator

AND requires both conditions to be true


If either condition is FALSE result will be FALSE in case of AND

CONDITION 1 CONDITION 2 RESULT

TRUE TRUE TRUE


TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

Retrieve all clerks of department number 20


SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE JOB='CLERK' AND DEPTNO=20;

EMPNO ENAME JOB DEPTNO


--------- ---------- --------- ---------
7369 SMITH CLERK 20
7876 ADAMS CLERK 20

Retrieve all salesman who are earning more than 1500


SQL> SELECT * FROM EMP WHERE JOB='SALESMAN' AND SAL>1500;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Retrieve all salesman who were hired before mar 1981


SQL> SELECT * FROM EMP WHERE JOB='SALESMAN' AND HIREDATE<'01-MAR-1981';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

34 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Using the OR Operator

OR requires either condition to be true.


If either condition is TRUE result will be TRUE in case of OR

CONDITION 1 CONDITION 2 RESULT

TRUE TRUE TRUE


TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

Retrieve either all clerks or all employees of department number 20


SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE JOB='CLERK' OR DEPTNO=20;

EMPNO ENAME JOB DEPTNO


--------- ---------- --------- ---------
7369 SMITH CLERK 20
7566 JONES MANAGER 20
7788 SCOTT ANALYST 20
7876 ADAMS CLERK 20
7900 JAMES CLERK 30
7902 FORD ANALYST 20
7934 MILLER CLERK 10

7 rows selected.

Using the NOT Operator

NOT operator inverse / invert the result.

NOT operator can be used with SQL Operators ( Between … and …, IN, LIKE, IS NULL)

SQL> SELECT * FROM EMP WHERE SAL NOT BETWEEN 2000 AND 3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

9 rows selected.

SQL> SELECT * FROM EMP WHERE ENAME NOT BETWEEN 'K' AND 'P';
SQL> SELECT * FROM EMP WHERE EMPNO NOT IN(7788,7839,7968,7654) ;
SQL> SELECT * FROM EMP WHERE ENAME NOT IN ('SCOTT','MARTIN','ALLEN','ASLAM');
SQL> SELECT * FROM EMP WHERE ENAME NOT LIKE 'A%';
SQL> SELECT * FROM EMP WHERE ENAME NOT LIKE '%S';

35 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Rules of Precedence
Order Evaluated Operator
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 NOT logical condition
7 AND logical condition
8 OR logical condition
The rules of precedence determine the order in which expressions are evaluated and calculated.
The table lists the default order of precedence. You can override the default order by using
parentheses around the expressions you want to calculate first.

AND Operator Evaluates first in the following example:

CLERK of department number 10 or MANAGER of any department

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP


2 WHERE JOB='MANAGER' OR JOB='CLERK' AND DEPTNO=10;

ENAME JOB SAL DEPTNO


---------- --------- --------- ---------
JONES MANAGER 2975 20
BLAKE MANAGER 2850 30
CLARK MANAGER 2450 10
MILLER CLERK 1300 10

Example of the Precedence of the AND Operator


In the above example, there are two conditions:
• The first condition is that the JOB is CLERK and the DEPTNO is 10.
• The second condition is that the JOB is MANAGER.
Therefore, the SELECT statement reads as follows:
“Select the row if an employee is a CLERK and belong to department number 10, or if the
employee is a MANAGER.”

CLERK and MANAGER of department number 10

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP


2 WHERE (JOB='MANAGER' OR JOB='CLERK') AND DEPTNO=10;

ENAME JOB SAL DEPTNO


---------- --------- --------- ---------
CLARK MANAGER 2450 10
MILLER CLERK 1300 10

Using Parentheses
In the example, there are two conditions:
• The first condition is that the JOB is CLERK or MANAGER.
• The second condition is DEPTNO is 10.
Therefore, the SELECT statement reads as follows:
“Select the row if an employee is a CLERK or a MANAGER, and if the employee belongs to
department number 10.”

36 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Sorting Data
The ORDER BY Clause
The order of rows returned in a query result is undefined. The ORDER BY clause can be used to
sort the rows. If you use the ORDER BY clause, it must be the last clause of the SQL statement.
You can specify an expression, or an alias, or column position as the sort condition.

Sorting By Column Name

SQL> SELECT * FROM EMP ORDER BY ENAME;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

14 rows selected.

Sorting on Multiple Columns

SQL> SELECT * FROM EMP ORDER BY DEPTNO, ENAME;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

14 rows selected.

SQL> SELECT * FROM EMP ORDER BY ENAME DESC;


SQL> SELECT * FROM EMP ORDER BY DEPTNO, ENAME DESC;
SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM FROM EMP ORDER BY JOB;
SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM FROM EMP ORDER BY JOB DESC;

37 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Sorting By Column Position

SQL> SELECT * FROM EMP ORDER BY 2;


SQL> SELECT * FROM EMP ORDER BY 2 DESC;
SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP ORDER BY 2;
SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP ORDER BY 4,1;

Sorting By Column Alias

SQL> SELECT ENAME,SAL,COMM, SAL*12 ANN_SAL FROM EMP ORDER BY ANN_SAL;

ENAME SAL COMM ANN_SAL


---------- --------- --------- ---------
SMITH 800 9600
JAMES 950 11400
ADAMS 1100 13200
WARD 1250 500 15000
MARTIN 1250 1400 15000
MILLER 1300 15600
TURNER 1500 0 18000
ALLEN 1600 300 19200
CLARK 2450 29400
BLAKE 2850 34200
JONES 2975 35700
SCOTT 3000 36000
FORD 3000 36000
KING 5000 60000

SQL> SELECT EMPNO, ENAME, SAL SALARY FROM EMP ORDER BY SALARY;

How Null Values Appear When Ordering (Sorting)

SQL> SELECT * FROM EMP ORDER BY COMM;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7782 CLARK MANAGER 7839 09-JUN-81 2450 10

SQL> SELECT * FROM EMP ORDER BY COMM DESC;

What is Differences in result?

SQL> SELECT EMPNO, ENAME, JOB DESIGNATION FROM EMP ORDER BY 3;


SQL> SELECT EMPNO, ENAME, JOB DESIGNATION FROM EMP ORDER BY JOB;
SQL> SELECT EMPNO, ENAME, JOB DESIGNATION FROM EMP ORDER BY DESIGNATION;

38 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 3
Single-Row Functions
Single row functions:
Manipulate data items
Accept arguments and return one value
Act on each row returned
Return one result per row
May modify the data type
Can be nested
Accept arguments which can be a column or an expression

Types of Single Row Functions


Character Functions UPPER, LOWER, INITCAP, LENGTH, SUBSTR, INSTR
Number Functions ROUND, TRUNC, MOD
Date Functions DATE
Conversion Functions TO_CHAR, TO_DATE, TO_NUMBER
General Functions NVL, COALESCE

Case Manipulation Functions


LOWER, UPPER, and INITCAP are the three case-conversion functions.
• LOWER: Converts mixed case or uppercase character strings to lowercase
• UPPER: Converts mixed case or lowercase character strings to uppercase
• INITCAP: Converts the first letter of each word to uppercase and remaining letters to
lowercase

SQL> SELECT UPPER('ORACLE'), LOWER('ORACLE'),INITCAP('ORACLE') FROM DUAL;

UPPER( LOWER( INITCA


------ ------ ------
ORACLE oracle Oracle

SQL> SELECT ENAME, UPPER(ENAME), LOWER(ENAME),INITCAP(ENAME) FROM EMP;

ENAME UPPER(ENAM LOWER(ENAM INITCAP(EN


---------- ---------- ---------- ----------
SMITH SMITH smith Smith
ALLEN ALLEN allen Allen
WARD WARD ward Ward
JONES JONES jones Jones
MARTIN MARTIN martin Martin
BLAKE BLAKE blake Blake
CLARK CLARK clark Clark
SCOTT SCOTT scott Scott
KING KING king King
TURNER TURNER turner Turner
ADAMS ADAMS adams Adams
JAMES JAMES james James
FORD FORD ford Ford
MILLER MILLER miller Miller

14 rows selected.

SELECT * FROM EMP WHERE ENAME = 'smith';


SELECT * FROM EMP WHERE ENAME = UPPER('smith');
SELECT * FROM EMP WHERE LOWER(ENAME) = 'smith';
SELECT * FROM EMP WHERE UPPER(ENAME) = 'SMITH';
SELECT * FROM EMP WHERE UPPER(ENAME) = UPPER('smith');

39 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Character Manipulation Functions


CONCAT, SUBSTR, LENGTH, INSTR, LPAD, RPAD, and TRIM are the character manipulation
functions covered in this lesson.
• SUBSTR: Extracts a string of determined length
• LENGTH: Shows the length of a string as a numeric value
• INSTR: Finds numeric position of a named character
• LPAD: Pads the character value right-justified
• RPAD: Pads the character value left-justified

SQL> SELECT LENGTH('ORACLE SQL') FROM DUAL;

LENGTH('ORACLESQL')
-------------------
10

SQL> SELECT * FROM EMP WHERE LENGTH(ENAME)=4;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP WHERE ENAME LIKE '____';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT SUBSTR('PETROMAN',4) FROM DUAL;

SUBST
-----
ROMAN

SQL> SELECT SUBSTR('PETROMAN',4,3) FROM DUAL;

SUB
---
ROM

SQL> SELECT SUBSTR('PETROMAN',-1,1) FROM DUAL;


S
-
N

SQL> SELECT SUBSTR('PETROMAN',-2,1) FROM DUAL;


S
-
A

SQL> SELECT SUBSTR('PETROMAN',-3,3) FROM DUAL;


SUB
---
MAN

40 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Retrieve all employees whose name begins with S


SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,1,1)='S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20

SQL> SELECT * FROM EMP WHERE ENAME LIKE 'S%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20

Retrieve all employees whose name contains A in second position


SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,2,1)='A';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

SQL> SELECT * FROM EMP WHERE ENAME LIKE '_A%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

Retrieve all employees whose name ends with S


SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,-1,1)='S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30

SQL> SELECT * FROM EMP WHERE ENAME LIKE '%S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30

SQL>

41 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

INSTR()
SQL> SELECT INSTR('PAKISTAN','I') FROM DUAL;

INSTR('PAKISTAN','I')
---------------------
4

SQL> SELECT INSTR('PAKISTAN','i') FROM DUAL;

INSTR('PAKISTAN','I')
---------------------
0

SQL> SELECT INSTR('PAKISTAN','TA') FROM DUAL;

INSTR('PAKISTAN','TA')
----------------------
6

SQL> SELECT INSTR('PAKISTAN','A') FROM DUAL;

INSTR('PAKISTAN','A')
---------------------
2

SQL> SELECT ENAME,INSTR(ENAME,'A') FROM EMP;

ENAME INSTR(ENAME,'A')
---------- ----------------
SMITH 0
ALLEN 1
WARD 2
JONES 0
MARTIN 2
BLAKE 3
CLARK 3
SCOTT 0
KING 0
TURNER 0
ADAMS 1
JAMES 2
FORD 0
MILLER 0

Find occurrence of 'a' start from 3rd position


SQL> SELECT INSTR('PAKISTAN','A',3) FROM DUAL;

INSTR('PAKISTAN','A',3)
-----------------------
7

Assignment CRV-0807-2011 Extract CRV, which denotes Voucher Type


CPV-0807-0111 Extract 0807, which denotes year 08 and month 07
BRV-0807-0002 Extract 08 from this BRV, 08 denotes year 2008
BPV-0807-0201 Extract 07 from this BPV, 07 denotes July of 2008
JV-0807-0128 Extract 0128 from this JV, which denotes Voucher No.

42 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Before padding or before filling means left padding or left filling


Using LPAD( ) functions
SQL> SELECT LPAD('PAK',7,'*') FROM DUAL;

LPAD('P
-------
****PAK

SQL> SELECT LPAD('PAK',7,' ') FROM DUAL;

LPAD('P
-------
PAK

SQL> SELECT LPAD('PAK',7,'->') FROM DUAL;

LPAD('P
-------
->->PAK

SQL> SELECT LPAD('PAK',7,'123-') FROM DUAL;

LPAD('P
-------
123-PAK

SQL> SELECT LPAD('4265550',12,'0321-') CELL_NO FROM DUAL;

CELL_NO
------------
0321-4265550

SQL> SELECT LPAD('4265550',11,'021-') PTCL_NO FROM DUAL;

PTCL_NO
-----------
021-4265550

SQL> SELECT EMPNO, ENAME, LPAD(EMPNO,8,'ORA-') NEW_EMPNO,


2 LPAD(ENAME,15,'.') ENAME, LPAD(ENAME,15,' ') ENAME FROM EMP;

EMPNO ENAME NEW_EMPN ENAME ENAME


--------- ---------- -------- --------------- ---------------
7369 SMITH ORA-7369 ..........SMITH SMITH
7499 ALLEN ORA-7499 ..........ALLEN ALLEN
7521 WARD ORA-7521 ...........WARD WARD
7566 JONES ORA-7566 ..........JONES JONES
7654 MARTIN ORA-7654 .........MARTIN MARTIN
7698 BLAKE ORA-7698 ..........BLAKE BLAKE
7782 CLARK ORA-7782 ..........CLARK CLARK
7788 SCOTT ORA-7788 ..........SCOTT SCOTT
7839 KING ORA-7839 ...........KING KING
7844 TURNER ORA-7844 .........TURNER TURNER
7876 ADAMS ORA-7876 ..........ADAMS ADAMS
7900 JAMES ORA-7900 ..........JAMES JAMES
7902 FORD ORA-7902 ...........FORD FORD
7934 MILLER ORA-7934 .........MILLER MILLER

14 rows selected.
43 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

After padding or after filling means right padding or right filling


Using RPAD( ) functions
SQL> SELECT EMPNO, RPAD(ENAME,40,'.') ENAME, LPAD(JOB,10,' ') JOB, SAL FROM EMP;

EMPNO ENAME JOB SAL


--------- ---------------------------------------- ---------- ---------
7369 SMITH................................... CLERK 800
7499 ALLEN................................... SALESMAN 1600
7521 WARD.................................... SALESMAN 1250
7566 JONES................................... MANAGER 2975
7654 MARTIN.................................. SALESMAN 1250
7698 BLAKE................................... MANAGER 2850
7782 CLARK................................... MANAGER 2450
7788 SCOTT................................... ANALYST 3000
7839 KING.................................... PRESIDENT 5000
7844 TURNER.................................. SALESMAN 1500
7876 ADAMS................................... CLERK 1100
7900 JAMES................................... CLERK 950
7902 FORD.................................... ANALYST 3000
7934 MILLER.................................. CLERK 1300

14 rows selected.

SQL>

Number Functions
Number functions accept numeric input and return numeric values. This section describes some
of the number functions.

ROUND Function
The ROUND function rounds the column, expression, or value to n decimal places. If the second
argument is 0 or is missing, the value is rounded to zero decimal places. If the second
argument is 2, the value is rounded to two decimal places. Conversely, if the second argument
is -2, the value is rounded to two decimal places to the left.
The ROUND function can also be used with date functions. You will see examples later in this
lesson.

TRUNC Function
The TRUNC function truncates the column, expression, or value to n decimal places.
The TRUNC function works with arguments similar to those of the ROUND function. If the
second argument is 0 or is missing, the value is truncated to zero decimal places. If the second
argument is 2, the value is truncated to two decimal places. Conversely, if the second argument
is -2, the value is truncated to two decimal places to the left.
Like the ROUND function, the TRUNC function can be used with date functions.

MOD Function
The MOD function finds the remainder of value1 divided by value2.
Note: The MOD function is often used to determine if a value is odd or even.

44 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

ROUND ( ) function with numbers


SQL> SELECT
2 ROUND(5.9283),
3 ROUND(5.9283,0),
4 ROUND(5.9283,1),
5 ROUND(5.9283,2),
6 ROUND(5.9283,3)
7 FROM DUAL;

ROUND(5.9283) ROUND(5.9283,0) ROUND(5.9283,1) ROUND(5.9283,2) ROUND(5.9283,3)


------------- --------------- --------------- --------------- ---------------
6 6 5.9 5.93 5.928

SQL> SELECT
2 ROUND(3.5397),
3 ROUND(3.5397,0),
4 ROUND(3.5397,1),
5 ROUND(3.5397,2),
6 ROUND(3.5397,3)
7 FROM DUAL;

ROUND(3.5397) ROUND(3.5397,0) ROUND(3.5397,1) ROUND(3.5397,2) ROUND(3.5397,3)


------------- --------------- --------------- --------------- ---------------
4 4 3.5 3.54 3.54

TRUNC ( ) function with numbers


SQL> SELECT
2 TRUNC(5.9283),
3 TRUNC(5.9283,0),
4 TRUNC(5.9283,1),
5 TRUNC(5.9283,2),
6 TRUNC(5.9283,3)
7 FROM DUAL;

TRUNC(5.9283) TRUNC(5.9283,0) TRUNC(5.9283,1) TRUNC(5.9283,2) TRUNC(5.9283,3)


------------- --------------- --------------- --------------- ---------------
5 5 5.9 5.92 5.928

SQL> SELECT
2 TRUNC(3.5397),
3 TRUNC(3.5397,0),
4 TRUNC(3.5397,1),
5 TRUNC(3.5397,2),
6 TRUNC(3.5397,3)
7 FROM DUAL;

TRUNC(3.5397) TRUNC(3.5397,0) TRUNC(3.5397,1) TRUNC(3.5397,2) TRUNC(3.5397,3)


------------- --------------- --------------- --------------- ---------------
3 3 3.5 3.53 3.539

SQL>

45 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

ROUND ( ) with -Ve Decimal Request


-1 nearest 10 10 20 30 40...
-2 nearest 100 100 200 300 400...
-3 nearest 1000 1000 2000 3000 4000...
-4 nearest 10000 10000 20000 30000 40000...

SQL> SELECT
2 ROUND(3175.9283,-1),
3 ROUND(3175.9283,-2),
4 ROUND(3175.9283,-3),
5 ROUND(3175.9283,-4)
6 FROM DUAL;

ROUND(3175.9283,-1) ROUND(3175.9283,-2) ROUND(3175.9283,-3) ROUND(3175.9283,-4)


------------------- ------------------- ------------------- -------------------
3180 3200 3000 0

SQL> SELECT
2 ROUND(5175.9283,-1),
3 ROUND(5175.9283,-2),
4 ROUND(5175.9283,-3),
5 ROUND(5175.9283,-4)
6 FROM DUAL;

ROUND(5175.9283,-1) ROUND(5175.9283,-2) ROUND(5175.9283,-3) ROUND(5175.9283,-4)


------------------- ------------------- ------------------- -------------------
5180 5200 5000 10000

SQL> SELECT
2 ROUND(5675.9283,-1),
3 ROUND(5675.9283,-2),
4 ROUND(5675.9283,-3),
5 ROUND(5675.9283,-4)
6 FROM DUAL;

ROUND(5675.9283,-1) ROUND(5675.9283,-2) ROUND(5675.9283,-3) ROUND(5675.9283,-4)


------------------- ------------------- ------------------- -------------------
5680 5700 6000 10000

TRUNC ( ) with -Ve Decimal Request

SQL> SELECT
2 TRUNC(5675.9283,-1),
3 TRUNC(5675.9283,-2),
4 TRUNC(5675.9283,-3),
5 TRUNC(5675.9283,-4)
6 FROM DUAL;

TRUNC(5675.9283,-1) TRUNC(5675.9283,-2) TRUNC(5675.9283,-3) TRUNC(5675.9283,-4)


------------------- ------------------- ------------------- -------------------
5670 5600 5000 0

SQL>

46 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

MOD ( )
SQL> SELECT MOD(3,2), MOD(10,2), MOD(15,3), MOD(52,6), MOD(230,5) FROM DUAL;

MOD(3,2) MOD(10,2) MOD(15,3) MOD(52,6) MOD(230,5)


--------- --------- --------- --------- ----------
1 0 0 4 0

The example calculates the remainder of the salary after dividing it by 500 for all employees.

SQL> SELECT ENAME, SAL,


2 MOD(SAL,500),
3 SAL-MOD(SAL,500),
4 (SAL-MOD(SAL,500))/500 NOTES_500,
5 -- (SAL-MOD(SAL,500))/1000 NOTES_1000,
6 TRUNC((SAL-MOD(SAL,500))/1000) NOTES_1000
7 FROM EMP;

ENAME SAL MOD(SAL,500) SAL-MOD(SAL,500) NOTES_500 NOTES_1000


---------- --------- ------------ ---------------- --------- ----------
SMITH 800 300 500 1 0
ALLEN 1600 100 1500 3 1
WARD 1250 250 1000 2 1
JONES 2975 475 2500 5 2
MARTIN 1250 250 1000 2 1
BLAKE 2850 350 2500 5 2
CLARK 2450 450 2000 4 2
SCOTT 3000 0 3000 6 3
KING 5000 0 5000 10 5
TURNER 1500 0 1500 3 1
ADAMS 1100 100 1000 2 1
JAMES 950 450 500 1 0
FORD 3000 0 3000 6 3
MILLER 1300 300 1000 2 1

14 rows selected.

SQL>

47 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Working with Dates


Arithmetic with Dates
SQL> SELECT SYSDATE, SYSDATE-1, SYSDATE+1 FROM DUAL;

SYSDATE SYSDATE-1 SYSDATE+1


--------- --------- ---------
24-JUL-08 23-JUL-08 25-JUL-08

SQL> SELECT ENAME,HIREDATE,HIREDATE-5,HIREDATE+5 FROM EMP;

ENAME HIREDATE HIREDATE- HIREDATE+


---------- --------- --------- ---------
SMITH 17-DEC-80 12-DEC-80 22-DEC-80
ALLEN 20-FEB-81 15-FEB-81 25-FEB-81
WARD 22-FEB-81 17-FEB-81 27-FEB-81
JONES 02-APR-81 28-MAR-81 07-APR-81
MARTIN 28-SEP-81 23-SEP-81 03-OCT-81
BLAKE 01-MAY-81 26-APR-81 06-MAY-81
CLARK 09-JUN-81 04-JUN-81 14-JUN-81
SCOTT 19-APR-87 14-APR-87 24-APR-87
KING 17-NOV-81 12-NOV-81 22-NOV-81
TURNER 08-SEP-81 03-SEP-81 13-SEP-81
ADAMS 23-MAY-87 18-MAY-87 28-MAY-87
JAMES 03-DEC-81 28-NOV-81 08-DEC-81
FORD 03-DEC-81 28-NOV-81 08-DEC-81
MILLER 23-JAN-82 18-JAN-82 28-JAN-82

14 rows selected.

Finding job duration


SQL> SELECT
2 ENAME,SYSDATE,HIREDATE,
3 SYSDATE-HIREDATE IN_DAYS,
4 (SYSDATE - HIREDATE) / 7 IN_WEEKS,
5 (SYSDATE - HIREDATE) / 30 IN_MONTHS,
6 (SYSDATE - HIREDATE) / 365 IN_YEARS FROM EMP;

ENAME SYSDATE HIREDATE IN_DAYS IN_WEEKS IN_MONTHS IN_YEARS


---------- --------- --------- --------- --------- --------- ---------
SMITH 24-JUL-08 17-DEC-80 10081.777 1440.2538 336.05923 27.621306
ALLEN 24-JUL-08 20-FEB-81 10016.777 1430.9681 333.89256 27.443224
WARD 24-JUL-08 22-FEB-81 10014.777 1430.6824 333.82589 27.437745
JONES 24-JUL-08 02-APR-81 9975.7768 1425.111 332.52589 27.330895
MARTIN 24-JUL-08 28-SEP-81 9796.7768 1399.5395 326.55923 26.840484
BLAKE 24-JUL-08 01-MAY-81 9946.7768 1420.9681 331.55923 27.251443
CLARK 24-JUL-08 09-JUN-81 9907.7768 1415.3967 330.25923 27.144594
SCOTT 24-JUL-08 19-APR-87 7767.7768 1109.6824 258.92589 21.28158
KING 24-JUL-08 17-NOV-81 9746.7768 1392.3967 324.89256 26.703498
TURNER 24-JUL-08 08-SEP-81 9816.7768 1402.3967 327.22589 26.895279
ADAMS 24-JUL-08 23-MAY-87 7733.7768 1104.8253 257.79256 21.188429
JAMES 24-JUL-08 03-DEC-81 9730.7768 1390.111 324.35923 26.659662
FORD 24-JUL-08 03-DEC-81 9730.7768 1390.111 324.35923 26.659662
MILLER 24-JUL-08 23-JAN-82 9679.7768 1382.8253 322.65923 26.519936

14 rows selected.

SQL>

48 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Oracle Date Format


Oracle database stores dates in an internal numeric format, representing the century, year,
month, day, hours, minutes, and seconds.
The default display and input format for any date is DD-MON-RR. Valid Oracle dates are
between January 1, 4712 B.C. and December 31, 9999 A.D.

This data is stored internally as follows:


CENTURY YEAR MONTH DAY HOUR MINUTE SECOND
19 94 06 07 5 10 43

Centuries and the Year 2000

The Oracle server is year 2000 compliant. When a record with a date column is inserted into a
table, the century information is picked up from the SYSDATE function. However, when the
date column is displayed on the screen, the century component is not displayed by default.
The DATE data type always stores year information as a four-digit number internally: two digits
for the century and two digits for the year. For example, the Oracle database stores the year as
1996 or 2001, and not just as 96 or 01.

The SYSDATE Function

SYSDATE is a date function that returns the current database server date and time. You can
use SYSDATE just as you would use any other column name. For example, you can display the
current date by selecting SYSDATE from a table. It is customary to select SYSDATE from a
dummy table called DUAL.

Date Functions

Date functions operate on Oracle dates. All date functions return a value of DATE data type
except MONTHS_BETWEEN, which returns a numeric value.

• MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and


date2. The result can be positive or negative. If date1 is later than date2, the result is
positive; if date1 is earlier than date2, the result is negative. The noninteger part of the
result represents a portion of the month.

• ADD_MONTHS(date, n): Adds n number of calendar months to date. The value of n must
be an integer and can be negative.

• NEXT_DAY(date, 'char'): Finds the date of the next specified day of the week ('char')
following date. The value of char may be a number representing a day or a character string.

• LAST_DAY(date): Finds the date of the last day of the month that contains date.

• ROUND(date[,'fmt']): Returns date rounded to the unit specified by the format model
fmt. If the format model fmt is omitted, date is rounded to the nearest day.

• TRUNC(date[, 'fmt']): Returns date with the time portion of the day truncated to the unit
specified by the format model fmt. If the format model fmt is omitted, date is truncated to
the nearest day.

49 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT
2 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947') TOT_MONTHS,
3 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')/12 TOT_YEARS,
4 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*4 TOT_WEEKS,
5 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*30 TOT_DAYS,
6 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*30*24 TOT_HOURS
7 FROM DUAL;

TOT_MONTHS TOT_YEARS TOT_WEEKS TOT_DAYS TOT_HOURS


---------- --------- --------- --------- ---------
732 61 2928 21960 527040

SQL>

SQL> SELECT
2 ADD_MONTHS('14-AUG-2008',1) AFTER_1_MONTH,
3 ADD_MONTHS('14-AUG-2008',6) AFTER_6_MONTHS,
4 ADD_MONTHS('14-AUG-2008',12) AFTER_1_YEAR,
5 ADD_MONTHS('14-AUG-2008',12*3) AFTER_3_YEARS,
6 ADD_MONTHS('14-AUG-2008',-3) BEFORE_3_MONTHS,
7 ADD_MONTHS('14-AUG-2008',-12*3) BEFORE_3_YEARS
8 FROM DUAL;

AFTER_1_M AFTER_6_M AFTER_1_Y AFTER_3_Y BEFORE_3_ BEFORE_3_


--------- --------- --------- --------- --------- ---------
14-SEP-08 14-FEB-09 14-AUG-09 14-AUG-11 14-MAY-08 14-AUG-05

SQL>

What was the first Thursday, Friday, Saturday & Sunday after August
14, 1947
SQL> SELECT
2 NEXT_DAY('14-AUG-1947','THURSDAY') FIRST_THU,
3 NEXT_DAY('14-AUG-1947','FRIDAY') FIRST_FRI,
4 NEXT_DAY('14-AUG-1947','SATURDAY') FIRST_SAT,
5 NEXT_DAY('14-AUG-1947','SUNDAY') FIRST_SUN
6 FROM DUAL;

FIRST_THU FIRST_FRI FIRST_SAT FIRST_SUN


--------- --------- --------- ---------
21-AUG-47 15-AUG-47 16-AUG-47 17-AUG-47

SQL>

How to find last day of the month


SQL> SELECT
2 LAST_DAY('14-AUG-1947'),
3 LAST_DAY('14-FEB-1947'),
4 LAST_DAY('14-FEB-2008')
5 FROM DUAL;

LAST_DAY( LAST_DAY( LAST_DAY(


--------- --------- ---------
31-AUG-47 28-FEB-47 29-FEB-08

SQL>

50 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Find out duration of each employee


SQL> SELECT EMPNO, ENAME, SYSDATE, HIREDATE,
2 MONTHS_BETWEEN(SYSDATE,HIREDATE) IN_MONTHS,
3 MONTHS_BETWEEN(SYSDATE,HIREDATE)/12 IN_YEARS,
4 MONTHS_BETWEEN(SYSDATE,HIREDATE)*30 IN_DAYS
5 FROM EMP;

EMPNO ENAME SYSDATE HIREDATE IN_MONTHS IN_YEARS IN_DAYS


--------- ---------- --------- --------- --------- --------- ---------
7369 SMITH 24-JUL-08 17-DEC-80 331.25276 27.604397 9937.5828
7499 ALLEN 24-JUL-08 20-FEB-81 329.15598 27.429665 9874.6795
7521 WARD 24-JUL-08 22-FEB-81 329.09147 27.424289 9872.7441
7566 JONES 24-JUL-08 02-APR-81 327.73663 27.311386 9832.0989
7654 MARTIN 24-JUL-08 28-SEP-81 321.89792 26.824827 9656.9376
7698 BLAKE 24-JUL-08 01-MAY-81 326.76889 27.230741 9803.0666
7782 CLARK 24-JUL-08 09-JUN-81 325.51082 27.125902 9765.3247
7788 SCOTT 24-JUL-08 19-APR-87 255.18824 21.265687 7655.6473
7839 KING 24-JUL-08 17-NOV-81 320.25276 26.68773 9607.5828
7844 TURNER 24-JUL-08 08-SEP-81 322.54308 26.87859 9676.2924
7876 ADAMS 24-JUL-08 23-MAY-87 254.05921 21.171601 7621.7763
7900 JAMES 24-JUL-08 03-DEC-81 319.70437 26.642031 9591.1311
7902 FORD 24-JUL-08 03-DEC-81 319.70437 26.642031 9591.1311
7934 MILLER 24-JUL-08 23-JAN-82 318.05921 26.504934 9541.7763

14 rows selected.

What was the first Sunday after hiring


What was the last day in which each employee was hired
What was the date after two months of hiring
SQL> SELECT
2 EMPNO, ENAME, HIREDATE,
3 NEXT_DAY(HIREDATE,'SUNDAY') FIRST_SUN,
4 LAST_DAY(HIREDATE) LAST_DAY,
5 ADD_MONTHS(HIREDATE,2) AFTER_2_MONTHS
6 FROM EMP;

EMPNO ENAME HIREDATE FIRST_SUN LAST_DAY AFTER_2_M


--------- ---------- --------- --------- --------- ---------
7369 SMITH 17-DEC-80 21-DEC-80 31-DEC-80 17-FEB-81
7499 ALLEN 20-FEB-81 22-FEB-81 28-FEB-81 20-APR-81
7521 WARD 22-FEB-81 01-MAR-81 28-FEB-81 22-APR-81
7566 JONES 02-APR-81 05-APR-81 30-APR-81 02-JUN-81
7654 MARTIN 28-SEP-81 04-OCT-81 30-SEP-81 28-NOV-81
7698 BLAKE 01-MAY-81 03-MAY-81 31-MAY-81 01-JUL-81
7782 CLARK 09-JUN-81 14-JUN-81 30-JUN-81 09-AUG-81
7788 SCOTT 19-APR-87 26-APR-87 30-APR-87 19-JUN-87
7839 KING 17-NOV-81 22-NOV-81 30-NOV-81 17-JAN-82
7844 TURNER 08-SEP-81 13-SEP-81 30-SEP-81 08-NOV-81
7876 ADAMS 23-MAY-87 24-MAY-87 31-MAY-87 23-JUL-87
7900 JAMES 03-DEC-81 06-DEC-81 31-DEC-81 03-FEB-82
7902 FORD 03-DEC-81 06-DEC-81 31-DEC-81 03-FEB-82
7934 MILLER 23-JAN-82 24-JAN-82 31-JAN-82 23-MAR-82

14 rows selected.

SQL>

51 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

ROUND ( ) & TRUNC ( ) functions with date


The ROUND and TRUNC functions can be used for number and date values. When used with
dates, these functions round or truncate to the specified format model. Therefore, you can
round dates to the nearest year or month.

ROUND (MONTH)
01-15 FIRST DAY OF SAME MONTH
16-31 FIRST DAY OF NEXT MONTH

ROUND (YEAR)
01-JAN ... 30-JUN FIRST DAY OF SAME YEAR
01-JUL ... 31-DEC FIRST DAY OF NEXT YEAR

TRUNC (MONTH)
01-31 FIRST DAY OF SAME MONTH

TRUNC (YEAR)
01-JAN ... 31-DEC FIRST DAY OF SAME YEAR.

ROUND (DD) DEFAULT IF NOT SPECIFIED


LESS THAN 12:00PM SAM DAY
MORE THAN 12:00PM NEXT DAY

ROUND (DAY)
BEFORE 12:00PM WEDNESDAY, PREVIOUS SUNDAY OF THE WEEK
AFTER 12:00PM WEDNESDAY, NEXT SUNDAY OF THE WEEK

TRUNC (DD) Same Day, eliminating time portion from date


TRUNC (DAY) Previous Sunday

Assume SYSDATE is 24-JUL-2008


SQL> SELECT SYSDATE, ROUND(SYSDATE,'MONTH'), TRUNC(SYSDATE,'MONTH') FROM DUAL;

SYSDATE ROUND(SYS TRUNC(SYS


--------- --------- ---------
24-JUL-08 01-AUG-08 01-JUL-08

SQL> SELECT
2 SYSDATE-10,
3 ROUND(SYSDATE-10,'MONTH'),
4 TRUNC(SYSDATE-10,'MONTH')
5 FROM DUAL;

SYSDATE-1 ROUND(SYS TRUNC(SYS


--------- --------- ---------
14-JUL-08 01-JUL-08 01-JUL-08

SQL> SELECT
2 SYSDATE-30,
3 ROUND(SYSDATE-30,'MONTH'),
4 TRUNC(SYSDATE-30,'MONTH')
5 FROM DUAL;

24-JUN-08 01-JUL-08 01-JUN-08

52 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT SYSDATE, ROUND(SYSDATE,'YEAR'), TRUNC(SYSDATE,'YEAR') FROM DUAL;

SYSDATE ROUND(SYS TRUNC(SYS


--------- --------- ---------
24-JUL-08 01-JAN-09 01-JAN-08

SQL> SELECT
2 SYSDATE-10,
3 ROUND(SYSDATE-10,'YEAR'),
4 TRUNC(SYSDATE-10,'YEAR')
5 FROM DUAL;

SYSDATE-1 ROUND(SYS TRUNC(SYS


--------- --------- ---------
14-JUL-08 01-JAN-09 01-JAN-08

SQL> SELECT
2 SYSDATE-30,
3 ROUND(SYSDATE-30,'MONTH'),
4 TRUNC(SYSDATE-30,'MONTH')
5 FROM DUAL;

SYSDATE-3 ROUND(SYS TRUNC(SYS


--------- --------- ---------
24-JUN-08 01-JUL-08 01-JUN-08

SQL> SELECT
2 SYSDATE,
3 NEXT_DAY(SYSDATE,'SUNDAY') COMMING_SUNDAY,
4 ROUND(SYSDATE,'DAY') COMMING_SUNDAY,
5 TRUNC(SYSDATE,'DAY') LAST_SUNDAY
6 FROM DUAL;

SYSDATE COMMING_S COMMING_S LAST_SUND


--------- --------- --------- ---------
24-JUL-08 27-JUL-08 27-JUL-08 20-JUL-08

Suppose date is 24-JUL-2008 and time is 13:55


SQL> SELECT SYSDATE, ROUND(SYSDATE), TRUNC(SYSDATE) FROM DUAL;

SYSDATE ROUND(SYS TRUNC(SYS


--------- --------- ---------
24-JUL-08 25-JUL-08 24-JUL-08

Note: Oracle also store time with date. When comparing date column without time portion, it is
recommended to use trunc() function with that column. Because trunc ( ) eliminate time
portion. Remember TRUNC (DD) remove time portion and TRUNC(DD) is default.

SQL> SELECT * FROM EMP WHERE TRUNC(HIREDATE)='17-DEC-1980';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

53 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Conversion Functions
In addition to Oracle data types, columns of tables in an Oracle9i database can be defined using
ANSI, DB2, and SQL/DS data types. However, the Oracle server internally converts such data
types to Oracle data types.

In some cases, Oracle server uses data of one data type where it expects data of a different
data type. When this happens, Oracle server can automatically convert the data to the
expected data type. This data type conversion can be done implicitly by Oracle server, or
explicitly by the user.

Implicit data type conversions work according to the rules explained in the next two slides.
Explicit data type conversions are done by using the conversion functions. Conversion functions
convert a value from one data type to another. Generally, the form of the function names
follows the convention data type TO data type. The first data type is the input data type; the
last data type is the output.

Note: Although implicit data type conversion is available, it is recommended that you do
explicit data type conversion to ensure the reliability of your SQL statements.

Explicit Data Type Conversion

TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHAR

54 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Using the TO_CHAR Function with Dates

Displaying a Date in a Specific Format


Previously, all Oracle date values were displayed in the DD-MON-YY format. You can use the
TO_CHAR function to convert a date from this default format to one specified by you.

The format model:


• Must be enclosed in single quotation marks and is case sensitive
• Can include any valid date format element
• Has an fm element to remove padded blanks or suppress leading zeros
• Is separated from the date value by a comma

DD 01-31
MON JAN, FEB, ... DEC
Mon Jan, Feb, ... Dec
MONTH JANUARY, FEBRUARY, ... DECEMBER
Month January, February, ... December
YY 01, 02, 03 ... (Century)
RR 01, 02, 03 ... (Century)
YEAR SPELL OUT YEAR
Year Spell Out Year
HH12 1 - 12
HH24 0 - 23
AM
PM
MI 01 - 59 MINUTES
SS 01 - 59 SECONDS
DY MON, TUE, .... SUN
Dy Mon, Tue, .... Sun
DAY MONDAY, TUESDAY, ... SUNDAY
Day Monday, Tuesday, ... Sunday

How to display time portion


SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH24:MI:SS') FROM DUAL;

24-JUL-08 14:29:37
SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH12:MI:SS AM') FROM DUAL;

24-JUL-08 02:29:41 PM
SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH12:MI:SS') FROM DUAL;

24-JUL-08 02:30:03
SQL> SELECT TO_CHAR(SYSDATE,'HH12:MI:SS') FROM DUAL;

02:31:40
SQL> SELECT TO_CHAR(SYSDATE,'HH12:MI:SS AM') FROM DUAL;

02:31:55 PM
SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') FROM DUAL;

14:32:05

55 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/YY HH12:MI:SS AM') FROM DUAL;

24/07/08 02:38:33 PM

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/RR HH12:MI:SS AM') FROM DUAL;

24/07/08 02:38:44 PM

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/RRRR HH12:MI:SS AM') FROM DUAL;

24/07/2008 02:38:49 PM

Adding 3 Days
SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-RR HH24:MI:SS'),
2 TO_CHAR(SYSDATE+3,'DD-MON-RR HH24:MI:SS')
3 FROM DUAL;

24-JUL-08 15:16:18 27-JUL-08 15:16:18

Adding 3 Hours
SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-RR HH24:MI:SS'),
2 TO_CHAR(SYSDATE+3/24,'DD-MON-RR HH24:MI:SS')
3 FROM DUAL;

24-JUL-08 15:16:44 24-JUL-08 18:16:44

SQL> SELECT TO_CHAR(SYSDATE,'DAY, MONTH DD RRRR') FROM DUAL;

THURSDAY , JULY 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Day, Month DD RRRR') FROM DUAL;

Thursday , July 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Day, Mon DD RRRR') FROM DUAL;

Thursday , Jul 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Dy, Mon DD RRRR') FROM DUAL;

Thu, Jul 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'DAY Day DY Dy') from dual;

THURSDAY Thursday THU Thu

56 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR(SYSDATE,'DD DDTH DDSP DDSPTH Ddth DdSP DdSPTH') FROM DUAL;
24 24TH TWENTY-FOUR TWENTY-FOURTH 24th Twenty-Four Twenty-Fourth

SQL> SELECT TO_CHAR(SYSDATE,'MM MmTH MmSP MmSPTH MON Mon MONTH Month') FROM
DUAL;

07 07th Seven Seventh JUL Jul JULY July

SQL> SELECT TO_CHAR(SYSDATE,'YY RR YYYY RRRR YEAR, Year') FROM DUAL;

08 08 2008 2008 TWO THOUSAND EIGHT, Two Thousand Eight

SQL> SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'Day, Month dd, rrrr') HIREDATE


FROM EMP;

ENAME HIREDATE HIREDATE


---------- --------- -----------------------------
SMITH 17-DEC-80 Wednesday, December 17, 1980
ALLEN 20-FEB-81 Friday , February 20, 1981
WARD 22-FEB-81 Sunday , February 22, 1981
JONES 02-APR-81 Thursday , April 02, 1981
MARTIN 28-SEP-81 Monday , September 28, 1981
BLAKE 01-MAY-81 Friday , May 01, 1981
CLARK 09-JUN-81 Tuesday , June 09, 1981
SCOTT 19-APR-87 Sunday , April 19, 1987
KING 17-NOV-81 Tuesday , November 17, 1981
TURNER 08-SEP-81 Tuesday , September 08, 1981
ADAMS 23-MAY-87 Saturday , May 23, 1987
JAMES 03-DEC-81 Thursday , December 03, 1981
FORD 03-DEC-81 Thursday , December 03, 1981
MILLER 23-JAN-82 Saturday , January 23, 1982

SQL> SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'fmDay, Month dd, rrrr') HIREDATE


FROM EMP;

ENAME HIREDATE HIREDATE


---------- --------- -----------------------------
SMITH 17-DEC-80 Wednesday, December 17, 1980
ALLEN 20-FEB-81 Friday, February 20, 1981
WARD 22-FEB-81 Sunday, February 22, 1981
JONES 02-APR-81 Thursday, April 2, 1981
MARTIN 28-SEP-81 Monday, September 28, 1981
BLAKE 01-MAY-81 Friday, May 1, 1981
CLARK 09-JUN-81 Tuesday, June 9, 1981
SCOTT 19-APR-87 Sunday, April 19, 1987
KING 17-NOV-81 Tuesday, November 17, 1981
TURNER 08-SEP-81 Tuesday, September 8, 1981
ADAMS 23-MAY-87 Saturday, May 23, 1987
JAMES 03-DEC-81 Thursday, December 3, 1981
FORD 03-DEC-81 Thursday, December 3, 1981
MILLER 23-JAN-82 Saturday, January 23, 1982

SQL> SELECT TO_CHAR(SYSDATE,'DdTH "of" Month RRRR') FROM DUAL;

24th of July 2008


57 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Using the TO_CHAR Function with Numbers


SQL> SELECT
2 TO_CHAR(58,'99.9') A,
3 TO_CHAR(58,'00.0') B,
4 TO_CHAR(58,'$99.9') C,
5 TO_CHAR(58,'$00.0') D
6 FROM DUAL;

A B C D
----- ----- ------ ------
58.0 58.0 $58.0 $58.0

SQL> SELECT
2 TO_CHAR(58,'999.99') A,
3 TO_CHAR(58,'000.00') B,
4 TO_CHAR(58,'$999.99') C,
5 TO_CHAR(58,'$000.00') D
6 FROM DUAL;

A B C D
------- ------- -------- --------
58.00 058.00 $58.00 $058.00

SQL> SELECT
2 TO_CHAR(58,'99,999.99') A,
3 TO_CHAR(58,'00,000.00') B,
4 TO_CHAR(58,'$99,999.99') C,
5 TO_CHAR(58,'$00,000.00') D
6 FROM DUAL;

A B C D
---------- ---------- ----------- -----------
58.00 00,058.00 $58.00 $00,058.00

SQL> SELECT
2 TO_CHAR(58755,'99,999.99') A,
3 TO_CHAR(58755,'00,000.00') B,
4 TO_CHAR(58755,'$99,999.99') C,
5 TO_CHAR(58755,'$00,000.00') D
6 FROM DUAL;

A B C D
---------- ---------- ----------- -----------
58,755.00 58,755.00 $58,755.00 $58,755.00

SQL> SELECT
2 TO_CHAR(5858755,'99,999.99') A,
3 TO_CHAR(5858755,'00,000.00') B,
4 TO_CHAR(5858755,'$99,999.99') C,
5 TO_CHAR(5858755,'$00,000.00') D
6 FROM DUAL;

A B C D
---------- ---------- ----------- -----------
########## ########## ########### ###########

58 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME,


2 HIREDATE,
3 TO_CHAR(HIREDATE,'DD DDSP') "DATE",
4 TO_CHAR(HIREDATE,'MON-RRRR') MON_YEAR,
5 TO_CHAR(HIREDATE,'RRRR') YEAR,
6 TO_CHAR(SAL,'99,999.99') SALARY
7 FROM EMP;

EMPNO ENAME HIREDATE DATE MON_YEAR YEAR SALARY


--------- ---------- --------- -------------------- -------- ---- ----------
7369 SMITH 17-DEC-80 17 SEVENTEEN DEC-1980 1980 800.00
7499 ALLEN 20-FEB-81 20 TWENTY FEB-1981 1981 1,600.00
7521 WARD 22-FEB-81 22 TWENTY-TWO FEB-1981 1981 1,250.00
7566 JONES 02-APR-81 02 TWO APR-1981 1981 2,975.00
7654 MARTIN 28-SEP-81 28 TWENTY-EIGHT SEP-1981 1981 1,250.00
7698 BLAKE 01-MAY-81 01 ONE MAY-1981 1981 2,850.00
7782 CLARK 09-JUN-81 09 NINE JUN-1981 1981 2,450.00
7788 SCOTT 19-APR-87 19 NINETEEN APR-1987 1987 3,000.00
7839 KING 17-NOV-81 17 SEVENTEEN NOV-1981 1981 5,000.00
7844 TURNER 08-SEP-81 08 EIGHT SEP-1981 1981 1,500.00
7876 ADAMS 23-MAY-87 23 TWENTY-THREE MAY-1987 1987 1,100.00
7900 JAMES 03-DEC-81 03 THREE DEC-1981 1981 950.00
7902 FORD 03-DEC-81 03 THREE DEC-1981 1981 3,000.00
7934 MILLER 23-JAN-82 23 TWENTY-THREE JAN-1982 1982 1,300.00

14 rows selected.

SQL> SELECT ENAME, HIREDATE,


2 TO_CHAR(HIREDATE,'Day') HIRE_DAY,
3 NEXT_DAY(HIREDATE,'SUNDAY') SUNDAY,
4 TO_CHAR(NEXT_DAY(HIREDATE,'SUNDAY'),'DD') SUNDAY,
5 TO_CHAR(LAST_DAY(HIREDATE),'Day') LAST_DAY,
6 TO_CHAR(ADD_MONTHS(HIREDATE,1),'Day') AFTER_2_MONTHS,
7 TO_CHAR(SAL,'09,999.99') SALARY
8 FROM EMP;

ENAME HIREDATE HIRE_DAY SUNDAY SU LAST_DAY AFTER_2_M SALARY


---------- --------- --------- --------- -- --------- --------- ----------
SMITH 17-DEC-80 Wednesday 21-DEC-80 21 Wednesday Saturday 00,800.00
ALLEN 20-FEB-81 Friday 22-FEB-81 22 Saturday Friday 01,600.00
WARD 22-FEB-81 Sunday 01-MAR-81 01 Saturday Sunday 01,250.00
JONES 02-APR-81 Thursday 05-APR-81 05 Thursday Saturday 02,975.00
MARTIN 28-SEP-81 Monday 04-OCT-81 04 Wednesday Wednesday 01,250.00
BLAKE 01-MAY-81 Friday 03-MAY-81 03 Sunday Monday 02,850.00
CLARK 09-JUN-81 Tuesday 14-JUN-81 14 Tuesday Thursday 02,450.00
SCOTT 19-APR-87 Sunday 26-APR-87 26 Thursday Tuesday 03,000.00
KING 17-NOV-81 Tuesday 22-NOV-81 22 Monday Thursday 05,000.00
TURNER 08-SEP-81 Tuesday 13-SEP-81 13 Wednesday Thursday 01,500.00
ADAMS 23-MAY-87 Saturday 24-MAY-87 24 Sunday Tuesday 01,100.00
JAMES 03-DEC-81 Thursday 06-DEC-81 06 Thursday Sunday 00,950.00
FORD 03-DEC-81 Thursday 06-DEC-81 06 Thursday Sunday 03,000.00
MILLER 23-JAN-82 Saturday 24-JAN-82 24 Sunday Tuesday 01,300.00

Assignment

1. Find all employees who were hired on Friday or Sunday.


2. Find all employees who were hired in FEB
3. Find all employees who were hired in 1981

59 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

TO_NUMBER ( )

SQL> SELECT 4+3 FROM DUAL;

4+3
---------
7

SQL> SELECT '4'+'3' FROM DUAL;

'4'+'3'
---------
7

SQL> SELECT TO_NUMBER('4')+TO_NUMBER('3') FROM DUAL;

TO_NUMBER('4')+TO_NUMBER('3')
-----------------------------
7

SQL> SELECT
2 SUBSTR('SECTOR 5',-1,1),
3 SUBSTR('SECTOR 6',-1,1),
4 TO_NUMBER(SUBSTR('SECTOR 5',-1,1)),
5 TO_NUMBER(SUBSTR('SECTOR 6',-1,1))
6 FROM DUAL;

S S TO_NUMBER(SUBSTR('SECTOR5',-1,1)) TO_NUMBER(SUBSTR('SECTOR6',-1,1))
- - --------------------------------- ---------------------------------
5 6 5 6

SQL> SELECT SUBSTR('HOUSE # 5, SEC 11, KARACHI',9,1)*10 FROM DUAL;

SUBSTR('HOUSE#5,SEC11,KARACHI',9,1)*10
--------------------------------------
50

TO_DATE ( )
SQL> SELECT '14-AUG-1947' A FROM DUAL;

14-AUG-1947

SQL> SELECT TO_DATE('14-AUG-1947') A FROM DUAL;

14-AUG-47

SQL> SELECT NEXT_DAY('14-AUG-1947','SUNDAY') A FROM DUAL;

17-AUG-47

SQL> SELECT NEXT_DAY(TO_DATE('14-AUG-1947'),'SUNDAY') A FROM DUAL;

17-AUG-47

60 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR('14-AUG-1947','RRRR') A FROM DUAL;


SELECT TO_CHAR('14-AUG-1947','RRRR') FROM DUAL
*
ERROR at line 1:
ORA-01722: invalid number

SQL> SELECT
2 TO_CHAR(SYSDATE,'RRRR')
3 -
4 TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR') TOT_YEARS
5 FROM DUAL;

TOT_YEARS
---------
61

SQL> SELECT
2 TO_NUMBER(TO_CHAR(SYSDATE,'RRRR'))
3 -
4 TO_NUMBER(TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR')) TOT_YEARS
5 FROM DUAL;

TOT_YEARS
---------
61

SQL> SELECT TO_DATE('14-AUG-1947') A FROM DUAL;

14-AUG-47

SQL> SELECT TO_DATE('14-AUG-1947','DD-MON-RRRR') A FROM DUAL;

14-AUG-47

SQL> SELECT TO_DATE('AUGUST 14, 1947','MONTH DD, RRRR') A FROM DUAL;

14-AUG-47

SQL> SELECT
2 TO_DATE('AUGUST 14, 1947','MONTH DD, RRRR') A,
3 TO_DATE('AUGUST 14, 1947','MON DD, RRRR') B,
4 TO_DATE('AUG 14, 1947','Mon DD, RRRR') C,
5 TO_DATE('14 AUG 1947','DD MONTH RRRR') D,
6 TO_DATE('AUG 1947','MONTH RRRR') E,
7 TO_DATE('1947','RRRR') F,
8 TO_DATE('AUG','MON') G,
9 TO_DATE('14','DD') H
10 FROM DUAL;

A B C D E F G H
--------- --------- --------- --------- --------- --------- --------- ---------
14-AUG-47 14-AUG-47 14-AUG-47 14-AUG-47 01-AUG-47 01-JUL-47 01-AUG-08 14-JUL-08

SQL> SELECT * FROM EMP WHERE HIREDATE=TO_DATE('17/12/1980','DD/MM/RRRR');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

61 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Nesting Functions

Single-row functions can be nested to any depth. Nested functions are evaluated from the
innermost level to the outermost level.
F3(F2(F1(col,arg1),arg2),arg3)

TO_NUMBER(TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR'))

NVL function
Converts a null to an actual value.
• Data types that can be used are date, character, and number.
• Data types must match:
– NVL(commission_pct,0)
– NVL(hire_date,'01-JAN-97')
– NVL(job_id,'No Job Yet')

SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,0), SAL+NVL(COMM,0) FROM EMP;

EMPNO ENAME JOB SAL COMM NVL(COMM,0) SAL+NVL(COMM,0)


--------- ---------- --------- --------- --------- ----------- ---------------
7369 SMITH CLERK 800 0 800
7499 ALLEN SALESMAN 1600 300 300 1900
7521 WARD SALESMAN 1250 500 500 1750
7566 JONES MANAGER 2975 0 2975
7654 MARTIN SALESMAN 1250 1400 1400 2650
7698 BLAKE MANAGER 2850 0 2850
7782 CLARK MANAGER 2450 0 2450
7788 SCOTT ANALYST 3000 0 3000
7839 KING PRESIDENT 5000 0 5000
7844 TURNER SALESMAN 1500 0 0 1500
7876 ADAMS CLERK 1100 0 1100
7900 JAMES CLERK 950 0 950
7902 FORD ANALYST 3000 0 3000
7934 MILLER CLERK 1300 0 1300

14 rows selected.

SQL> SELECT ENAME, COMM, NVL(COMM,0), NVL(TO_CHAR(COMM),'NO COMMISSION') FROM EMP;

ENAME COMM NVL(COMM,0) NVL(TO_CHAR(COMM),'NOCOMMISSION')


---------- --------- ----------- ----------------------------------------
SMITH 0 NO COMMISSION
ALLEN 300 300 300
WARD 500 500 500
JONES 0 NO COMMISSION
MARTIN 1400 1400 1400
BLAKE 0 NO COMMISSION
CLARK 0 NO COMMISSION
SCOTT 0 NO COMMISSION
KING 0 NO COMMISSION
TURNER 0 0 0
ADAMS 0 NO COMMISSION
JAMES 0 NO COMMISSION
FORD 0 NO COMMISSION
MILLER 0 NO COMMISSION

62 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

COALESCE Function
SQL> SELECT EMPNO, ENAME, JOB, COMM, SAL, COALESCE(COMM,SAL,100) SALARY FROM EMP;

EMPNO ENAME JOB COMM SAL SALARY


--------- ---------- --------- --------- --------- ---------
7369 SMITH CLERK 800 800
7499 ALLEN SALESMAN 300 1600 300
7521 WARD SALESMAN 500 1250 500
7566 JONES MANAGER 2975 2975
7654 MARTIN SALESMAN 1400 1250 1400
7698 BLAKE MANAGER 2850 2850
7782 CLARK MANAGER 2450 2450
7788 SCOTT ANALYST 3000 3000
7839 KING PRESIDENT 5000 5000
7844 TURNER SALESMAN 0 1500 0
7876 ADAMS CLERK 1100 1100
7900 JAMES CLERK 950 950
7902 FORD ANALYST 3000 3000
7934 MILLER CLERK 1300 1300

14 rows selected.

SQL> SELECT ENAME, COMM, NVL(COMM,0), COALESCE(COMM,0), COALESCE(COMM,SAL,0)


FROM EMP;

ENAME COMM NVL(COMM,0) COALESCE(COMM,0) COALESCE(COMM,SAL,0)


---------- --------- ----------- ---------------- --------------------
SMITH 0 0 800
ALLEN 300 300 300 300
WARD 500 500 500 500
JONES 0 0 2975
MARTIN 1400 1400 1400 1400
BLAKE 0 0 2850
CLARK 0 0 2450
SCOTT 0 0 3000
KING 0 0 5000
TURNER 0 0 0 0
ADAMS 0 0 1100
JAMES 0 0 950
FORD 0 0 3000
MILLER 0 0 1300

SELECT EMPNO, COALESCE(PHONE_NO, CELL_NO, EMAIL, ADDRESS) CONTACT FROM EMP;


SELECT EMPNO, COALESCE(NEW_NIC, OLD_NIC,

63 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Conditional Expressions
Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement:
SQL> SELECT EMPNO, ENAME, DEPTNO,
2 DECODE(DEPTNO,10,'ACCOUNTS',20,'RESEARCH',30,'SALES','INVALID') DNAME
3 FROM EMP;

EMPNO ENAME DEPTNO DNAME


--------- ---------- --------- --------
7369 SMITH 20 RESEARCH
7499 ALLEN 30 SALES
7521 WARD 30 SALES
7566 JONES 20 RESEARCH
7654 MARTIN 30 SALES
7698 BLAKE 30 SALES
7782 CLARK 10 ACCOUNTS
7788 SCOTT 20 RESEARCH
7839 KING 10 ACCOUNTS
7844 TURNER 30 SALES
7876 ADAMS 20 RESEARCH
7900 JAMES 30 SALES
7902 FORD 20 RESEARCH
7934 MILLER 10 ACCOUNTS

Management has decided to revise salary according to the following:


PRESIDENT 15% MANAGER 12% ANALYST 10%
SALESMAN 8% OTHER 6%

The result of the following three queries is same:

SELECT EMPNO, ENAME, JOB, SAL,


DECODE(JOB,'PRESIDENT',SAL+SAL*15/100,'MANAGER',SAL+SAL*12/100,
'ANALYST',SAL+SAL*10/100,'SALESMAN',SAL+SAL*8/100,SAL+SAL*6/100) "INCREMENT"
FROM EMP;

SELECT EMPNO, ENAME, JOB, SAL,


DECODE(JOB,'PRESIDENT',SAL+SAL*.15,'MANAGER',SAL+SAL*.12,
'ANALYST',SAL+SAL*.1,'SALESMAN',SAL+SAL*.08,SAL+SAL*.06) "INCREMENT"
FROM EMP;

SQL> SELECT EMPNO, ENAME, JOB, SAL,


2 DECODE(JOB,'PRESIDENT',SAL*1.15,'MANAGER',SAL*1.12,
3 'ANALYST',SAL*1.1,'SALESMAN',SAL*1.08,SAL*1.06) "INCREMENT"
4 FROM EMP;

EMPNO ENAME JOB SAL INCREMENT


--------- ---------- --------- --------- ---------
7369 SMITH CLERK 800 848
7499 ALLEN SALESMAN 1600 1728
7521 WARD SALESMAN 1250 1350
7566 JONES MANAGER 2975 3332
7654 MARTIN SALESMAN 1250 1350
7698 BLAKE MANAGER 2850 3192
7782 CLARK MANAGER 2450 2744
7788 SCOTT ANALYST 3000 3300
7839 KING PRESIDENT 5000 5750
7844 TURNER SALESMAN 1500 1620
7876 ADAMS CLERK 1100 1166
7900 JAMES CLERK 950 1007
7902 FORD ANALYST 3000 3300
7934 MILLER CLERK 1300 1378

64 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Tables in the Oracle Database (Part 1)

• User Tables:
– Are a collection of tables created and maintained by the user
– Contain user information

• Data Dictionary:
– Is a collection of tables created and maintained by the Oracle Server
– Contain database information

Creating a table
Create tables to store data by using CREATE TABLE statement. Create Table is a DDL
Statement.

Create a table to store student information.


SQL> CREATE TABLE STUDENT
2 (
3 RNO NUMBER(4) PRIMARY KEY,
4 NAME VARCHAR2(20) NOT NULL,
5 DOB DATE,
6 NIC NUMBER(13) UNIQUE,
7 GENDER CHAR(1)
8 );

Table created.

Create a table to store class information.


SQL> CREATE TABLE CLASS
2 (
3 CID NUMBER(2) PRIMARY KEY,
4 CDESC VARCHAR2(20)
5 );

Table created.

Create a table to store marks information.


SQL> CREATE TABLE STD_MARKS
2 (
3 RNO NUMBER(4) REFERENCES STUDENT (RNO),
4 CID NUMBER(2) REFERENCES CLASS (CID),
5 PER NUMBER(5,2)
6 );

Table created.

Create a table to store grade criteria.


SQL> CREATE TABLE STD_GRADE
2 (GRADE VARCHAR2(2),
3 MIN_PER NUMBER(5,2),
4 MAX_PER NUMBER(5,2)
5 );

Table created.

65 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

How to verify table creation?

By a data dictionary view Æ USER_TABLES or (TABS)


SQL> SELECT TABLE_NAME FROM USER_TABLES;

TABLE_NAME
------------------------------
DEPT
EMP
BONUS
SALGRADE
STD_GRADE
STD_MARKS
CLASS
STUDENT

8 rows selected.

By a data dictionary view Æ USER_OBJECTS or (OBJ)


SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE='TABLE';

OBJECT_NAME
---------------------------------------------------------------------
DEPT
EMP
BONUS
SALGRADE
STD_GRADE
STD_MARKS
CLASS
STUDENT

8 rows selected.

By a data dictionary view Æ USER_CATALOG or (CAT)


SQL> SELECT * FROM USER_CATALOG WHERE TABLE_TYPE='TABLE';

TABLE_NAME TABLE_TYPE
------------------------------ -----------
DEPT TABLE
EMP TABLE
BONUS TABLE
SALGRADE TABLE
STD_GRADE TABLE
STD_MARKS TABLE
CLASS TABLE
STUDENT TABLE

8 rows selected.

66 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

By a data dictionary view Æ TAB or (TAB)


SQL> SELECT * FROM TAB WHERE TABTYPE='TABLE';

TNAME TABTYPE CLUSTERID


------------------------------ ------- ---------
DEPT TABLE
EMP TABLE
BONUS TABLE
SALGRADE TABLE
STD_GRADE TABLE
STD_MARKS TABLE
CLASS TABLE
STUDENT TABLE

8 rows selected.

By DESC / DESCRIBE Command


SQL> DESC STUDENT
Name Null? Type
------------------------------- -------- ----
RNO NOT NULL NUMBER(4)
NAME NOT NULL VARCHAR2(20)
DOB DATE
NIC NUMBER(13)
GENDER CHAR(1)

SQL> DESC CLASS


Name Null? Type
------------------------------- -------- ----
CID NOT NULL NUMBER(2)
CDESC VARCHAR2(20)

SQL> DESC STD_MARKS


Name Null? Type
------------------------------- -------- ----
RNO NUMBER(4)
CID NUMBER(2)
PER NUMBER(5,2)

SQL> DESC STD_GRADE


Name Null? Type
------------------------------- -------- ----
GRADE VARCHAR2(2)
MIN_PER NUMBER(5,2)
MAX_PER NUMBER(5,2)

SQL>

By SELECT Statement
SQL> SELECT * FROM STUDENT;

no rows selected

SQL>

67 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Insertion in a Table (Part 1)

You can add new rows to a table by using the INSERT statement.

SQL> INSERT INTO STUDENT There is a Column List before VALUES keyword.
2 (RNO, NAME, DOB, NIC, GENDER)
3 VALUES
4 (1,'MUHAMMAD ASLAM','23-JAN-1986',1452412345671,'M');

1 row created.

• Insert a new row containing values for each column.


• Optionally, list the columns in the INSERT clause.

SQL> INSERT INTO STUDENT


2 (RNO, NAME, DOB, NIC, GENDER)
3 VALUES
4 (2,'SAMINA KHAN','31-MAR-1987',4567712345645,'F');

1 row created.

There is not any Column List before VALUES keyword.

SQL> INSERT INTO STUDENT


2 VALUES
3 (3,'AAMIR','25-FEB-1982',1234567891231,'M');

If you do not use the column list, the values must be listed according to the default order of the
columns in the table, and a value must be provided for each column.

SQL> DESC STUDENT


Name Null? Type
------------------------------- -------- ----
RNO NOT NULL NUMBER(4)
NAME NOT NULL VARCHAR2(20)
DOB DATE
NIC NUMBER(13)
GENDER CHAR(1)

SQL> INSERT INTO STUDENT


2 (RNO, NAME, DOB, NIC, GENDER)
3 VALUES
4 (4,'RAJ KUMAR','25-APR-1997',NULL,'M');

In this example NULL value is moved in NIC column by using NULL keyword for NIC column.

SQL> INSERT INTO STUDENT


2 (RNO, NAME, DOB, GENDER)
3 VALUES
4 (5,'ZOBIA KHAN','12-AUG-1997','F');

In this example NULL value is moved in NIC column by excluding NIC column from column list.

68 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

INSERT INTO CLASS VALUES (1,'CLASS ONE');


INSERT INTO CLASS VALUES (2,'CLASS TWO');
INSERT INTO CLASS VALUES (3,'CLASS THREE');
INSERT INTO CLASS VALUES (4,'CLASS FOUR');
INSERT INTO CLASS VALUES (5,'CLASS FIVE');

INSERT INTO STD_MARKS VALUES (1, 1, 75.32);


INSERT INTO STD_MARKS VALUES (2, 1, 61.16);
INSERT INTO STD_MARKS VALUES (3, 1, 48.95);
INSERT INTO STD_MARKS VALUES (4, 1, 89.91);

INSERT INTO STD_GRADE VALUES ('A1',90,100);


INSERT INTO STD_GRADE VALUES ('A',80,89.99);
INSERT INTO STD_GRADE VALUES ('B',70,79.99);
INSERT INTO STD_GRADE VALUES ('C',60,69.99);
INSERT INTO STD_GRADE VALUES ('D',50,59.99);
INSERT INTO STD_GRADE VALUES ('F',0,49.99);

SQL> SELECT * FROM STUDENT;

RNO NAME DOB NIC G


------------- -------------------- --------- ------------- -
1 MUHAMMAD ASLAM 23-JAN-86 1452412345671 M
2 SAMINA KHAN 31-MAR-87 4567712345645 F
3 AAMIR 25-FEB-82 1234567891231 M
4 RAJ KUMAR 25-APR-97 M
5 ZOBIA KHAN 12-AUG-97 F

SQL> SELECT * FROM CLASS;

CID CDESC
---------- --------------------
1 CLASS ONE
2 CLASS TWO
3 CLASS THREE
4 CLASS FOUR
5 CLASS FIVE

SQL> SELECT * FROM STD_MARKS;

RNO CID PER


---------- ---------- ----------
1 1 75.32
2 1 61.16
3 1 48.95
4 1 89.91

SQL> SELECT * FROM STD_GRADE;

GR MIN_PER MAX_PER
-- ---------- ----------
A1 90 100
A 80 89.99
B 70 79.99
C 60 69.99
D 50 59.99
F 0 49.99

6 rows selected.

69 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 4
Displaying Data from Multiple Tables
Data from Multiple Tables

Sometimes you need to use data from more than one table.
• EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM exist in the EMP table.
• DEPTNO exist in both the EMP and DEPT tables.
• DNAME & LOC exist in the DEPT table.
To produce the result, you need to link the EMP and DEPT tables and access data from both of them.

EMP TABLE
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

DEPT TABLE
DEPTNO DNAME LOC
--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Data retrieved from both tables (EMP & DEPT tables)


EMPNO ENAME JOB SAL DEPTNO DNAME LOC
--------- ---------- --------- --------- --------- -------------- -------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK

70 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Types of Joins
Oracle Proprietary Joins (8i and prior):

• Equijoin
• Non-equijoin
• Outer join
• Self join

Defining Joins

When data from more than one table in the database is required, a join condition is used. Rows
in one table can be joined to rows in another table according to common values existing in
corresponding columns, that is, usually primary and foreign key columns.
To display data from two or more related tables, write a simple join condition in the WHERE
clause.
In the syntax:
table1.column denotes the table and column from which data is retrieved
table1.column1 = is the condition that joins (or relates) the tables together
table2.column2

Guidelines

• When writing a SELECT statement that joins tables, precede the column name with the table
name for clarity and to enhance database access.
• If the same column name appears in more than one table, the column name must be
prefixed with the table name.
• To join n tables together, you need a minimum of n-1 join conditions. For example, to join
four tables, a minimum of three joins is required. This rule may not apply if your table has a
concatenated primary key, in which case more than one column is required to uniquely
identify each row.

Equijoin

To determine an employee’s department name, you compare the value in the DEPTNO column
in the EMP table with the DEPTNO values in the DEPT table. The relationship between the EMP
and DEPT tables is an equijoin—that is, values in the DEPTNO column on both tables must be
equal. Frequently, this type of join involves primary and foreign key complements.

Note: Equijoins are also called simple joins or inner joins.

EMP TABLE DEPT TABLE

EMPNO ENAME DEPTNO DEPTNO DNAME LOC


--------- ---------- --------- --------- ------------ ----------
7369 SMITH 20 10 ACCOUNTING NEW YORK
7499 ALLEN 30 20 RESEARCH DALLAS
7521 WARD 30 30 SALES CHICAGO
7566 JONES 20 40 OPERATIONS BOSTON
7654 MARTIN 30
7698 BLAKE 30
7782 CLARK 10
7788 SCOTT 20
.... ...... ..
.... ...... ..

71 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Insert a record in EMP table by using the following query:


SQL> INSERT INTO EMP
2 (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
3 VALUES
4 (1,'ASLAM','CLERK',7566,SYSDATE,1200,NULL,NULL);

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 ASLAM CLERK 7566 26-JUL-08 1200

15 rows selected.

The above select statement retrieves 15 rows. Employee ASLAM does not belong to any
department, because there is a NULL value in DEPTNO column of ASLAM’s record.

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

The above select statement retrieves 4 rows. There is a DEPTNO 40, while there is not any
employee in EMP table who belong to department 40.

72 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Retrieving Records with Equijoins


Display all employees with their department names and location.
Employee information is stored in EMP table
Department information is stored in DEPT table

There is a column DEPTNO which exists in both tables


Match the value in DEPTNO of EMP table with DEPTNO of DEPT table.

SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC


2 FROM EMP, DEPT
3 WHERE EMP.DEPTNO=DEPT.DEPTNO;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK

14 rows selected.

The query retrieve 14 rows, ASLAM’s record did not retrieved. Why?

In the example:
• The SELECT clause specifies the column names to retrieve:
• employee number, name, job, salary, and department number, which are columns in
the EMP table
• department name, and location, which are columns in the DEPT table
• The FROM clause specifies the two tables that the database must access:
• EMP table
• DEPT table
• The WHERE clause specifies how the tables are to be joined:
EMP.DEPTNO = DEPT.DEPTNO
Because the DEPTNO column is common to both tables, it must be prefixed by the table name
to avoid ambiguity or Use table prefixes to qualify column names that are in multiple tables.

Improve performance by using table prefixes


SELECT EMP.EMPNO, EMP.ENAME, EMP.JOB, EMP.SAL, EMP.DEPTNO, DEPT.DNAME, DEPT.LOC
FROM EMP, DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;

Using Table Alias


SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC
FROM EMP E, DEPT D
WHERE E.DEPTNO=D.DEPTNO;

73 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Additional Search Conditions


SQL> SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO
4 AND SAL>2000;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7902 FORD ANALYST 3000 20 RESEARCH DALLAS

6 rows selected.

SQL> SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC


2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO
4 AND DNAME='SALES';

OR

SQL> SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC


2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO
4 AND E.DEPTNO=30;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7900 JAMES CLERK 950 30 SALES CHICAGO

6 rows selected.

Is there any difference in the following two queries?


SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC
FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND SAL>2000;

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC


FROM EMP E, DEPT D WHERE SAL>2000 AND E.DEPTNO=D.DEPTNO;

Cartesian / Cross Products (rows of one table multiply with rows of another table)

• A Cartesian product is formed when:


– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to all rows in the second table
• To avoid a Cartesian product, always include a valid join condition in a WHERE clause.

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME FROM EMP E, DEPT D

74 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Non-Equijoins

A non-equijoin is a join condition containing something other than an equality operator.


The relationship between the EMP table and the SALGRADE table has an example of a non-
equijoin. A relationship between the two tables is that the SAL column in the EMPL table must
be between the values in the LOSAL and HISAL columns of the SALGRADE table. The
relationship is obtained using an operator other than equals (=).

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

SQL> SELECT * FROM SALGRADE;

GRADE LOSAL HISAL


--------- --------- ---------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999

SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, G.GRADE


2 FROM EMP E, SALGRADE G
3 WHERE E.SAL BETWEEN G.LOSAL AND G.HISAL;

EMPNO ENAME JOB SAL GRADE


--------- ---------- --------- --------- ---------
7369 SMITH CLERK 800 1
7900 JAMES CLERK 950 1
7876 ADAMS CLERK 1100 1
7521 WARD SALESMAN 1250 2
7654 MARTIN SALESMAN 1250 2
7934 MILLER CLERK 1300 2
7844 TURNER SALESMAN 1500 3
7499 ALLEN SALESMAN 1600 3
7782 CLARK MANAGER 2450 4
7698 BLAKE MANAGER 2850 4
7566 JONES MANAGER 2975 4
7788 SCOTT ANALYST 3000 4
7902 FORD ANALYST 3000 4
7839 KING PRESIDENT 5000 5
14 rows selected.

75 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Non-Equijoins (continued)

The example creates a non-equijoin to evaluate an employee’s salary grade. The salary must be
between any pair of the low and high salary ranges.
It is important to note that all employees appear exactly once when this query is executed. No
employee is repeated in the list. There are two reasons for this:
• None of the rows in the job grade table contain grades that overlap. That is, the salary
value for an employee can lie only between the low salary and high salary values of one of
the rows in the salary grade table.
• All of the employees’ salaries lie within the limits provided by the salgrade table. That is, no
employee earns less than the lowest value contained in the LOSAL column or more than the
highest value contained in the HISAL column.

Note: Other conditions, such as <= and >= can be used, but BETWEEN is the simplest.
Remember to specify the low value first and the high value last when using BETWEEN.
Table aliases have been specified in the slide example for performance reasons, not because of
possible ambiguity.

More examples of Non-Equijoins

SQL> SELECT * FROM STD_MARKS;

RNO CID PER


---------- ---------- ----------
1 1 75.32
2 1 61.16
3 1 48.95
4 1 89.91

SQL> SELECT * FROM STD_GRADE;

GR MIN_PER MAX_PER
-- ---------- ----------
A1 90 100
A 80 89.99
B 70 79.99
C 60 69.99
D 50 59.99
F 0 49.99

6 rows selected.

SQL> SELECT RNO, PER, GRADE


2 FROM STD_MARKS, STD_GRADE
3 WHERE PER BETWEEN MIN_PER AND MAX_PER
4 ORDER BY 1;

RNO PER GR
---------- ---------- --
1 75.32 B
2 61.16 C
3 48.95 F
4 89.91 A

SQL>

76 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Outer Joins

Returning Records with No Direct Match with Outer Joins


If a row does not satisfy a join condition, the row will not appear in the query result. For
example, in the equijoin condition of EMP and DEPT tables, employee ASLAM does not appear
because there is no department number recorded for his in the EMP table. Instead of seeing 15
employees in the result set, you see 14 records.

SQL> SELECT * FROM EMP;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 ASLAM CLERK 7566 26-JUL-08 1200
15 rows selected.

SQL> SELECT * FROM DEPT; DEPTNO is missing

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON No Employee is working in DEPTNO 40

SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC


2 FROM EMP, DEPT
3 WHERE EMP.DEPTNO=DEPT.DEPTNO;
EMPNO ENAME JOB SAL DEPTNO DNAME LOC
--------- ---------- --------- --------- --------- -------------- -------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
14 rows selected.

77 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

When joining EMP and DEPT tables:


ASLAM’s record is not displaying from EMP table
Operations’s record is not displaying from DEPT table

Aslam does not belong to any department because there is a null value in DEPTNO column.
So when you join EMP and DEPT tables using equijoin, the values of DEPTNO column of EMP
table matches with the values of DEPTNO column of DEPT table, and only those records will be
displayed which values matches.

There is an Opeations’s department, DEPTNO 40 in DEPT table, but No Employee is working in


DEPTNO 40 in EMP table, so value is not matching. Only those records will by displayed using
equijoin which values matches in both tables.

Why we use Outer Joins?

We use outer join when mismatched values to be displayed. or


Using Outer Joins to Return Records with No Direct Match

The missing rows can be returned if an outer join operator is used in the join condition. The
operator is a plus sign enclosed in parentheses (+), and it is placed on the “side” of the join
that is deficient in information. This operator has the effect of creating one or more null rows,
to which one or more rows from the nondeficient table can be joined.
In the syntax:
table1.column = is the condition that joins (or relates) the tables together.
table2.column (+) is the outer join symbol, which can be placed on either side of the
WHERE clause condition, but not on both sides.
(Place the outer join symbol following the name of the column in
the table without the matching rows.)

SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC


2 FROM EMP, DEPT
3 WHERE EMP.DEPTNO=DEPT.DEPTNO(+);

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
1 ASLAM CLERK 1200

15 rows selected.

Placed (+) on the “side” of the join that is deficient (missing) in information. Aslam’s record
exists in EMP table, but NULL DEPTNO does not exists in DEPT table, so put (+) on DEPT side
because DEPT side is missing information.

78 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC


2 FROM EMP, DEPT
3 WHERE EMP.DEPTNO(+)=DEPT.DEPTNO;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7900 JAMES CLERK 950 30 SALES CHICAGO
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
OPERATIONS BOSTON

15 rows selected.

Placed (+) on the “side” of the join that is deficient (missing) in information. Operations
department DEPTNO 40 exists in DEPT table, but DEPTNO 40 is not assigned to any employee,
so put (+) on EMP side because EMPT side is missing information.

Display all departments in which no employee was hired.


SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC
2 FROM EMP, DEPT
3 WHERE EMP.DEPTNO(+)=DEPT.DEPTNO
4 AND EMP.DEPTNO IS NULL;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
OPERATIONS BOSTON

Outer Join Restrictions

• The outer join operator can appear on only one side of the expression—the side that has
information missing. It returns those rows from one table that have no direct match in the
other table.
• A condition involving an outer join cannot use the IN operator or be linked to another
condition by the OR operator.

79 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Self Joins
Sometimes you need to join a table to itself. To find the name of each employee’s manager,
you need to join the EMP table to itself, or perform a self join. For example, to find the name of
ALLEN’s manager, you need to:
• Find ALLEN in the EMP table by looking at ENAME column.
• Find the manager number for ALLEN by looking at the MGR column. ALLEN’s manager
number is 7698.
• Find the name of the manager with MGR 7698 by looking at the ENAME column. BLAKE’s
employee number is 7698, so BLAKE is ALLEN’s manager.
In this process, you look in the table twice. The first time you look in the table to find ALLEN in
the ENAME column and MGR value of 7698. The second time you look in EMPNO column to find
7698 and the ENAME column to find BLAKE.

SQL> SELECT * FROM EMP;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 ASLAM CLERK 7566 26-JUL-08 1200

15 rows selected.

SQL> SELECT W.EMPNO, W.ENAME, M.EMPNO MGR, M.ENAME


2 FROM EMP W, EMP M
3 WHERE W.MGR=M.EMPNO;
EMPNO ENAME MGR ENAME
--------- ---------- --------- ----------
7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7521 WARD 7698 BLAKE
7566 JONES 7839 KING
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 KING
7782 CLARK 7839 KING
7788 SCOTT 7566 JONES
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES
7934 MILLER 7782 CLARK
1 ASLAM 7566 JONES

14 rows selected.

KING’s record did not display because KING’s MGR is null, which did not match with any EMPNO.

80 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

To display KING’s record, you have to use outer join condition, because KING’s MGR is null
which, which did not match with any EMPNO. You have to put (+) on manager side because
manager is missing but worker (KING) exists.
In another words KING’s manager is missing and you have to put (+) on missing side.

SQL> SELECT W.EMPNO, W.ENAME, M.EMPNO MGR, M.ENAME


2 FROM EMP W, EMP M
3 WHERE W.MGR=M.EMPNO(+);
EMPNO ENAME MGR ENAME
--------- ---------- --------- ----------
7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7521 WARD 7698 BLAKE
7566 JONES 7839 KING
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 KING
7782 CLARK 7839 KING
7788 SCOTT 7566 JONES
7839 KING
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES
7934 MILLER 7782 CLARK
1 ASLAM 7566 JONES

15 rows selected.

The example joins the EMP table to itself. To simulate two tables in the FROM clause, there are
two aliases, namely w and m, for the same table, EMP.
In this example, the WHERE clause contains the join that means “where a worker’s manager
number matches the employee number for the manager.”

The DELETE clause


The DELETE statement is used to remove row from table.

How to remove ASLAM’S record? Aslam’s EMPNO is 1.

SQL> DELETE EMP WHERE EMPNO=1;

1 row deleted.

The COMMIT statement


The COMMIT statement is used to save data permanently into database. All DDL and DCL
statements execute automatic commit. Commit is also executed automatically in some other
cases that will be discussed later. After DML statements you have to use COMMIT statement for
permanently saving.

SQL> COMMIT;

Commit complete.

Note: CREATE TABLE, INSERT, DELETE and COMMIT will be discussed late in detail.

81 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 5
Aggregating Data Using Group Functions
Group Functions
Unlike single-row functions, group functions operate on sets of rows to give one result per
group. These sets may be the whole table or the table split into groups.

Types of Group Functions


• AVG
• COUNT
• MAX
• MIN
• SUM

Guidelines for Using Group Functions


• DISTINCT makes the function consider only nonduplicate values; ALL makes it consider
every value including duplicates. The default is ALL and therefore does not need to be
specified.
• The data types for the functions with an expr argument may be CHAR, VARCHAR2,
NUMBER, or DATE.
• All group functions ignore null values. To substitute a value for null values, use the NVL,
NVL2, or COALESCE functions.
• The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY
clause. To override this default ordering, DESC can be used in an ORDER BY clause.
SQL> SELECT SUM(SAL) FROM EMP;
SUM(SAL)
---------
29025

SQL> SELECT SUM(SAL) FROM EMP WHERE DEPTNO=10;


SUM(SAL)
---------
8750

You can use AVG, SUM, MIN, and MAX functions against columns that can store numeric data.
The example the sum, highest, lowest and average of monthly salaries of all employees.
SQL> SELECT SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL) FROM EMP;
SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- --------- --------- ---------
29025 2073.2143 5000 800

You can use the MAX and MIN functions for any data type. The example displays the most
junior and most senior employee.
SQL> SELECT MAX(HIREDATE), MIN(HIREDATE) FROM EMP;
MAX(HIRED MIN(HIRED
--------- ---------
23-MAY-87 17-DEC-80

The following example displays the employee name that is first and the employee name that is
the last in an alphabetized list of all employees.
SQL> SELECT MIN(ENAME), MAX(ENAME) FROM EMP;
MIN(ENAME) MAX(ENAME)
---------- ----------
ADAMS WARD

82 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The COUNT Function

The COUNT function is used to return the number of rows in a table.


The COUNT function has three formats:
• COUNT(*)
• COUNT(expr)
• COUNT(DISTINCT expr)

COUNT(*) returns the number of rows in a table that satisfy the criteria of the SELECT
statement, including duplicate rows and rows containing null values in any of the columns.
SQL> SELECT COUNT(*) FROM EMP;
COUNT(*)
---------
14

If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows
that satisfies the condition in the WHERE clause.
SQL> SELECT COUNT(*) FROM EMP WHERE DEPTNO=10;
COUNT(*)
---------
3

SQL> SELECT COUNT(*) FROM EMP WHERE JOB='CLERK';


COUNT(*)
---------
4

COUNT(expr) returns the number of non-null values in the column identified by expr.
SQL> SELECT COUNT(EMPNO), COUNT(MGR), COUNT(COMM) FROM EMP;
COUNT(EMPNO) COUNT(MGR) COUNT(COMM)
------------ ---------- -----------
14 13 4

COUNT(DISTINCT expr) returns the number of unique, non-null values in the column identified
by expr. Or Use the DISTINCT keyword to suppress the counting of any duplicate values within
a column.
SQL> SELECT COUNT(JOB), COUNT(DISTINCT JOB), COUNT(DISTINCT DEPTNO) FROM EMP;

COUNT(JOB) COUNT(DISTINCTJOB) COUNT(DISTINCTDEPTNO)


---------- ------------------ ---------------------
14 5 3

The following example displays the number of employees who are earning more than 2000.
SQL> SELECT COUNT(*) FROM EMP WHERE SAL>2000;
COUNT(*)
---------
6

SQL> SELECT COUNT(*) FROM EMP WHERE TO_CHAR(HIREDATE,'RRRR')=1981;


COUNT(*)
---------
10

83 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Group Functions and Null Values


All group functions ignore null values in the column. In the example, the average is calculated
based only on the rows in the table where a valid value is stored in the COMM column. The
average is calculated as the total commission paid to all employees divided by the number of
employees receiving a commission (four).

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

SQL> SELECT COUNT(*), COUNT(COMM), AVG(COMM), SUM(COMM), SUM(COMM)/COUNT(COMM)


FROM EMP;

COUNT(*) COUNT(COMM) AVG(COMM) SUM(COMM) SUM(COMM)/COUNT(COMM)


--------- ----------- --------- --------- ---------------------
14 4 550 2200 550

Using the NVL Function with Group Functions


The NVL function forces group functions to include null values. In the example, the average is
calculated based on all rows in the table, regardless of whether null values are stored in the
COMM column. The average is calculated as the total commission paid to all employees divided
by the total number of employees in the company (14).

SQL> SELECT
2 SUM(COMM), COUNT(COMM), AVG(COMM),
3 COUNT(NVL(COMM,0)), AVG(NVL(COMM,0))
4 FROM EMP;

SUM(COMM) COUNT(COMM) AVG(COMM) COUNT(NVL(COMM,0)) AVG(NVL(COMM,0))


--------- ----------- --------- ------------------ ----------------
2200 4 550 14 157.14286

84 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Creating Groups of Data by using GROUP BY clause

Until now, all group functions have treated the table as one large group of information. At
times, you need to divide the table of information into smaller groups. This can be done by
using the GROUP BY clause.

You can use the GROUP BY clause to divide the rows in a table into groups. You can then use
the group functions to return summary information for each group.

Guidelines
• If you include a group function in a SELECT clause, you cannot select individual results as
well, unless the individual column appears in the GROUP BY clause. You receive an error
message if you fail to include the column list in the GROUP BY clause.
• Using a WHERE clause, you can exclude rows before dividing them into groups.
• You must include the columns in the GROUP BY clause.
• You cannot use a column alias in the GROUP BY clause.
• By default, rows are sorted by ascending order of the columns included in the GROUP BY
list. You can override this by using the ORDER BY clause.

The GROUP BY Clause (continued)


When using the GROUP BY clause, make sure that all columns in the SELECT list that are not
group functions are included in the GROUP BY clause. The example displays the department
number and the average salary for each department. Here is how this SELECT statement,
containing a GROUP BY clause, is evaluated:
• The SELECT clause specifies the columns to be retrieved:
• Department number column in the EMP table
• The average of all the salaries in the group you specified in the GROUP BY clause
• The FROM clause specifies the tables that the database must access: the EMP table.
• The WHERE clause specifies the rows to be retrieved. Since there is no WHERE clause, all
rows are retrieved by default.
• The GROUP BY clause specifies how the rows should be grouped. The rows are being
grouped by department number, so the AVG function that is being applied to the salary
column will calculate the average salary for each department.
SQL> SELECT DEPTNO, AVG(SAL) SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)
2 FROM EMP 2 FROM EMP
3 GROUP BY DEPTNO; 3 GROUP BY DEPTNO;

DEPTNO AVG(SAL) DEPTNO COUNT(*) SUM(SAL)


--------- --------- --------- --------- ---------
30 1566.6667 30 6 9400
20 2175 20 5 10875
10 2916.6667 10 3 8750

The GROUP BY column does not have to be in the SELECT clause. For example, the SELECT
statement in the example displays the average salaries for each department without displaying
the respective department numbers. Without the department numbers, however, the results do
not look meaningful.
SQL> SELECT AVG(SAL) SQL> SELECT COUNT(*), SUM(SAL)
2 FROM EMP 2 FROM EMP
3 GROUP BY DEPTNO; 3 GROUP BY DEPTNO;

AVG(SAL) COUNT(*) SUM(SAL)


--------- --------- ---------
1566.6667 6 9400
2175 5 10875
2916.6667 3 8750

85 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

You can use the group function in the ORDER BY clause.


SQL> SELECT DEPTNO, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL)
2 FROM EMP
3 GROUP BY DEPTNO
4 ORDER BY SUM(SAL);
DEPTNO COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- --------- --------- --------- --------- ---------
10 3 8750 2916.6667 5000 1300
30 6 9400 1566.6667 2850 950
20 5 10875 2175 3000 800

Summary information according to job wise


SQL> SELECT JOB, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL)
2 FROM EMP
3 GROUP BY JOB
4 ORDER BY 2;
JOB COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- --------- --------- --------- --------- ---------
PRESIDENT 1 5000 5000 5000 5000
ANALYST 2 6000 3000 3000 3000
MANAGER 3 8275 2758.3333 2975 2450
SALESMAN 4 5600 1400 1600 1250
CLERK 4 4150 1037.5 1300 800

Summary information according to year wise


SQL> SELECT
2 TO_CHAR(HIREDATE,'RRRR'), COUNT(*), SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL)
3 FROM EMP
4 GROUP BY TO_CHAR(HIREDATE,'RRRR')
5 ORDER BY 1;

TO_C COUNT(*) SUM(SAL) MAX(SAL) MIN(SAL) AVG(SAL)


---- --------- --------- --------- --------- ---------
1980 1 800 800 800 800
1981 10 22825 5000 950 2282.5
1987 2 4100 3000 1100 2050
2082 1 1300 1300 1300 1300

Summary information according to mon_year wise


SQL> SELECT TO_CHAR(HIREDATE,'MON-RRRR') MON_YEAR, COUNT(*), SUM(SAL)
2 FROM EMP
3 GROUP BY TO_CHAR(HIREDATE,'MON-RRRR')
4 ORDER BY 1;
MON_YEAR COUNT(*) SUM(SAL)
-------- --------- ---------
APR-1981 1 2975
APR-1987 1 3000
DEC-1980 1 800
DEC-1981 2 3950
FEB-1981 2 2850
JAN-2082 1 1300
JUN-1981 1 2450
MAY-1981 1 2850
MAY-1987 1 1100
NOV-1981 1 5000
SEP-1981 2 2750

86 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Grouping by More Than One Column


Groups within Groups
You can return summary results for groups and subgroups by listing more than one GROUP BY
column. You can determine the default sort order of the results by the order of the columns in
the GROUP BY clause. Here is how the SELECT statement on the slide, containing a GROUP BY
clause, is evaluated:
• The SELECT clause specifies the column to be retrieved:
• Department number and job in the EMP table
• The summary of all the salaries in the group that you specified in the GROUP BY clause
• The FROM clause specifies the tables that the database must access: the EMP table.
• The GROUP BY clause specifies how you must group the rows:
• First, the rows are grouped by department number.
• Second, within the department number groups, the rows are grouped by job.
So the group functions are being applied to the salary column for all job within each
department number group.

SQL> SELECT DEPTNO, JOB, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL)


2 FROM EMP
3 GROUP BY DEPTNO, JOB
4 ORDER BY 1,2;
DEPTNO JOB COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- --------- --------- --------- --------- --------- ---------
10 CLERK 1 1300 1300 1300 1300
10 MANAGER 1 2450 2450 2450 2450
10 PRESIDENT 1 5000 5000 5000 5000
20 ANALYST 2 6000 3000 3000 3000
20 CLERK 2 1900 950 1100 800
20 MANAGER 1 2975 2975 2975 2975
30 CLERK 1 950 950 950 950
30 MANAGER 1 2850 2850 2850 2850
30 SALESMAN 4 5600 1400 1600 1250
9 rows selected.

SQL> SELECT
2 TO_CHAR(HIREDATE,'RRRR'), TO_CHAR(HIREDATE,'MON'), COUNT(*), SUM(SAL)
3 FROM EMP
4 GROUP BY TO_CHAR(HIREDATE,'RRRR'), TO_CHAR(HIREDATE,'MON')
5 ORDER BY 1,2;

TO_C TO_ COUNT(*) SUM(SAL)


---- --- --------- ---------
1980 DEC 1 800
1981 APR 1 2975
1981 DEC 2 3950
1981 FEB 2 2850
1981 JUN 1 2450
1981 MAY 1 2850
1981 NOV 1 5000
1981 SEP 2 2750
1987 APR 1 3000
1987 MAY 1 1100
2082 JAN 1 1300

11 rows selected.

87 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Illegal Queries Using Group Functions


SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)
2 FROM EMP;
SELECT DEPTNO, COUNT(*), SUM(SAL)
*
ERROR at line 1:
ORA-00937: not a single-group group function

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL), AVG(SAL)


2 FROM EMP
3 GROUP BY DEPTNO
4 ORDER BY SAL;
ORDER BY SAL
*
ERROR at line 4:
ORA-00979: not a GROUP BY expression

Whenever you use a mixture of individual items (DEPTNO) and group functions (COUNT) in the
same SELECT statement, you must include a GROUP BY clause that specifies the individual
items (in this case, DEPTNO). If the GROUP BY clause is missing, then the error message
“not a single-group group function” appears and an asterisk (*) points to the offending column.

You can correct the error by adding the GROUP BY clause.

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)


2 FROM EMP
3 GROUP BY DEPTNO;

DEPTNO COUNT(*) SUM(SAL)


--------- --------- ---------
30 6 9400
20 5 10875
10 3 8750

Any column or expression in the SELECT list that is not an aggregate function must be in the
GROUP BY clause.

• You cannot use the WHERE clause to restrict groups.


• You use the HAVING clause to restrict groups.
• You cannot use group functions in the WHERE clause.

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)


2 FROM EMP
3 WHERE SUM(SAL)>9000
4 GROUP BY DEPTNO;
WHERE SUM(SAL)>9000
*
ERROR at line 3:
ORA-00934: group function is not allowed here

88 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Excluding Group Results: The HAVING Clause


Restricting Group Results
In the same way that you use the WHERE clause to restrict the rows that you select, you use
the HAVING clause to restrict groups. To find the summation of salary of each department, but
show only the departments that have a summation of salary more than 9,000, you need to do
the following:
1. Find the summation of salary for each department by grouping by department number.
2. Restrict the groups to those departments with a sum of salary greater than 9,000.
SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)
2 FROM EMP
3 HAVING SUM(SAL)>9000
4 GROUP BY DEPTNO;
DEPTNO COUNT(*) SUM(SAL)
--------- --------- ---------
30 6 9400
20 5 10875

The HAVING Clause


You use the HAVING clause to specify which groups are to be displayed, and thus, you further
restrict the groups on the basis of aggregate information.
In the syntax:
group_condition restricts the groups of rows returned to those groups for which
the specified condition is true
The Oracle server performs the following steps when you use the HAVING clause:
1. Rows are grouped.
2. The group function is applied to the group.
3. The groups that match the criteria in the HAVING clause are displayed.
The HAVING clause can precede the GROUP BY clause, but it is recommended that you place
the GROUP BY clause first because that is more logical. Groups are formed and group functions
are calculated before the HAVING clause is applied to the groups in the SELECT list.
SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)
2 FROM EMP
3 GROUP BY DEPTNO
4 HAVING SUM(SAL)>9000;
DEPTNO COUNT(*) SUM(SAL)
--------- --------- ---------
30 6 9400
20 5 10875

The following example displays department numbers and maximum salaries for those
departments whose maximum salary is greater or equal to 3,000.
You can use the GROUP BY clause without using a group function in the SELECT list.
If you restrict rows based on the result of a group function, you must have a GROUP BY clause
as well as the HAVING clause.
The following example displays the department numbers and maximum salaries for those
departments whose maximum salary is greater than 3,000:
SQL> SELECT DEPTNO, MAX(SAL) SQL> SELECT DEPTNO
2 FROM EMP 2 FROM EMP
3 GROUP BY DEPTNO 3 GROUP BY DEPTNO
4 HAVING MAX(SAL)>=3000; 4 HAVING MAX(SAL)>=3000;
DEPTNO MAX(SAL) DEPTNO
--------- --------- ---------
20 3000 20
10 5000 10

89 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*)


2 FROM EMP
3 GROUP BY TO_CHAR(HIREDATE,'RRRR')
4 HAVING COUNT(*)>1
5 ORDER BY TO_CHAR(HIREDATE,'RRRR');

TO_C COUNT(*)
---- ---------
1981 10
1987 2

SQL> SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*)


2 FROM EMP
3 GROUP BY TO_CHAR(HIREDATE,'RRRR')
4 ORDER BY TO_CHAR(HIREDATE,'RRRR');

TO_C COUNT(*)
---- ---------
1980 1
1981 10
1987 2
2082 1

Nesting Group Functions


Group functions can be nested to a depth of two. The example displays the maximum average
salary.

SQL> SELECT MAX(AVG(SAL))


2 FROM EMP
3 GROUP BY DEPTNO;

MAX(AVG(SAL))
-------------
2916.6667

SQL> SELECT MAX(SUM(SAL))


2 FROM EMP
3 GROUP BY DEPTNO;

MAX(SUM(SAL))
-------------
10875

SQL> SELECT SUM(MAX(SAL)) FROM EMP


2 GROUP BY DEPTNO;

SUM(MAX(SAL))
-------------
10850

90 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 6
Subqueries
A subquery is a query within a query. In Oracle, you can create subqueries within your SQL
statements. These subqueries can reside in the WHERE clause, HAVING clause, the FROM
clause, or the SELECT clause.

Use a subquery when there is an unknown criteria.

For example,
I want to retrieve all employees who are working in SMITH’S department.

Smith’s Department is unknown, first find Smith’s department by using the following query:

SQL> SELECT DEPTNO FROM EMP WHERE ENAME='SMITH';

DEPTNO
---------
20

And now use department number 20 for retrieving all employees of that department.

SQL> SELECT * FROM EMP WHERE DEPTNO=20;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20

But you can achieve the above task by using the following subquery in where clause.

SQL> SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE ENAME='SMITH');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20

In the above example, the inner query determines the department of employee SMITHl. The
outer query takes the result of the inner query and uses this result to display all the employees
who belong to this department.

Display all employees who are earning more than JONES.


Without subquery:
SQL> SELECT SAL FROM EMP WHERE ENAME='JONES'; Æ 2975
SQL> SELECT * FROM EMP WHERE SAL>2975;

Using subquery:
SQL> SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME='JONES');

91 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Display all employees who are working on the same post as BLAKE

BLAKE’s job is unknown, first find BLAKE’s job by using the following query:

SQL> SELECT JOB FROM EMP WHERE ENAME='BLAKE';

JOB
---------
MANAGER

And now use MANAGER in criteria for retrieving all employees of that job.

SQL> SELECT * FROM EMP WHERE JOB='MANAGER';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10

But you can achieve the above task by using the following subquery in where clause.

SQL> SELECT * FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME='BLAKE');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10

Display all employees who are working in SALES department

Department names are not saved in EMP table. Now you have to use DEPT table in subquery
because DEPT table contains department names.

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

In the following query you used two tables DEPT in inner query and EMP in outer query.

SQL> SELECT * FROM EMP


WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

92 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Using Group Functions in a Subquery


You can display data from a main query by using a group function in a subquery to return a
single row. The subquery is in parentheses and is placed after the comparison condition.

Display employee who is (are) earning maximum salary


First find maximum salary by using the following query:
SQL> SELECT MAX(SAL) FROM EMP;
MAX(SAL)
---------
5000

Then put 5000 in WHERE clause for matching criteria:

SQL> SELECT * FROM EMP WHERE SAL=5000;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10

But you can use the following subquery:

SQL> SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP);


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10

Guidelines for Using Subqueries


• A subquery must be enclosed in parentheses.
• Place the subquery on the right side of the comparison condition for readability.
• The ORDER BY clause in the subquery is not needed unless you are performing Top-N
analysis.
• Two classes of comparison conditions are used in subqueries: single-row operators and
multiple-row operators.
• Use single-row operators with single-row subqueries and use multiple-row operators
with multiple-row subqueries.

Write queries of the following:


1. Subordinates list of BLAKE (manager)
2. Employees working with ALLEN in the same department
3. Manager's record of Mr. SMITH
4. Employees who are working in NEW YORK
5. Employees who are senior than SCOTT
6. Employee with least salary in the company
7. Complete information of most experienced employee in the company
8. Display all employees who are working on the same job as SMITH'S job and are earning
more than ADAMS

What is the meaning of following queries?


SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'RRRR') =
(SELECT TO_CHAR(HIREDATE,'RRRR') FROM EMP WHERE ENAME='JONES');
SELECT * FROM EMP
WHERE LENGTH(ENAME)=(SELECT LENGTH(ENAME) FROM EMP WHERE EMPNO=7521);
SELECT * FROM EMP
WHERE SUBSTR(ENAME,2,1)=(SELECT SUBSTR(ENAME,2,1) FROM EMP WHERE EMPNO=7902);

93 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Types of Subqueries
• Single-row subqueries: Queries that return only one row from the inner SELECT
statement
• Multiple-row subqueries: Queries that return more than one row from the inner SELECT
statement

Note: There are also multiple-column subqueries: Queries that return more than one column
from the inner SELECT statement.

Single-Row Subqueries
A single-row subquery is one that returns one row from the inner SELECT statement. This type
of subquery uses a single-row operator.

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to

SELECT * FROM EMP WHERE HIREDATE=(SELECT HIREDATE FROM EMP WHERE EMPNO=7902);
SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE LOC='NEW YORK');
SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE EMPNO=7900);

The HAVING Clause with Subqueries


You can use subqueries not only in the WHERE clause, but also in the HAVING clause. The
Oracle server executes the subquery, and the results are returned into the HAVING clause of
the main query.
The SQL statement on in the following example displays all the departments that have a
minimum salary greater than that of department 30.

SQL> SELECT DEPTNO, MIN(SAL) FROM EMP


2 GROUP BY DEPTNO
3 HAVING MIN(SAL)>(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30);
DEPTNO MIN(SAL)
--------- ---------
10 1300

SQL> SELECT DEPTNO, MIN(SAL) FROM EMP


2 GROUP BY DEPTNO;
DEPTNO MIN(SAL)
--------- ---------
30 950
20 800
10 1300

SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30;


MIN(SAL)
---------
950

94 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries. You use a
multiple-row operator, instead of a single-row operator, with a multiple-row subquery. The
multiple-row operator expects one or more values.

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery

What is wrong with this Statement?

SQL> SELECT * FROM EMP


2 WHERE SAL = (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);
WHERE SAL = (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO)
*
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row

One common error with subqueries is more than one row returned for a single-row subquery.
In the SQL statement in the above example, the subquery contains a GROUP BY clause, which
implies that the subquery will return multiple rows, one for each group it finds. In this case, the
result of the subquery will be 2850, 3000 and 5000.

SQL> SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO;

MAX(SAL)
---------
2850
3000
5000

The outer query takes the results of the subquery (2850, 3000, 5000) and uses these results in
its WHERE clause. The WHERE clause contains an equal (=) operator, a single-row comparison
operator expecting only one value. The = operator cannot accept more than one value from the
subquery and therefore generates the error.
To correct this error, change the = operator to IN.
Find the employees who earn the same salary as the minimum salary for each department.
SQL> SELECT * FROM EMP
2 WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10

The inner query is executed first, producing a query result. The main query block is then
processed and uses the values returned by the inner query to complete its search condition. In
fact, the main query would appear to the Oracle server as follows:

SELECT last_name, salary, department_id


FROM employees
WHERE salary IN (2850, 3000, 5000);

95 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Display all employees who are working on the same post of department
number 10 employees
SQL> SELECT * FROM EMP WHERE JOB IN (SELECT JOB FROM EMP WHERE DEPTNO=10);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7900 JAMES CLERK 7698 03-DEC-81 950 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7369 SMITH CLERK 7902 17-DEC-80 800 20

8 rows selected.

Find all available jobs/posts of department number 10

SQL> SELECT JOB FROM EMP WHERE DEPTNO=10;

JOB
---------
MANAGER
PRESIDENT
CLERK

SQL> SELECT * FROM EMP WHERE JOB IN ('MANAGER','PRESIDENT','CLERK');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

8 rows selected.

Retrieve all managers of CLERK


SQL> SELECT * FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP WHERE JOB='CLERK');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT MGR FROM EMP WHERE JOB='CLERK';

Result of the above query


7902 7788 7698 7782

96 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Using ANY and ALL Operator in Multiple-Row Subqueries

ANY Æ OR

>ANY means more than the minimum.


<ANY means less than the maximum.
=ANY is equivalent to IN operator.

ALL Æ AND

>ALL means more than the maximum.


<ALL means less than the minimum.
= ALL is not possible.

The >ANY Operator

List all employees having salaries more then the minimum salary of department # 30

SQL> SELECT SAL FROM EMP WHERE DEPTNO=30;

SAL
---------
1600
1250
1250
2850
1500
950

6 rows selected.

SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30;

MIN(SAL)
---------
950

SQL> SELECT * FROM EMP


WHERE SAL>(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

12 rows selected.

SQL>

97 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP


2 WHERE SAL > ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20

12 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL > ANY (950,1250,1500,1600,2850);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

12 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL>950 OR SAL>1250 OR SAL>1500 OR SAL>1600 OR SAL>2850;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

12 rows selected.

98 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The <ANY Operator

List all employees having salaries less then the maximum salary of department # 30

SQL> SELECT SAL FROM EMP WHERE DEPTNO=30;

SAL
---------
1600
1250
1250
2850
1500
950

6 rows selected.

SQL> SELECT MAX(SAL) FROM EMP WHERE DEPTNO=30;


2850

SQL> SELECT * FROM EMP


2 WHERE SAL<(SELECT MAX(SAL) FROM EMP WHERE DEPTNO=30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

9 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL < ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10

9 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL < ANY (950,1250,1500,1600,2850);

SQL> SELECT * FROM EMP


2 WHERE SAL<950 OR SAL<1250 OR SAL<1500 OR SAL<1600 OR SAL<2850;

99 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The =ANY Operator

SQL> SELECT SAL FROM EMP WHERE DEPTNO=30;

SAL
---------
1600
1250
1250
2850
1500
950

6 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL = ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

6 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL IN (950,1250,1500,1600,2850);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

6 rows selected.

SQL> SELECT * FROM EMP


2 WHERE SAL IN (SELECT SAL FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

6 rows selected.

100 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The >ALL Operator

List of all employees having salaries more then the maximum salary of department # 30

SQL> SELECT SAL FROM EMP WHERE DEPTNO = 30;

SAL
---------
1600
1250
1250
2850
1500
950

6 rows selected.

SQL> SELECT MAX(SAL) FROM EMP WHERE DEPTNO = 30;


2850

SQL> SELECT * FROM EMP


2 WHERE SAL > (SELECT MAX(SAL) FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP


2 WHERE SAL > ALL (SELECT SAL FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP


2 WHERE SAL > ALL (950,1250,1500,1600,2850);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP


2 WHERE SAL>950 AND SAL>1250 AND SAL>1500 AND SAL>1600 AND SAL>2850;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

101 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The <ALL Operator

SQL> SELECT SAL FROM EMP WHERE DEPTNO = 30;

SAL
---------
1600
1250
1250
2850
1500
950

6 rows selected.

SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO = 30;

MIN(SAL)
---------
950

SQL> SELECT * FROM EMP


2 WHERE SAL < (SELECT MIN(SAL) FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

SQL> SELECT * FROM EMP


2 WHERE SAL < ALL (SELECT SAL FROM EMP WHERE DEPTNO = 30);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

SQL> SELECT * FROM EMP


2 WHERE SAL < ALL (950,1250,1500,1600,2850);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

=<ALL is not possible.

SQL> SELECT * FROM EMP


2 WHERE SAL = ALL (SELECT SAL FROM EMP WHERE DEPTNO = 30);

no rows selected

SQL>

102 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

List all employees having salaries less then the maximum salary of any
"CLERK". Do not display any "CLERK".
SQL> SELECT * FROM EMP WHERE SAL < (SELECT MAX(SAL) FROM EMP WHERE JOB='CLERK');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30

SQL> SELECT * FROM EMP WHERE SAL <ANY (SELECT SAL FROM EMP WHERE JOB='CLERK');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

SQL> SELECT * FROM EMP


WHERE SAL <ANY (SELECT SAL FROM EMP WHERE JOB='CLERK') AND JOB<>'CLERK';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

List all employees having salaries more then the average salary of any
department.
SQL> SELECT * FROM EMP
WHERE SAL >ALL (SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO;

AVG(SAL)
---------
1566.6667
2175
2916.6667

103 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

What happened if inner query return null

A common problem with subqueries is no rows being returned by the inner query.
In the following SQL statement, the subquery contains a WHERE clause. Presumably, the
intention is to find the employee whose commission is equal to SMITH’s commission. The
statement is correct but selects no rows when executed.

There is no commission for SMITH, So the subquery returns no rows. The outer query takes the
results of the subquery (null) and uses these results in its WHERE clause. The outer query finds
no employee with a COMM equal to null, and so returns no rows. If a COMM existed with a
value of null, the row is not returned because comparison of two null values yields a null,
therefore the WHERE condition is not true.

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

Display all employees whose commission is equal to SMITH’s commission.


SQL> SELECT COMM FROM EMP WHERE ENAME='SMITH';

COMM
---------

SQL> SELECT * FROM EMP


2 WHERE COMM=(SELECT COMM FROM EMP WHERE ENAME='SMITH');

no rows selected

SQL> SELECT * FROM EMP


2 WHERE NVL(COMM,-1)=(SELECT NVL(COMM,-1) FROM EMP WHERE ENAME='SMITH');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

10 rows selected.

104 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

List all employees having at least one subordinate.


SQL> SELECT * FROM EMP
2 WHERE EMPNO IN (SELECT MGR FROM EMP);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

6 rows selected.

List of all employees having no sub-ordinate.


SQL> SELECT * FROM EMP
2 WHERE EMPNO NOT IN (SELECT MGR FROM EMP);

no rows selected

The SQL statement on the slide attempts to display all the employees who do not have any
subordinates. Logically, this SQL statement should have returned 8 rows. However, the SQL
statement does not return any rows. One of the values returned by the inner query is a null
value, and hence the entire query returns no rows. The reason is that all conditions that
compare a null value result in a null. So whenever null values are likely to be part of the results
set of a subquery, do not use the NOT IN operator.
Alternatively, a WHERE clause can be included in the subquery to display all employees who do
not have any subordinates:
SQL> SELECT * FROM EMP
2 WHERE EMPNO NOT IN (SELECT NVL(MGR,0) FROM EMP);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

8 rows selected.

SQL> SELECT * FROM EMP


2 WHERE EMPNO NOT IN (SELECT MGR FROM EMP WHERE MGR IS NOT NULL);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

8 rows selected.

105 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 7
Producing Readable Output with SQL*Plus
Substitution Variables

A variable can be thought of as a container in which the values are temporarily stored. When
the statement is run, the value is substituted.

In SQL*Plus, you can use single ampersand (&) substitution variables to temporarily store
values. You can predefine variables in SQL*Plus by using the DEFINE command. DEFINE
creates and assigns a value to a variable.

Use SQL*Plus substitution variables to:


• Temporarily store values
– Single ampersand (&)
– Double ampersand (&&)
– DEFINE command
• Pass variable values between SQL statements

Display environmental variables by using [DEF]INE command


SQL> DEFINE
DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release
10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options" (CHAR)
DEFINE _O_RELEASE = "1002000100" (CHAR)
DEFINE _RC = "1" (CHAR)

SQL> DEF
DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release
10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options" (CHAR)
DEFINE _O_RELEASE = "1002000100" (CHAR)

Declare variables in SQL Plus environment by using DEFINE Command


SQL> DEFINE A=10

SQL> DEFINE B=SMITH

SQL> DEFINE C=ALLEN

SQL> DEFINE
DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release
10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options" (CHAR)
DEFINE _O_RELEASE = "1002000100" (CHAR)
DEFINE _RC = "1" (CHAR)
DEFINE A = "10" (CHAR)
DEFINE B = "SMITH" (CHAR)
DEFINE C = "ALLEN" (CHAR)

106 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Remove defined variables in SQL Plus environment by using UNDEFINE


Command
SQL> UNDEFINE C

Display value of specific variable


SQL> DEF A
DEFINE A = "10" (CHAR)
SQL> DEF B
DEFINE B = "SMITH" (CHAR)
SQL> DEF C
symbol c is UNDEFINED

Using defined variables in SQL statements by using single &


SQL> SELECT * FROM EMP WHERE DEPTNO=&A;
old 1: SELECT * FROM EMP WHERE DEPTNO=&A
new 1: SELECT * FROM EMP WHERE DEPTNO=10

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE ENAME='&B';


old 1: SELECT * FROM EMP WHERE ENAME='&B'
new 1: SELECT * FROM EMP WHERE ENAME='SMITH'

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

SQL> SET VERIFY OFF

SQL> SELECT * FROM EMP WHERE DEPTNO=&A;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE ENAME='&B';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

Use singe & Substitution Variable if you want to use already defined variable i.e. A or B
Enclose Char and Date in single quote

107 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

If you use & single substitution variable in SQL statement which is not
defined then it will prompt (ask) each time for the value and variable
will not be created.
SQL> SET VERIFY ON

SQL> SELECT * FROM EMP WHERE DEPTNO=&ASLAM;


Enter value for aslam: 10
old 1: SELECT * FROM EMP WHERE DEPTNO=&ASLAM
new 1: SELECT * FROM EMP WHERE DEPTNO=10

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE DEPTNO=&DEPARTMENT_NO;


Enter value for department_no: 20
old 1: SELECT * FROM EMP WHERE DEPTNO=&DEPARTMENT_NO
new 1: SELECT * FROM EMP WHERE DEPTNO=20

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP WHERE JOB='&JOB_TITLE';


Enter value for job_title: CLERK
old 1: SELECT * FROM EMP WHERE JOB='&JOB_TITLE'
new 1: SELECT * FROM EMP WHERE JOB='CLERK'

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE SAL>&SALARY;


Enter value for salary: 2000
old 1: SELECT * FROM EMP WHERE SAL>&SALARY
new 1: SELECT * FROM EMP WHERE SAL>2000

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

108 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP WHERE HIREDATE<'&HIREDATE';


Enter value for hiredate: 01-JAN-1981
old 1: SELECT * FROM EMP WHERE HIREDATE<'&HIREDATE'
new 1: SELECT * FROM EMP WHERE HIREDATE<'01-JAN-1981'

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

SQL> SELECT * FROM EMP WHERE HIREDATE<&JOINING_DATE;


Enter value for joining_date: '01-JAN-1981'
old 1: SELECT * FROM EMP WHERE HIREDATE<&JOINING_DATE
new 1: SELECT * FROM EMP WHERE HIREDATE<'01-JAN-1981'

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20

SQL> DEFINE
DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release
10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options" (CHAR)
DEFINE _O_RELEASE = "1002000100" (CHAR)
DEFINE _RC = "1" (CHAR)
DEFINE A = "10" (CHAR)
DEFINE B = "SMITH" (CHAR)

If you use && double substitution variable in SQL statement which is


not defined then it will prompt (ask) for the first time for the value and
variable will be create with provided name.

SQL> SELECT * FROM EMP WHERE DEPTNO=&&DEPT_NO;


Enter value for dept_no: 10
old 1: SELECT * FROM EMP WHERE DEPTNO=&&DEPT_NO
new 1: SELECT * FROM EMP WHERE DEPTNO=10

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE SAL>&&EMPLOYEE_SALARY;


Enter value for employee_salary: 3000
old 1: SELECT * FROM EMP WHERE SAL>&&EMPLOYEE_SALARY
new 1: SELECT * FROM EMP WHERE SAL>3000

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10

109 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Notice that DEPT_NO and EMPLOYEE_SALARY variable have been created by using && double
substitution variable.

SQL> DEFINE
DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release
10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options" (CHAR)
DEFINE _O_RELEASE = "1002000100" (CHAR)
DEFINE _RC = "1" (CHAR)
DEFINE A = "10" (CHAR)
DEFINE B = "SMITH" (CHAR)
DEFINE DEPT_NO = "10" (CHAR)
DEFINE EMPLOYEE_SALARY = "3000" (CHAR)

You can use DEPT_NO and EMPLOYEE_SALARY variables in SQL


statements
SQL> SET VERIFY OFF

SQL> SELECT * FROM EMP WHERE SAL=&EMPLOYEE_SALARY;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP


2 WHERE JOB='CLERK' AND DEPTNO=&DEPT_NO;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP


2 WHERE JOB='CLERK' AND DEPTNO=&&DEPT_NO;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7934 MILLER CLERK 7782 23-JAN-82 1300 10

• Both & and && first search for variable in memory.


• Both & and && use existing value of the variable if exist.
• Both will collect input from user if variable does not exist.
• & destroy variable after query if it does not already exist but && store variable value in
memory for later use.

Variable can be defined by using DEFINE command or by using && substitution variable.
Variable can be destroy by using UNDEFINE command or variable will be destroy when you exit
from the current session.

110 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Use of & and && in different clauses


SQL> SELECT &COL1, &COL2, &COL3 FROM EMP WHERE SAL>=&SALARY;
Enter value for col1: EMPNO
Enter value for col2: ENAME
Enter value for col3: SAL
Enter value for salary: 3000

EMPNO ENAME SAL


--------- ---------- ---------
7788 SCOTT 3000
7839 KING 5000
7902 FORD 3000

SQL> SELECT &COL1, &COL2, &COL3 FROM &TABLE_NAME;


Enter value for col1: DEPTNO
Enter value for col2: DNAME
Enter value for col3: LOC
Enter value for table_name: DEPT

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL> SELECT &COL1, &COL2, &COL3 FROM &TABLE_NAME;


Enter value for col1: EMPNO
Enter value for col2: JOB
Enter value for col3: ENAME
Enter value for table_name: EMP

EMPNO JOB ENAME


--------- --------- ----------
7369 CLERK SMITH
7499 SALESMAN ALLEN
7521 SALESMAN WARD
7566 MANAGER JONES
7654 SALESMAN MARTIN
7698 MANAGER BLAKE
7782 MANAGER CLARK
7788 ANALYST SCOTT
7839 PRESIDENT KING
7844 SALESMAN TURNER
7876 CLERK ADAMS
7900 CLERK JAMES
7902 ANALYST FORD
7934 CLERK MILLER

SQL> SELECT &COL1, &COL2, &COL3 FROM &TABLE_NAME;


Enter value for col1: EMPNO, ENAME, JOB
Enter value for col2: SAL
Enter value for col3: DEPTNO
Enter value for table_name: EMP

111 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP


2 WHERE SAL = (&QUERY);
Enter value for query: SELECT SAL FROM EMP WHERE ENAME = 'ALLEN'

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Environmental Setting

------------------- SET FEEDBACK [ON/OFF/n] -------------------

SQL> SET FEEDBACK 3


SQL> SELECT * FROM EMP WHERE DEPTNO=10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

3 rows selected.

SQL> SET FEEDBACK 5


SQL> SELECT * FROM EMP WHERE DEPTNO=10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

------------------- SET HEADING ON/OFF -------------------

SQL> SET HEADING OFF


SQL> SELECT * FROM EMP WHERE DEPTNO=10;

7782 CLARK MANAGER 7839 09-JUN-81 2450 10


7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SET HEADING ON


SQL> SELECT * FROM EMP WHERE DEPTNO=10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

------------------- SHOW -------------------


SQL> SHOW HEADING
heading ON
SQL> SHOW FEEDBACK
FEEDBACK ON for 5 or more rows
SQL> SHOW ALL

112 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

---------------- SET LINESIZE --------------------


SHOW LINES
SELECT * FROM EMP;
SET LINES 100;
SHOW LINESIZE
SHOW LINES

---------------- SET PAGESIZE --------------------


SHOW PAGESIZE
SHOW PAGES
SET PAGESIZE 25

The COLUMN Command


SQL> COL ENAME HEADING EMPLOYEE
SQL> COL JOB HEADING JOB_TITLE
SQL> COL COMM HEADING CMSN NULL NOT_APP
SQL> COL SAL FORMAT 9,999.99

SQL> SELECT * FROM EMP;

EMPNO EMPLOYEE JOB_TITLE MGR HIREDATE SAL CMSN DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 8,00 NOT_APP 20
7499 ALLEN SALESMAN 7698 20-FEB-81 16,00 300 30
7521 WARD SALESMAN 7698 22-FEB-81 12,50 500 30
7566 JONES MANAGER 7839 02-APR-81 29,75 NOT_APP 20
7654 MARTIN SALESMAN 7698 28-SEP-81 12,50 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 28,50 NOT_APP 30
7782 CLARK MANAGER 7839 09-JUN-81 24,50 NOT_APP 10
7788 SCOTT ANALYST 7566 19-APR-87 30,00 NOT_APP 20
7839 KING PRESIDENT 17-NOV-81 50,00 NOT_APP 10
7844 TURNER SALESMAN 7698 08-SEP-81 15,00 0 30
7876 ADAMS CLERK 7788 23-MAY-87 11,00 NOT_APP 20
7900 JAMES CLERK 7698 03-DEC-81 9,50 NOT_APP 30
7902 FORD ANALYST 7566 03-DEC-81 30,00 NOT_APP 20
7934 MILLER CLERK 7782 23-JAN-82 13,00 NOT_APP 10

View setting of specific column


SQL> COL SAL
COLUMN SAL ON
FORMAT 9,999.99

View setting of all columns


SQL> COL

Clear format of specific column


SQL> COL SAL CLEAR
SQL> COL COMM CLEAR
SQL> COL JOB CLEAR
SQL> COL ENAME CLEAR

Clear format of all columns


SQL> CLEAR COLUMNS

113 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> COL SAL NOPRINT


SQL> COL COMM NOPRINT
SQL> COL ENAME FORMAT A20 HEADING EMPLOYEE_NAME
SQL> SELECT * FROM EMP;

EMPNO EMPLOYEE_NAME JOB MGR HIREDATE DEPTNO


--------- -------------------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 20
7499 ALLEN SALESMAN 7698 20-FEB-81 30
7521 WARD SALESMAN 7698 22-FEB-81 30
7566 JONES MANAGER 7839 02-APR-81 20
7654 MARTIN SALESMAN 7698 28-SEP-81 30
7698 BLAKE MANAGER 7839 01-MAY-81 30
7782 CLARK MANAGER 7839 09-JUN-81 10
7788 SCOTT ANALYST 7566 19-APR-87 20
7839 KING PRESIDENT 17-NOV-81 10
7844 TURNER SALESMAN 7698 08-SEP-81 30
7876 ADAMS CLERK 7788 23-MAY-87 20
7900 JAMES CLERK 7698 03-DEC-81 30
7902 FORD ANALYST 7566 03-DEC-81 20
7934 MILLER CLERK 7782 23-JAN-82 10

14 rows selected.

SQL> COL SAL PRINT


SQL> COL ENAME FORMAT A10 HEADING NAME JUSTIFY CENTER
SQL> COL COMM CLEAR

SQL> SELECT * FROM EMP;

EMPNO NAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

What is DEMOBLD.SQL?
DEMOBLD.SQL is a script file created by oracle. It contains tables for practice.

E:\oracle\ora92\sqlplus\demo\demobld.sql

114 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL Statements Versus SQL*Plus Commands

SQL SQL*Plus

• A language • An environment

• ANSI standard • Oracle proprietary

• Keyword cannot be abbreviated • Keywords can be abbreviated

• Statements manipulate data and table • Commands do not allow


definitions in the manipulation of values in the
databa database

• Runs on a browser

• Centrally loaded, does not have to


be implemented on each machine

• Do not require statement


terminator

• Command does not store in buffer

SQL> SELECT EMPNO, ENAME, JOB, SAL


2 FROM EMP
3 WHERE DEPTNO=10
4 ORDER BY EMPNO;

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7782 CLARK MANAGER 2450
7839 KING PRESIDENT se
5000
7934 MILLER CLERK 1300
• Require statement terminator ;

• Last query stores in buffer


The LIST command
SQL> L SQL> L 1 3
1 SELECT EMPNO, ENAME, JOB, SAL 1 SELECT EMPNO, ENAME, JOB, SAL
2 FROM EMP 2 FROM EMP
3 WHERE DEPTNO=10 3* WHERE DEPTNO=10
4* ORDER BY EMPNO SQL> L 1
1* SELECT EMPNO, ENAME, JOB, SAL
SQL>

The SAVE command

To save your query in a text file for later use

SQL> SAVE D:\Q1


Created file D:\Q1

Use REPLACE/REP if you want to overwrite previous file.


SQL> SAVE Q1 REP

115 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The START or @ command

To load and execute already saved query without listing a query.

SQL> @D:\Q1

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300

SQL> START D:\Q1

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300

The RUN or R command

To load and execute already saved query with listing a query.


SQL> RUN D:\Q1
1 SELECT EMPNO, ENAME, JOB, SAL
2 FROM EMP
3 WHERE DEPTNO=10
4* ORDER BY EMPNO

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300

To run already loaded query in a buffer.

SQL> R
1 SELECT EMPNO, ENAME, JOB, SAL
2 FROM EMP
3 WHERE DEPTNO=10
4* ORDER BY EMPNO

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300

The GET command The / Command


Only load already saved query into buffer. To execute a query already loaded in buffer.

SQL> GET D:\Q1 SQL> /


1 SELECT EMPNO, ENAME, JOB, SAL
2 FROM EMP EMPNO ENAME JOB SAL
3 WHERE DEPTNO=10 --------- ---------- --------- ---------
4* ORDER BY EMPNO 7782 CLARK MANAGER 2450
SQL> 7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300
116 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 8
Manipulating Data
Data Manipulation Language

• A DML statement is executed when you:


– Add new rows to a table
– Modify existing rows in a table
– Remove existing rows from a table
• A transaction consists of a collection of DML statements that form a logical unit of work.

The INSERT Statement

You can add new rows to a table by issuing the INSERT statement.

Inserting New Rows

• Insert a new row containing values for each column.


• List values in the default order of the columns in the table.
• Optionally, list the columns in the INSERT clause.
• Enclose character and date values within single quotation marks.

SQL> INSERT INTO DEPT


2 (DEPTNO, DNAME, LOC)
3 VALUES
4 (55, 'IT','KARACHI');

1 row created.

Because you can insert a new row that contains values for each column, the column list is not
required in the INSERT clause. However, if you do not use the column list, the values must be
listed according to the default order of the columns in the table, and a value must be provided
for each column.

Inserting Rows with Null Values by using NULL in value list

SQL> INSERT INTO DEPT


2 (DEPTNO, DNAME, LOC)
3 VALUES
4 (60,'PURCHASE',NULL);

1 row created.

Explicit method: Specify the NULL keyword in the VALUES clause.

Inserting Rows with Null Values by excluding column from column list.
SQL> INSERT INTO DEPT
2 (DEPTNO, DNAME)
3 VALUES
4 (65,'AUDIT');

1 row created.

Implicit method: Omit the column from the column list.

Only one row is inserted at a time if VALUES clause is used for insertion with INSERT.

117 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

You can not insert null value in not null column. So be care full when you are inserting rows in a
table. Null value can be inserted by NULL key word or by omitting column from column list.

SQL> INSERT INTO DEPT


2 (DNAME, LOC)
3 VALUES
4 ('HR','LAHORE');
INSERT INTO DEPT
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."DEPT"."DEPTNO")

You are inserting NULL value in DEPTNO column, and null is not allowed for DEPTNO column.

When inserting rows in a table any constraint may violate, so be care full.

SQL> INSERT INTO DEPT


2 (DEPTNO, DNAME, LOC)
3 VALUES
4 (10,'MIS','LAHORE');
INSERT INTO DEPT
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.PK_DEPT) violated

You are inserting duplicate value in DEPTNO column, DEPTNO is primary key.

SQL> INSERT INTO EMP


2 (EMPNO, ENAME, JOB, DEPTNO)
3 VALUES
4 (4,'ALI','MANAGER',70);
INSERT INTO EMP
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.FK_DEPTNO) violated - parent key not found

You are inserting a value 70 in DEPTNO column which is not present in DEPT table.

Inserting Special Values

SQL> INSERT INTO EMP


2 (EMPNO, ENAME, JOB, HIREDATE, DEPTNO)
3 VALUES
4 (1,USER,'CLERK',SYSDATE,55);

1 row created.

Inserting Specific Date Values


SQL> INSERT INTO EMP
2 (EMPNO, ENAME, JOB, HIREDATE)
3 VALUES
4 (2,'ASLAM','MANAGER',TO_DATE('JULY 28, 2008','MONTH DD, RRRR'));

1 row created.

The DD-MON-YY format is usually used to insert a date value. If a date must be entered in a format other than the
default format, you must use the TO_DATE function.

118 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Creating a Script

• Use & substitution in a SQL statement to prompt for values.


• & is a placeholder for the variable value.

SQL> INSERT INTO EMP


2 (EMPNO, ENAME, JOB, SAL, HIREDATE, DEPTNO)
3 VALUES
4 (&EMPNO, '&ENAME','&JOB',&SALARY,'&HIREDATE',&DEPTNO);
Enter value for empno: 3
Enter value for ename: SALEEM
Enter value for job: CLERK
Enter value for salary: 2000
Enter value for hiredate: 10-JAN-2007
Enter value for deptno: 10
old 4: (&EMPNO, '&ENAME','&JOB',&SALARY,'&HIREDATE',&DEPTNO)
new 4: (3, 'SALEEM','CLERK',2000,'10-JAN-2007',10)

1 row created.

Verify new insertion


SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
55 IT KARACHI
60 PURCHASE
65 AUDIT

7 rows selected.

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 SCOTT CLERK 06-AUG-08 55
2 ASLAM MANAGER 28-JUL-08
3 SALEEM CLERK 10-JAN-07 2000 10

17 rows selected.

119 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP WHERE DEPTNO=10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
3 SALEEM CLERK 10-JAN-07 2000 10

SQL> SELECT * FROM EMP WHERE JOB IN ('CLERK','MANAGER');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 SCOTT CLERK 06-AUG-08 55
2 ASLAM MANAGER 28-JUL-08
3 SALEEM CLERK 10-JAN-07 2000 10

10 rows selected.

Is the following query working correctly?


What about ASLAM’s record?
Aslam is MANAGER and department is not assigned to him.
What is the meaning of the following query?

SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO


2 FROM EMP
3 WHERE DEPTNO <> 10 AND JOB IN ('CLERK','MANAGER');

EMPNO ENAME JOB SAL DEPTNO


--------- ---------- --------- --------- ---------
7369 SMITH CLERK 800 20
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
1 SCOTT CLERK 55

6 rows selected.

120 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

You have to change your condition in where clause.

SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO


2 FROM EMP
3 WHERE (DEPTNO<>10 OR DEPTNO IS NULL) AND JOB IN ('CLERK','MANAGER');

EMPNO ENAME JOB SAL DEPTNO


--------- ---------- --------- --------- ---------
7369 SMITH CLERK 800 20
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
1 SCOTT CLERK 55
2 ASLAM MANAGER

7 rows selected.

SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO


2 FROM EMP
3 WHERE NVL(DEPTNO,0)<>10 AND JOB IN ('CLERK','MANAGER');

EMPNO ENAME JOB SAL DEPTNO


--------- ---------- --------- --------- ---------
7369 SMITH CLERK 800 20
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
1 SCOTT CLERK 55
2 ASLAM MANAGER

7 rows selected.

121 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The following joining query will not show ASLAM’s record, because ASLAM is not assigned any
department. The department value of ASLAM’s record mismatched with value in DEPT table.

SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC


2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
1 SCOTT CLERK 55 IT KARACHI
3 SALEEM CLERK 2000 10 ACCOUNTING NEW YORK

16 rows selected.

How can I find all employees either value is matched or not?


SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO(+);

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
1 SCOTT CLERK 55 IT KARACHI
2 ASLAM MANAGER
3 SALEEM CLERK 2000 10 ACCOUNTING NEW YORK

17 rows selected.

I want to find only those employees whose department value is mismatched?


SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO(+) AND E.DEPTNO IS NULL;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
2 ASLAM MANAGER

122 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

I want to find those departments in which no employee was hired.

SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, D.DEPTNO, D.DNAME, D.LOC


2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO(+)=D.DEPTNO AND E.EMPNO IS NULL;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------
40 OPERATIONS BOSTON
60 PURCHASE
65 AUDIT

INSERT is a DML statement. For saving data permanently into database, commit may be applied either
implicitly or explicitly.

The COMMIT statement

For applying explicit commit the COMMIT statement is used.

SQL> COMMIT;

Commit complete.

SQL>

The ROLLBACK statement


You can undo or revert data which is changed by DML statements. To revert/undo you have to use
rollback, rollback may be applied either implicitly or explicitly.

For applying explicit rollback the ROLLBACK statement is used.

SQL> ROLLBACK;

Rollback complete.

SQL>

COMMIT and ROLLBACK will be discussed in detail.

123 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Let’s come back to INSERT statement.

Execute the following query to create a table for practice INSERT statement.

Create a table EMP_INS with the same structure of EMP table. The WHERE 1>2 restrict for
copying data.

SQL> CREATE TABLE EMP_INS AS SELECT * FROM EMP WHERE 1>2;

Table created.

Notice the EMPNO column in both EMP and EMP_INS tables in the below:

SQL> DESC EMP


Name Null? Type
------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

SQL> DESC EMP_INS


Name Null? Type
------------------------------- -------- ----
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

SQL> CREATE TABLE DEPT_INS AS SELECT * FROM DEPT;

Table created.

Note: when you create a table by using subquery like in the above examples, then constrains
will not be copied.

Create a table DEPT_INS with the same structure of DEPT table as well as with all rows,
because the WHERE clause is not used.
SQL> SELECT * FROM EMP_INS;

no rows selected

SQL> SELECT * FROM DEPT_INS;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
55 IT KARACHI
60 PURCHASE
65 AUDIT

7 rows selected.

124 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Copying Rows from Another Table

You can use the INSERT statement to add rows to a table where the values are derived from
existing tables. In place of the VALUES clause, you use a subquery.

The number of columns and their data types in the column list of the INSERT clause must
match the number of values and their data types in the subquery. Do not use the VALUES
clause.

Insert rows from EMP table to EMP_INS table by using INSERT statement.

The following query will copy all employees of department number 10 from EMP table into
EMP_INS table. If you do not specify WHERE clause then all rows of EMP table will copy into
EMP_INS table.

SQL> INSERT INTO EMP_INS


2 SELECT * FROM EMP WHERE DEPTNO=10;

4 rows created.

If you do not specify column list in INSERT clause and in the subquery (SELECT clause), its
means the structure of both tables are same.

The following query will copy EMPNO, ENAME, JOB, SAL & DEPTNO columns of those employees
who are working as CLEAR and MANAGER and did not belong to department number 10.

SQL> INSERT INTO EMP_INS


2 (EMPNO, ENAME, JOB, SAL, DEPTNO)
3 SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
4 FROM EMP
5 WHERE (DEPTNO <> 10 OR DEPTNO IS NULL) AND JOB IN ('CLERK','MANAGER');

7 rows created.

If structure of both tables are not same then you must provide the corresponding columns for
insertion in INSERT clause and in the subquery (SELECT clause).

SQL> SELECT * FROM EMP_INS;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
3 SALEEM CLERK 10-JAN-07 2000 10
7369 SMITH CLERK 800 20
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
1 SCOTT CLERK 55
2 ASLAM MANAGER

11 rows selected.

125 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Changing Data in a Table

You can modify existing rows by using the UPDATE statement.

• Specific row or rows are modified if you specify the WHERE clause.
• All rows in the table are modified if you omit the WHERE clause.

SQL> UPDATE EMP


2 SET ENAME='S.C.O.T.T.'
3 WHERE EMPNO=1;

1 row updated.

SQL> SELECT * FROM EMP WHERE EMPNO=1;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
1 S.C.O.T.T. CLERK 06-AUG-08 55

SQL> UPDATE EMP


2 SET ENAME='SCOTT',
3 SAL =1000
4 WHERE EMPNO=1;

1 row updated.

SQL> SELECT * FROM EMP WHERE EMPNO=1;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
1 SCOTT CLERK 06-AUG-08 1000 55

Updating with a Subquery

SQL> UPDATE EMP


2 SET MGR = 7839,
3 SAL = (SELECT MAX(SAL) FROM EMP WHERE JOB='MANAGER'),
4 DEPTNO = 55
5 WHERE EMPNO = 2;

1 row updated.
SQL> SELECT * FROM EMP WHERE EMPNO=2;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
2 ASLAM MANAGER 7839 28-JUL-08 2975 55

Updating Rows Based on Another Table

SQL> UPDATE EMP


2 SET JOB = 'ASST IT',
3 SAL = SAL+SAL*15/100,
4 MGR = 2 ,
5 DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DNAME='IT')
6 WHERE EMPNO=3;

1 row updated.

126 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Updating with a Nested Subquery


SQL> UPDATE EMP
2 SET MGR=(SELECT EMPNO FROM EMP
3 WHERE JOB='MANAGER' AND
4 DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='IT')
5 )
6 WHERE EMPNO=1;

1 row updated.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 SCOTT CLERK 2 06-AUG-08 1000 55
2 ASLAM MANAGER 7839 28-JUL-08 2975 55
3 SALEEM ASST IT 2 10-JAN-07 2300 55

17 rows selected.

Updating Rows: Integrity Constraint Error

SQL> UPDATE EMP


2 SET DEPTNO=5
3 WHERE SAL>2000;
UPDATE EMP
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.FK_DEPTNO) violated - parent key not
found

If you attempt to update a record with a value that is tied to an integrity constraint, an error is
returned. In the above example, department number 5 does not exist in the parent table,
DEPT, and so you receive the parent key violation ORA-02291.

127 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 SCOTT CLERK 2 06-AUG-08 1000 55
2 ASLAM MANAGER 7839 28-JUL-08 2975 55
3 SALEEM ASST IT 2 10-JAN-07 2300 55

17 rows selected.

Give 10% increment to all employees who have hired before 12 or more months.

SQL> UPDATE EMP


2 SET SAL=SAL+SAL*10/100
3 WHERE TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE))>=12;

15 rows updated.

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 880 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1760 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1375 500 30
7566 JONES MANAGER 7839 02-APR-81 3273 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1375 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 3135 30
7782 CLARK MANAGER 7839 09-JUN-81 2695 10
7788 SCOTT ANALYST 7566 19-APR-87 3300 20
7839 KING PRESIDENT 17-NOV-81 5500 10
7844 TURNER SALESMAN 7698 08-SEP-81 1650 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1210 20
7900 JAMES CLERK 7698 03-DEC-81 1045 30
7902 FORD ANALYST 7566 03-DEC-81 3300 20
7934 MILLER CLERK 7782 23-JAN-82 1430 10
1 SCOTT CLERK 2 06-AUG-08 1000 55
2 ASLAM MANAGER 7839 28-JUL-08 2975 55
3 SALEEM ASST IT 2 10-JAN-07 2530 55

17 rows selected.

SQL> ROLLBACK;

Rollback complete.

128 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP_INS;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
3 SALEEM CLERK 10-JAN-07 2000 10
7369 SMITH CLERK 800 20
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
1 SCOTT CLERK 55
2 ASLAM MANAGER

11 rows selected.

SQL> UPDATE EMP_INS SET SAL=NULL;

11 rows updated.

SQL> SELECT * FROM EMP_INS;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 10
7839 KING PRESIDENT 17-NOV-81 10
7934 MILLER CLERK 7782 23-JAN-82 10
3 SALEEM CLERK 10-JAN-07 10
7369 SMITH CLERK 20
7566 JONES MANAGER 20
7698 BLAKE MANAGER 30
7876 ADAMS CLERK 20
7900 JAMES CLERK 30
1 SCOTT CLERK 55
2 ASLAM MANAGER

11 rows selected.

SQL> UPDATE EMP_INS A


2 SET SAL = (SELECT SAL FROM EMP B WHERE A.EMPNO=B.EMPNO);

SQL> SELECT * FROM EMP_INS;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
3 SALEEM CLERK 10-JAN-07 2300 10
7369 SMITH CLERK 800 20
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
1 SCOTT CLERK 1000 55
2 ASLAM MANAGER 2975

11 rows selected.

129 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Removing a Row from a Table

You can remove existing rows by using the DELETE statement.

Specific rows are deleted if you specify the WHERE clause.


SQL> DELETE EMP WHERE DEPTNO=10;

3 rows deleted.

SQL> DELETE FROM EMP WHERE DEPTNO=10;

3 rows deleted.

All rows in the table are deleted if you omit the WHERE clause.

SQL> DELETE EMP;

14 rows deleted.

SQL> DELETE FROM EMP;

14 rows deleted.

SQL> ROLLBACK;

Rollback complete.

Deleting Rows Based on Another Table


SQL> DELETE EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES');

6 rows deleted.

Deleting Rows: Integrity Constraint Error


SQL> DELETE DEPT WHERE DEPTNO=10;
DELETE DEPT WHERE DEPTNO=10
*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.FK_DEPTNO) violated - child record found

If you attempt to delete a record with a value that is tied to an integrity constraint, an error is
returned. In the above example you try to delete department number 10 from the DEPT table,
but it results in an error because department number is used as a foreign key in the EMPL
table. If the parent record that you attempt to delete has child records, then you receive the
child record found violation ORA-02292.

130 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Database Transactions

The Oracle server ensures data consistency based on transactions. Transactions give you more
flexibility and control when changing data, and they ensure data consistency in the event of
user process failure or system failure.

Transactions consist of DML statements that make up one consistent change to the data.

When Does a Transaction Start and End?

A transaction begins when the first DML statement is encountered and ends when one of the
following occurs:
• A COMMIT or ROLLBACK statement is issued
• A DDL statement, such as CREATE, is issued
• A DCL statement is issued
• The user exits SQL*Plus
• A machine fails or the system crashes
After one transaction ends, the next executable SQL statement automatically starts the next
transaction.

A DDL statement or a DCL statement is automatically committed and therefore implicitly ends a
transaction.

Explicit Transaction Control Statements


You can control the logic of transactions by using the COMMIT, SAVEPOINT, and ROLLBACK
statements.

Implicit Transaction Processing

• An automatic commit occurs under the following circumstances:


– DDL statement is issued
– DCL statement is issued
– Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements
• An automatic rollback occurs under an abnormal termination of SQL*Plus or a system
failure.

State of the Data Before COMMIT or ROLLBACK

• The previous state of the data can be recovered.


• The current user can review the results of the DML operations by using the SELECT
statement.
• Other users cannot view the results of the DML statements by the current user.
• The affected rows are locked; other users cannot change the data within the affected rows.

State of the Data after COMMIT

• Data changes are made permanent in the database.


• The previous state of the data is permanently lost.
• All users can view the results.
• Locks on the affected rows are released; those rows are available for other users to
manipulate.
• All savepoints are erased.

131 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

State of the Data After ROLLBACK

Discard all pending changes by using the ROLLBACK statement:


• Data changes are undone.
• Previous state of the data is restored.
• Locks on the affected rows are released.

Committing Data

SQL> COMMIT;

Commit complete.

Rollback Data

SQL> ROLLBACK;

Rollback complete.

Statement-Level Rollback

• If a single DML statement fails during execution, only that statement is rolled back.
• The Oracle server implements an implicit savepoint.
• All other changes are retained.
• The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK
statement.

Read Consistency

• Read consistency guarantees a consistent view of the data at all times.


• Changes made by one user do not conflict with changes made by another user.
• Read consistency ensures that on the same data:
– Readers do not wait for writers.
– Writers do not wait for readers.

Locking

In an Oracle database, locks:


• Prevent destructive interaction between concurrent transactions
• Require no user action
• Automatically use the lowest level of restrictiveness
• Are held for the duration of the transaction
• Are of two types: explicit locking and implicit locking

132 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 9
Creating and Managing Tables
Database Objects
An Oracle database can contain multiple data structures. Each structure should be outlined in
the database design so that it can be created during the build stage of database development.
• Table: Stores data
• View: Subset of data from one or more tables
• Sequence: Numeric value generator
• Index: Improves the performance of some queries
• Synonym: Gives alternative names to objects

Oracle Table Structures


• Tables can be created at any time, even while users are using the database.
• You do not need to specify the size of any table. The size is ultimately defined by the
amount of space allocated to the database as a whole. It is important, however, to
estimate how much space a table will use over time.
• Table structure can be modified online.

Tables can have up to 1,000 columns and must conform to standard database object-naming
conventions.

The CREATE TABLE Statement

Create tables to store data by executing the SQL CREATE TABLE statement. This statement is
one of the data definition language (DDL) statements

SQL> CREATE TABLE DEPT_INFO


2 (
3 DEPTNO NUMBER(2) PRIMARY KEY,
4 DNAME VARCHAR2(14),
5 LOC VARCHAR2(13)
6 );

Table created.

SQL> CREATE TABLE EMP_INFO


2 (
3 EMPNO NUMBER(4) PRIMARY KEY,
4 ENAME VARCHAR2(10),
5 JOB VARCHAR2(9),
6 MGR NUMBER(4) REFERENCES EMP (EMPNO),
7 HIREDATE DATE,
8 SAL NUMBER(7,2),
9 COMM NUMBER(7,2),
10 DEPTNO REFERENCES DEPT (DEPTNO)
11 );

Table created.

SQL>

DEPTNO is a primary key in DEPT table, and foreign key in EMP table.
EMPNO is a primary key in EMP table.

133 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

How to verify table creation?

By DESC / DESCRIBE Command

SQL> DESC DEPT_INFO


Name Null? Type
------------------------------- -------- ----
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

SQL> DESC EMP_INFO


Name Null? Type
------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

By SELECT Statement

SQL> SELECT * FROM DEPT_INFO;

no rows selected

SQL> SELECT * FROM EMP_INFO;

no rows selected

Querying the Data Dictionary

By a data dictionary view Æ USER_TABLES or (TABS)

SQL> SELECT TABLE_NAME FROM USER_TABLES;

By a data dictionary view Æ USER_OBJECTS or (OBJ)

SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE='TABLE';

By a data dictionary view Æ USER_CATALOG or (CAT)

SQL> SELECT * FROM USER_CATALOG WHERE TABLE_TYPE='TABLE';

By a data dictionary view Æ TAB or (TAB)

SQL> SELECT * FROM TAB WHERE TABTYPE='TABLE';

134 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Creating a Table by Using a Subquery

The following queries will create a table as well as copy all rows:

SQL> CREATE TABLE EMP1


2 AS SELECT * FROM EMP;

Table created.

SQL> CREATE TABLE EMP2


2 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP;

Table created.

SQL> CREATE TABLE EMP3


2 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10;

Table created.

SQL> CREATE TABLE EMP4


2 (EMP_ID, EMP_NAME, JOB, SALARY)
3 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP;

Table created.

SQL> DESC EMP1


Name Null? Type
------------------------------- -------- ----
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

SQL> DESC EMP2


Name Null? Type
------------------------------- -------- ----
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
SAL NUMBER(7,2)

SQL> DESC EMP3


Name Null? Type
------------------------------- -------- ----
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
SAL NUMBER(7,2)

SQL> DESC EMP4


Name Null? Type
------------------------------- -------- ----
EMP_ID NUMBER(4)
EMP_NAME VARCHAR2(10)
JOB VARCHAR2(9)
SALARY NUMBER(7,2)
135 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

The ALTER TABLE Statement

After you create a table, you may need to change the table structure because: you omitted a
column, your column definition needs to be changed, or you need to remove columns. You can
do this by using the ALTER TABLE statement.

You can add, modify, and drop columns to a table by using the ALTER TABLE statement.

You use the ADD clause to add columns.

SQL> ALTER TABLE EMP4


2 ADD HIREDATE DATE;

Table altered.

SQL> ALTER TABLE EMP4


2 ADD
3 (
4 COMM NUMBER(4),
5 DEPTNO NUMBER(2),
6 NIC VARCHAR2(13)
7 );

Table altered.

SQL> DESC EMP4


Name Null? Type
------------------------------- -------- ----
EMP_ID NUMBER(4)
EMP_NAME VARCHAR2(10)
JOB VARCHAR2(9)
SALARY NUMBER(7,2)
HIREDATE DATE
COMM NUMBER(4)
DEPTNO NUMBER(2)
NIC VARCHAR2(13)

You use the MODIFY clause to add columns.

You can modify a column definition by using the ALTER TABLE statement with the MODIFY
clause. Column modification can include changes to a column’s data type, size, and default
value.

SQL> ALTER TABLE EMP4


2 MODIFY COMM NUMBER(7,2);

Table altered.

SQL> ALTER TABLE EMP4


2 MODIFY
3 (
4 JOB VARCHAR2(10),
5 NIC VARCHAR2(15)
6 );

Table altered.

136 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> DESC EMP4


Name Null? Type
------------------------------- -------- ----
EMP_ID NUMBER(4)
EMP_NAME VARCHAR2(10)
JOB VARCHAR2(10)
SALARY NUMBER(7,2)
HIREDATE DATE
COMM NUMBER(7,2)
DEPTNO NUMBER(2)
NIC VARCHAR2(15)

Guidelines
• You can increase the width or precision of a numeric column.
• You can increase the width of numeric or character columns.
• You can decrease the width of a column only if the column contains only null values or if
the table has no rows.
• You can change the data type only if the column contains null values.
• You can convert a CHAR column to the VARCHAR2 data type or convert a VARCHAR2
column to the CHAR data type only if the column contains null values or if you do not
change the size.
• A change to the default value of a column affects only subsequent insertions to the
table.

Dropping a Column

You can drop a column from a table by using the ALTER TABLE statement with the DROP
COLUMN clause. This is a feature available in Oracle8i and later.
Guidelines
• The column may or may not contain data.
• Using the ALTER TABLE statement, only one column can be dropped at a time.
• The table must have at least one column remaining in it after it is altered.
• Once a column is dropped, it cannot be recovered.

SQL> ALTER TABLE EMP4


2 DROP COLUMN HIREDATE;

Table altered.

SQL> ALTER TABLE EMP4


2 DROP (COMM);

Table altered.

SQL> ALTER TABLE EMP4


2 DROP (DEPTNO, SALARY, NIC);

Table altered.

SQL> DESC EMP4


Name Null? Type
------------------------------- -------- ----
EMP_ID NUMBER(4)
EMP_NAME VARCHAR2(10)
JOB VARCHAR2(10)
137 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Dropping a Table

The DROP TABLE statement removes the definition of an Oracle table. When you drop a table,
the database loses all the data in the table and all the indexes associated with it.

SQL> DROP TABLE EMP1;

Table dropped.

Changing the Name of an Object

SQL> RENAME EMP2 TO EMP222;

Table renamed.

Truncating a Table

Another DDL statement is the TRUNCATE TABLE statement, which is used to remove all rows
from a table and to release the storage space used by that table. When using the TRUNCATE
TABLE statement, you cannot roll back row removal.

You must be the owner of the table or have DELETE TABLE system privileges to truncate a
table.

The DELETE statement can also remove all rows from a table, but it does not release storage
space. The TRUNCATE command is faster. Removing rows with the TRUNCATE statement is
faster than removing them with the DELETE statement for the following reasons:
• The TRUNCATE statement is a data definition language (DDL) statement and generates
no rollback information.
• Truncating a table does not fire the delete triggers of the table.
• If the table is the parent of a referential integrity constraint, you cannot truncate the
table. Disable the constraint before issuing the TRUNCATE statement.

SQL> SELECT COUNT(*) FROM EMP222;

COUNT(*)
---------
17

SQL> TRUNCATE TABLE EMP222;

Table truncated.

SQL> SELECT COUNT(*) FROM EMP222;

COUNT(*)
---------
0

138 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 10

Including Constraints
Constraints

The Oracle Server uses constraints to prevent invalid data entry into tables.
You can use constraints to do the following:
• Enforce rules on the data in a table whenever a row is inserted, updated, or deleted
from that table. The constraint must be satisfied for the operation to succeed.
• Prevent the deletion of a table if there are dependencies from other tables
• Provide rules for Oracle tools, such as Oracle Developer

Constraints are usually created at the same time as the table. Constraints can be added to a
table after its creation and also temporarily disabled.
Constraints can be defined at one of two levels.
• Column level constraint
• Table level constraint flevel

The NOT NULL constraint can be specified only at the column level, not at the table level.

The following constraint types are valid:


• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK

Constraint Guidelines

• Name a constraint or the Oracle server generates a name by using the SYS_Cn format.
• Create a constraint either:
– At the same time as the table is created, or
– After the table has been created
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.

Create DEPARTMENT table


Define constraints at column level
Do not provide constraint name because Oracle will provide constraints name
SQL> CREATE TABLE DEPARTMENT
2 (
3 DEPTNO NUMBER(2) PRIMARY KEY,
4 DNAME VARCHAR2(10) NOT NULL,
5 LOC VARCHAR2(10) DEFAULT 'KARACHI'
6 );

Table created.

139 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Inserting into DEPARTMENT table


SQL> INSERT INTO DEPARTMENT VALUES (1,'ADMIN','LAHORE');

1 row created.

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (2,'ACCOUNTS','LAHORE');

1 row created.

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (3,'IT',DEFAULT);

1 row created.

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME) VALUES (4,'AUDIT');

1 row created.

SQL> DESC DEPARTMENT


Name Null? Type
------------------------------- -------- ----
DEPTNO NOT NULL NUMBER(2)
DNAME NOT NULL VARCHAR2(10)
LOC VARCHAR2(10)

SQL> SELECT * FROM DEPARTMENT;

DEPTNO DNAME LOC


--------- ---------- ----------
1 ADMIN LAHORE
2 ACCOUNTS LAHORE
3 IT KARACHI
4 AUDIT KARACHI

Note the errors in the following queries and give the reason of errors

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (4,'PURCHASE','LAHORE');


INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (4,'PURCHASE','LAHORE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C0011127) violated

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES


(NULL,'PURCHASE','LAHORE');
INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (NULL,'PURCHASE','LAHORE')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."DEPARTMENT"."DEPTNO")

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (5,NULL,'LAHORE');


INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (5,NULL,'LAHORE')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."DEPARTMENT"."DNAME")

140 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Use the following data dictionary views for viewing constraints information

SQL> DESC USER_CONSTRAINTS


Name Null? Type
------------------------------- -------- ----
OWNER NOT NULL VARCHAR2(30)
CONSTRAINT_NAME NOT NULL VARCHAR2(30)
CONSTRAINT_TYPE VARCHAR2(1)
TABLE_NAME NOT NULL VARCHAR2(30)
SEARCH_CONDITION LONG
R_OWNER VARCHAR2(30)
R_CONSTRAINT_NAME VARCHAR2(30)
DELETE_RULE VARCHAR2(9)
STATUS VARCHAR2(8)
DEFERRABLE VARCHAR2(14)
DEFERRED VARCHAR2(9)
VALIDATED VARCHAR2(13)
GENERATED VARCHAR2(14)
BAD VARCHAR2(3)
RELY VARCHAR2(4)
LAST_CHANGE DATE
INDEX_OWNER VARCHAR2(30)
INDEX_NAME VARCHAR2(30)
INVALID VARCHAR2(7)
VIEW_RELATED VARCHAR2(14)

SQL> DESC USER_CONS_COLUMNS


Name Null? Type
------------------------------- -------- ----
OWNER NOT NULL VARCHAR2(30)
CONSTRAINT_NAME NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME VARCHAR2(4000)
POSITION NUMBER

View constraints information of DEPARTMENT table by using data dictionary views:

You can view constraints information by using user_constraints but you can not view the
column names for which constraints are used.

SQL> SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS
3 WHERE TABLE_NAME='DEPARTMENT';

CONSTRAINT_NAME C
------------------------------ -
SYS_C0011126 C
SYS_C0011127 P

You have to use user_cons_columns if you want to view column name for which constraints are
used but you can not view constraints type by user_cons_columns.

SQL> COL COLUMN_NAME FORMAT A15


SQL> SELECT CONSTRAINT_NAME, COLUMN_NAME, POSITION
2 FROM USER_CONS_COLUMNS
3 WHERE TABLE_NAME='DEPARTMENT';

CONSTRAINT_NAME COLUMN_NAME POSITION


------------------------------ --------------- ---------
SYS_C0011126 DNAME
SYS_C0011127 DEPTNO 1
141 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

If you want to view complete constraint information including constraints type and column
information then you have to join user_constraints and user_cons_columns.

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='DEPARTMENT';

CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
SYS_C0011126 DNAME C
SYS_C0011127 DEPTNO P

Create EMPLOYEE table


Define constraints at column level
Do not provide constraint name because Oracle will provide constraints name
SQL> CREATE TABLE EMPLOYEE
2 (
3 EMP_ID NUMBER(4) PRIMARY KEY,
4 FIRST_NAME VARCHAR2(10) NOT NULL,
5 LAST_NAME VARCHAR2(10),
6 JOIN_DATE DATE DEFAULT SYSDATE,
7 DESG VARCHAR2(20) DEFAULT 'CLERK',
8 SALARY NUMBER(7,2) CHECK (SALARY BETWEEN 500 AND 99999),
9 NIC VARCHAR2(20) UNIQUE,
10 DEPTNO NUMBER(02) REFERENCES DEPARTMENT (DEPTNO)
11 );

Table created.

SQL> DESC EMPLOYEE


Name Null? Type
------------------------------- -------- ----
EMP_ID NOT NULL NUMBER(4)
FIRST_NAME NOT NULL VARCHAR2(10)
LAST_NAME VARCHAR2(10)
JOIN_DATE DATE
DESG VARCHAR2(20)
SALARY NUMBER(7,2)
NIC VARCHAR2(20)
DEPTNO NUMBER(2)

View constraints information of EMPLOYEE table by using data dictionary views:

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE';

CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
SYS_C0011128 FIRST_NAME C
SYS_C0011129 SALARY C
SYS_C0011130 EMP_ID P
SYS_C0011131 NIC U
SYS_C0011132 DEPTNO R
142 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Create EMPLOYEE2 table with user defined constraint name


Define constraints at column level

SQL> CREATE TABLE EMPLOYEE2


2 (
3 EMP_ID NUMBER(4) CONSTRAINT EMPLOYEE2_EMP_ID_PK PRIMARY KEY,
4 FIRST_NAME VARCHAR2(10) CONSTRAINT EMPLOYEE2_FIRSTNAME_NN NOT NULL,
5 LAST_NAME VARCHAR2(10),
6 JOIN_DATE DATE DEFAULT SYSDATE,
7 DESG VARCHAR2(20) DEFAULT 'CLERK',
8 SALARY NUMBER(7,2)
9 CONSTRAINT EMPLOYEE2_SALARY_C CHECK (SALARY BETWEEN 500 AND 99999),
10 NIC VARCHAR2(20) CONSTRAINT EMPLOYEE2_NIC_U UNIQUE,
11 DEPTNO NUMBER(02)
12 CONSTRAINT EMPLOYEE2_DEPTNO_FK REFERENCES DEPARTMENT (DEPTNO)
13 );

Table created.

View constraints information of EMPLOYEE2 table by using data dictionary views:

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE2';

CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
EMPLOYEE2_FIRSTNAME_NN FIRST_NAME C
EMPLOYEE2_SALARY_C SALARY C
EMPLOYEE2_EMP_ID_PK EMP_ID P
EMPLOYEE2_NIC_U NIC U
EMPLOYEE2_DEPTNO_FK DEPTNO R

Inserting into EMPLOYEE2 table


SQL> INSERT INTO EMPLOYEE2
2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (1,'MUHAMMAD','RAHEEM',DEFAULT,'SOFTWARE ENGINEER',50000,'12345-1234567-
1',3);

1 row created.

Note the errors in the following queries and give the reason of errors
SQL> INSERT INTO EMPLOYEE2
2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (1,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,NULL,3);
INSERT INTO EMPLOYEE2
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.EMPLOYEE2_EMP_ID_PK) violated

143 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> INSERT INTO EMPLOYEE2


2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (2,NULL,'ASLAM',DEFAULT,DEFAULT,40000,NULL,3);
(2,NULL,'ASLAM',DEFAULT,DEFAULT,40000,NULL,3)
*
ERROR at line 4:
ORA-01400: cannot insert NULL into ("SCOTT"."EMPLOYEE2"."FIRST_NAME")

SQL> INSERT INTO EMPLOYEE2


2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,400,NULL,3);
INSERT INTO EMPLOYEE2
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.EMPLOYEE2_SALARY_C) violated

SQL> INSERT INTO EMPLOYEE2


2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,'12345-1234567-1',3);
INSERT INTO EMPLOYEE2
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.EMPLOYEE2_NIC_U) violated

SQL> INSERT INTO EMPLOYEE2


2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,NULL,5);
INSERT INTO EMPLOYEE2
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.EMPLOYEE2_DEPTNO_FK) violated - parent
key not found

SQL> INSERT INTO EMPLOYEE2


2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO)
3 VALUES
4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,NULL,1);

1 row created.

SQL> SELECT EMP_ID, JOIN_DATE, DESG, SALARY, NIC, DEPTNO FROM EMPLOYEE2;

EMP_ID JOIN_DATE DESG SALARY NIC DEPTNO


--------- --------- ----------------- --------- --------------- ---------
1 06-AUG-08 SOFTWARE ENGINEER 50000 12345-1234567-1 3
2 06-AUG-08 CLERK 40000 1

SQL>

144 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Create EMPLOYEE3 table with user defined constraint name


Define constraints at table level

SQL> CREATE TABLE EMPLOYEE3


2 (
3 EMP_ID NUMBER(4),
4 FIRST_NAME VARCHAR2(10) CONSTRAINT EMPLOYEE3_FIRSTNAME_NN NOT NULL,
5 LAST_NAME VARCHAR2(10),
6 JOIN_DATE DATE DEFAULT SYSDATE,
7 DESG VARCHAR2(20) DEFAULT 'CLERK',
8 SALARY NUMBER(7,2),
9 NIC VARCHAR2(20),
10 DEPTNO NUMBER(02),
11 CONSTRAINT EMPLOYEE3_EMP_ID_PK PRIMARY KEY (EMP_ID),
12 CONSTRAINT EMPLOYEE3_SALARY_C CHECK (SALARY BETWEEN 500 AND 99999),
13 CONSTRAINT EMPLOYEE3_NIC_U UNIQUE (NIC),
14 CONSTRAINT EMPLOYEE3_DEPTNO_FK FOREIGN KEY (DEPTNO)
15 REFERENCES DEPARTMENT (DEPTNO)
16 );

Table created.

View constraints information of EMPLOYEE3 table by using data dictionary views:

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE3';

CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
EMPLOYEE3_FIRSTNAME_NN FIRST_NAME C
EMPLOYEE3_SALARY_C SALARY C
EMPLOYEE3_EMP_ID_PK EMP_ID P
EMPLOYEE3_NIC_U NIC U
EMPLOYEE3_DEPTNO_FK DEPTNO R

Dropping a Constraint

To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS and
USER_CONS_COLUMNS data dictionary views. Then use the ALTER TABLE statement with the
DROP clause. The CASCADE option of the DROP clause causes any dependent constraints also
to be dropped.

SQL> ALTER TABLE EMPLOYEE3


2 DROP CONSTRAINT EMPLOYEE3_NIC_U;

Table altered.

SQL> ALTER TABLE EMPLOYEE3


2 DROP CONSTRAINT EMPLOYEE3_FIRSTNAME_NN;

Table altered.

SQL> ALTER TABLE EMPLOYEE3


2 DROP CONSTRAINT EMPLOYEE3_DEPTNO_FK;

145 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

View constraints information of EMPLOYEE3 table after dropping EMPLOYEE3_NIC_U


and EMPLOYEE3_FIRSTNAME_NN;

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE3';

CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
EMPLOYEE3_SALARY_C SALARY C
EMPLOYEE3_EMP_ID_PK EMP_ID P

Adding a Constraint
You can add a constraint for existing tables by using the ALTER TABLE statement with the ADD
clause.

SQL> ALTER TABLE EMPLOYEE3


2 ADD CONSTRAINT EMP3_NIC_U UNIQUE (NIC);

Table altered.

SQL> ALTER TABLE EMPLOYEE3


2 ADD CONSTRAINT EMP3_DEPTNO_FK FOREIGN KEY (DEPTNO)
3 REFERENCES DEPARTMENT (DEPTNO);

Table altered.

SQL> ALTER TABLE EMPLOYEE3


2 MODIFY FIRST_NAME CONSTRAINT EMP3_FIRSTNAME_NN NOT NULL;

Table altered.

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE3';

CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
EMP3_NIC_U NIC U
EMPLOYEE3_SALARY_C SALARY C
EMPLOYEE3_EMP_ID_PK EMP_ID P
EMP3_DEPTNO_FK DEPTNO R
EMP3_FIRSTNAME_NN FIRST_NAME C

SQL> ALTER TABLE EMPLOYEE3


2 DROP CONSTRAINT EMPLOYEE3_SALARY_C;

Table altered.

SQL> ALTER TABLE EMPLOYEE3

146 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
2 DROP CONSTRAINT EMPLOYEE3_EMP_ID_PK;

Disabling Constraints

You can disable a constraint without dropping it or re-creating it by using the ALTER TABLE
statement with the DISABLE clause.

SQL> ALTER TABLE EMPLOYEE3


2 DISABLE CONSTRAINT EMP3_NIC_U;

Table altered.

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE, T.STATUS


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE3';

CONSTRAINT_NAME COLUMN_NAME C STATUS


------------------------------ --------------- - --------
EMP3_NIC_U NIC U DISABLED
EMP3_DEPTNO_FK DEPTNO R ENABLED
EMP3_FIRSTNAME_NN FIRST_NAME C ENABLED

Enabling Constraints

You can enable a constraint without dropping it or re-creating it by using the ALTER TABLE
statement with the ENABLE clause.

SQL> ALTER TABLE EMPLOYEE3


2 ENABLE CONSTRAINT EMP3_NIC_U;

Table altered.

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE, T.STATUS


2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C
3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND
4 C.TABLE_NAME=T.TABLE_NAME AND
5 T.TABLE_NAME='EMPLOYEE3';

CONSTRAINT_NAME COLUMN_NAME C STATUS


------------------------------ --------------- - --------
EMP3_NIC_U NIC U ENABLED
EMP3_DEPTNO_FK DEPTNO R ENABLED
EMP3_FIRSTNAME_NN FIRST_NAME C ENABLED

Cascading Constraints
SQL> ALTER TABLE DEPARTMENT
2 DROP (DEPTNO);
DROP (DEPTNO)
*
ERROR at line 2:
ORA-12992: cannot drop parent key column

SQL> ALTER TABLE DEPARTMENT


2 DROP (DEPTNO) CASCADE CONSTRAINT;

Table altered.

147 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 11
Creating Views
You can present logical subsets or combinations of data by creating views of tables. A view is a
logical table based on a table or another view. A view contains no data of its own but is like a
window through which data from tables can be viewed or changed. The tables on which a view
is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.

Advantages of Views
• Views restrict access to the data because the view can display selective columns from
the table.
• Views can be used to make simple queries to retrieve the results of complicated queries.
For example, views can be used to query information from multiple tables without the
user knowing how to write a join statement.
• Views provide data independence for ad hoc users and application programs. One view
can be used to retrieve data from several tables.
• Views provide groups of users access to data according to their particular criteria.

Simple Views versus Complex Views

There are two classifications for views: simple and complex. The basic difference is related to
the DML (INSERT, UPDATE, and DELETE) operations.
• A simple view is one that:
• Derives data from only one table
• Contains no functions or groups of data
• Can perform DML operations through the view
• A complex view is one that:
• Derives data from many tables
• Contains functions or groups of data
• Does not always allow DML operations through the view

The following query will create a view based on EMP table having only six columns. The view is
created for restricting users from view salary and commission information.

The CREATE VIEW statement


SQL> CREATE VIEW EMP_V1
2 AS SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, DEPTNO FROM EMP;

View created.

Display structure of a view

SQL> DESC EMP_V1


Name Null? Type
------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
DEPTNO NUMBER(2)

148 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Retrieving data using view


SQL> SELECT * FROM EMP_V1;
EMPNO ENAME JOB MGR HIREDATE DEPTNO
--------- ---------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 20
7499 ALLEN SALESMAN 7698 20-FEB-81 30
7521 WARD SALESMAN 7698 22-FEB-81 30
7566 JONES MANAGER 7839 02-APR-81 20
7654 MARTIN SALESMAN 7698 28-SEP-81 30
7698 BLAKE MANAGER 7839 01-MAY-81 30
7782 CLARK MANAGER 7839 09-JUN-81 10
7788 SCOTT ANALYST 7566 19-APR-87 20
7839 KING PRESIDENT 17-NOV-81 10
7844 TURNER SALESMAN 7698 08-SEP-81 30
7876 ADAMS CLERK 7788 23-MAY-87 20
7900 JAMES CLERK 7698 03-DEC-81 30
7902 FORD ANALYST 7566 03-DEC-81 20
7934 MILLER CLERK 7782 23-JAN-82 10
1 SCOTT CLERK 2 06-AUG-08 55
2 ASLAM MANAGER 7839 28-JUL-08 55
3 SALEEM ASST IT 2 10-JAN-07 55

17 rows selected.

Inserting using view

SQL> INSERT INTO EMP_V1


2 (EMPNO, ENAME, JOB, DEPTNO)
3 VALUES
4 (4, 'ZIA','CLERK',10);

1 row created.

You inserted into EMP table through EMP_V1

SQL> SELECT * FROM EMP;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
4 ZIA CLERK 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 SCOTT CLERK 2 06-AUG-08 1000 55
2 ASLAM MANAGER 7839 28-JUL-08 2975 55
3 SALEEM ASST IT 2 10-JAN-07 2300 55
18 rows selected.
149 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Modifying a View

With the OR REPLACE option, a view can be created even if one exists with this name already, thus
replacing the old version of the view for its owner. This means that the view can be altered without
dropping, re-creating, and regranting object privileges.

The following view has been creating to view employee department # 10.

SQL> CREATE OR REPLACE VIEW EMP_VIEW_D10


2 AS SELECT * FROM EMP WHERE DEPTNO=10;
View created.

SQL> DESC EMP_VIEW_D10


Name Null? Type
------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

SQL> SELECT * FROM EMP_VIEW_D10;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

You can add an alias for each column name.

SQL> CREATE OR REPLACE VIEW EMP_V2


2 (EMP_ID, EMP_NAME, DESG, SALARY, DEPT_ID) AS
3 SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
4 FROM EMP WHERE SAL>2000;
View created.

SQL> DESC EMP_V2


Name Null? Type
------------------------------- -------- ----
EMP_ID NOT NULL NUMBER(4)
EMP_NAME VARCHAR2(10)
DESG VARCHAR2(9)
SALARY NUMBER(7,2)
DEPT_ID NUMBER(2)

SQL> SELECT * FROM EMP_V2;

EMP_ID EMP_NAME DESG SALARY DEPT_ID


--------- ---------- ----------------- --------- ---------
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7782 CLARK MANAGER 2450 10
7788 SCOTT ANALYST 3000 20
7839 KING PRESIDENT 5000 10
7902 FORD ANALYST 3000 20
2 ASLAM MANAGER 2975 55
3 SALEEM ASST IT 2300 55
8 rows selected.

150 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Creating a Complex View


Create a complex view that contains display values from two tables.

SQL> CREATE OR REPLACE VIEW EMP_DEPT AS


2 SELECT E.EMPNO, E.ENAME, E.JOB, E.DEPTNO, D.DNAME, D.LOC
3 FROM EMP E, DEPT D
4 WHERE E.DEPTNO=D.DEPTNO;
View created.

SQL> SELECT * FROM EMP_DEPT;


EMPNO ENAME JOB DEPTNO DNAME LOC
--------- ---------- --------- --------- -------------- -------------
7369 SMITH CLERK 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 30 SALES CHICAGO
7521 WARD SALESMAN 30 SALES CHICAGO
7566 JONES MANAGER 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 30 SALES CHICAGO
7698 BLAKE MANAGER 30 SALES CHICAGO
7782 CLARK MANAGER 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 20 RESEARCH DALLAS
7839 KING PRESIDENT 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 30 SALES CHICAGO
7876 ADAMS CLERK 20 RESEARCH DALLAS
7900 JAMES CLERK 30 SALES CHICAGO
7902 FORD ANALYST 20 RESEARCH DALLAS
4 ZIA CLERK 10 ACCOUNTING NEW YORK
7934 MILLER CLERK 10 ACCOUNTING NEW YORK
1 SCOTT CLERK 55 IT KARACHI
2 ASLAM MANAGER 55 IT KARACHI
3 SALEEM ASST IT 55 IT KARACHI
18 rows selected.

Create a complex view that contains group functions to display summary information.

SQL> CREATE OR REPLACE VIEW DEPT_SUMMARY AS


2 SELECT DEPTNO, COUNT(*) CNT, SUM(SAL) SUM_SAL, AVG(SAL) AVG_SAL
3 FROM EMP
4 GROUP BY DEPTNO;

View created.

SQL> SELECT * FROM DEPT_SUMMARY;

DEPTNO CNT SUM_SAL AVG_SAL


--------- --------- --------- ---------
30 6 9400 1566.6667
20 5 10875 2175
55 3 6275 2091.6667
10 4 8750 2916.6667

SQL> CREATE OR REPLACE VIEW AVAILABLE_JOBS AS


2 SELECT DISTINCT JOB FROM EMP;
View created.

SQL> SELECT * FROM AVAILABLE_JOBS;


JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST

151 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
ASST IT

Removing a View

You use the DROP VIEW statement to remove a view. The statement removes the view
definition from the database. Dropping views has no effect on the tables on which the view was
based. Views or other applications based on deleted views become invalid.

SQL> DROP VIEW EMP_V1;

View dropped.

Inline Views

• An inline view is a subquery with an alias (or correlation name) that you can use within
a SQL statement.
• A named subquery in the FROM clause of the main query is an example of an inline
view.
• An inline view is not a schema object.

SQL> SELECT EMP_ID, EMP_NAME, DESG


2 FROM (SELECT EMPNO EMP_ID, ENAME EMP_NAME, JOB DESG
3 FROM EMP WHERE DEPTNO=10) A;

EMP_ID EMP_NAME DESG


--------- ---------- -----------------
7782 CLARK MANAGER
7839 KING PRESIDENT
4 ZIA CLERK
7934 MILLER CLERK

Top-N Analysis

• Top-N queries ask for the n largest or smallest values of a column. For example:
– What are the ten best selling products?
– What are the ten worst selling products?
• Both largest values and smallest values sets are considered Top-N queries.

To display the top three earner names and salaries from the EMP table:

SQL> SELECT ROWNUM SNO, ENAME, SAL, DEPTNO


2 FROM ( SELECT ENAME, SAL, DEPTNO
3 FROM EMP WHERE SAL IS NOT NULL
4 ORDER BY SAL DESC )
5 WHERE ROWNUM <= 3;

SNO ENAME SAL DEPTNO


--------- ---------- --------- ---------
1 KING 5000 10
2 SCOTT 3000 20
3 FORD 3000 20

NOTE: Use USER_VIEWS data dictionary to display created view information

152 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Chapter 12
Other Database Objects
Sequence

A sequence:
• Automatically generates unique numbers
• Is a sharable object
• Is typically used to create a primary key value
• Replaces application code

Create a sequence S1 with default options


SQL> CREATE SEQUENCE S1;

Sequence created.

Using a Sequence

After you create your sequence, it generates sequential numbers for use in your tables.
Reference the sequence values by using the NEXTVAL and CURRVAL pseudocolumns.

NEXTVAL and CURRVAL Pseudocolumns

• NEXTVAL returns the next available sequence value. It returns a unique value every
time it is referenced, even for different users.
• CURRVAL obtains the current sequence value.

SQL> SELECT S1.NEXTVAL FROM DUAL;

NEXTVAL
---------
1

SQL> SELECT S1.NEXTVAL FROM DUAL;

NEXTVAL
---------
2

SQL> SELECT S1.CURRVAL FROM DUAL;

CURRVAL
---------
2

SQL> SELECT S1.NEXTVAL FROM DUAL;

NEXTVAL
---------
3

153 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SQL> CREATE SEQUENCE S2


2 START WITH 10
3 INCREMENT BY 2
4 MAXVALUE 15;

Sequence created.

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
10

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
12

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
14

SQL> SELECT S2.NEXTVAL FROM DUAL;


SELECT S2.NEXTVAL FROM DUAL
*
ERROR at line 1:
ORA-08004: sequence S2.NEXTVAL exceeds MAXVALUE and cannot be instantiated

SQL> SELECT S2.CURRVAL FROM DUAL;

CURRVAL
---------
14

Confirming Sequences

Once you have created your sequence, it is documented in the data dictionary. Since a
sequence is a database object, you can identify it in the USER_OBJECTS data dictionary table.
You can also confirm the settings of the sequence by selecting from the USER_SEQUENCES
data dictionary view.

SQL> SELECT SEQUENCE_NAME, MIN_VALUE, INCREMENT_BY, LAST_NUMBER


FROM USER_SEQUENCES;

SEQUENCE_NAME MIN_VALUE INCREMENT_BY LAST_NUMBER


------------------------------ --------- ------------ -----------
S1 1 1 21
S2 1 2 16

154 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Modifying a Sequence

Altering a Sequence

If you reach the MAXVALUE limit for your sequence, no additional values from the sequence are
allocated and you will receive an error indicating that the sequence exceeds the MAXVALUE. To
continue to use the sequence, you can modify it by using the ALTER SEQUENCE statement.

SQL> ALTER SEQUENCE S2 MAXVALUE 100;

Sequence altered.

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
16

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
18

Guidelines for Modifying Sequences


• You must be the owner or have the ALTER privilege for the sequence in order to modify
it.
• Only future sequence numbers are affected by the ALTER SEQUENCE statement.
• The START WITH option cannot be changed using ALTER SEQUENCE. The sequence must
be dropped and re-created in order to restart the sequence at a different number.
• Some validation is performed. For example, a new MAXVALUE that is less than the
current sequence number cannot be imposed.

SQL> ALTER SEQUENCE S2


2 MAXVALUE 5000
3 INCREMENT BY 5
4 CYCLE;

Sequence altered.

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
23

SQL> ALTER SEQUENCE S2 NOCYCLE;

Sequence altered.

CYCLE | NOCYCLE specifies whether the sequence continues to generate values after reaching its maximum or
minimum value (NOCYCLE is the default option.)

SQL> ALTER SEQUENCE S2 INCREMENT BY -5 MINVALUE 1 CYCLE;

Sequence altered.

SQL> SELECT S2.NEXTVAL FROM DUAL;

NEXTVAL
---------
155 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
18

Using a Sequence
SQL> CREATE SEQUENCE S3 MAXVALUE 9;

Sequence created.

SQL> INSERT INTO DEPT


2 (DEPTNO, DNAME, LOC)
3 VALUES
4 (S3.NEXTVAL, 'MAINTENANCE','KARACHI');

1 row created.

SQL> /

1 row created.

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
1 MAINTENANCE KARACHI
2 MAINTENANCE KARACHI
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
55 IT KARACHI
60 PURCHASE
65 AUDIT

9 rows selected.

SQL> ROLLBACK;

Rollback complete.

SQL> CREATE SEQUENCE S4;

Sequence created.

SQL> ALTER TABLE EMP ADD SNO NUMBER(4);

Table altered.

SQL> UPDATE EMP SET SNO=S4.NEXTVAL WHERE DEPTNO=10;

4 rows updated.

SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, SNO FROM EMP WHERE DEPTNO=10;

EMPNO ENAME JOB SAL DEPTNO SNO


--------- ---------- --------- --------- --------- ---------
7782 CLARK MANAGER 2450 10 1
7839 KING PRESIDENT 5000 10 2
4 ZIA CLERK 10 3
7934 MILLER CLERK 1300 10 4

SQL> ALTER TABLE EMP DROP COLUMN SNO;

156 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Table altered.

SQL> CREATE TABLE EMP_SEQ


2 AS
3 SELECT S5.NEXTVAL EMPNO, ENAME, JOB, SAL, DEPTNO
4 FROM EMP;

Table created.

SQL> SELECT * FROM EMP_SEQ;

EMPNO ENAME JOB SAL DEPTNO


--------- ---------- --------- --------- ---------
1 SMITH CLERK 800 20
2 ALLEN SALESMAN 1600 30
3 WARD SALESMAN 1250 30
4 JONES MANAGER 2975 20
5 MARTIN SALESMAN 1250 30
6 BLAKE MANAGER 2850 30
7 CLARK MANAGER 2450 10
8 SCOTT ANALYST 3000 20
9 KING PRESIDENT 5000 10
10 TURNER SALESMAN 1500 30
11 ADAMS CLERK 1100 20
12 JAMES CLERK 950 30
13 FORD ANALYST 3000 20
14 ZIA CLERK 10
15 MILLER CLERK 1300 10
16 SCOTT CLERK 1000 55
17 ASLAM MANAGER 2975 55
18 SALEEM ASST IT 2300 55

18 rows selected.

SQL> INSERT INTO EMP_SEQ VALUES (S5.NEXTVAL, 'WAQAS','SYS. ADM',35000,10);

1 row created.

SQL> SELECT * FROM EMP_SEQ WHERE ENAME='WAQAS';

EMPNO ENAME JOB SAL DEPTNO


--------- ---------- --------- --------- ---------
19 WAQAS SYS. ADM 35000 10

Gaps in the Sequence

Although sequence generators issue sequential numbers without gaps, this action occurs
independent of a commit or rollback. Therefore, if you roll back a statement containing a
sequence, the number is lost.

Another event that can cause gaps in the sequence is a system crash. If the sequence caches
values in the memory, then those values are lost if the system crashes.

Because sequences are not tied directly to tables, the same sequence can be used for multiple
tables. If you do so, each table can contain gaps in the sequential numbers.

Removing a Sequence

SQL> DROP SEQUENCE S5;

157 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Sequence dropped.

Index

An Oracle server index is a schema object that can speed up the retrieval of rows by using a
pointer. Indexes can be created explicitly or automatically. If you do not have an index on the
column, then a full table scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is to reduce the
necessity of disk I/O by using an indexed path to locate data quickly. The index is used and
maintained automatically by the Oracle server. Once an index is created, no direct activity is
required by the user.
Indexes are logically and physically independent of the table they index. This means that they
can be created or dropped at any time and have no effect on the base tables or other indexes.
Note: When you drop a table, corresponding indexes are also dropped.

Types of Indexes
• Automatically:
A unique index is created automatically when you define a PRIMARY KEY or UNIQUE
constraint in a table definition.
• Manually:
Users can create nonunique indexes on columns to speed up access to the rows.

Note: You can manually create a unique index, but it is recommended that you create a unique
constraint, which implicitly creates a unique index.

Creating an Index

Create an index on one or more columns by issuing the CREATE INDEX statement.

Automatically index creation:


Add a new column NIC in EMP table,
Add a unique constraint on NIC column
Unique index will be created automatically

SQL> ALTER TABLE EMP


2 ADD NIC VARCHAR2(15) CONSTRAINT EMP_NIC_U UNIQUE;

Table altered.

Manually index creation:

Create an index on ENAME to improve the speed of query access to the ENAME column in the
EMP table.

SQL> CREATE INDEX INDX_EMP_ENAME


2 ON EMP (ENAME);

Index created.

Create an index on SAL, COMM to improve the speed of query access.

SQL> CREATE INDEX INDX_EMP_SAL_COMM


2 ON EMP (SAL,COMM);

158 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Index created.

Confirming Indexes

Confirm the existence of indexes from the USER_INDEXES data dictionary view.

SQL> SELECT INDEX_NAME, INDEX_TYPE, UNIQUENESS


2 FROM USER_INDEXES WHERE TABLE_NAME='EMP';

INDEX_NAME INDEX_TYPE UNIQUENES


------------------------------ --------------------------- ---------
PK_EMP NORMAL UNIQUE
INDX_EMP_ENAME NORMAL NONUNIQUE
EMP_NIC_U NORMAL UNIQUE
INDX_EMP_SAL_COMM NORMAL NONUNIQUE

You can also check the columns involved in an index by querying the USER_IND_COLUMNS
view.

SQL> COL COLUMN_NAME FORMAT A15


SQL> SELECT INDEX_NAME, COLUMN_NAME, COLUMN_POSITION
2 FROM USER_IND_COLUMNS WHERE TABLE_NAME='EMP';

INDEX_NAME COLUMN_NAME COLUMN_POSITION


------------------------------ --------------- ---------------
PK_EMP EMPNO 1
INDX_EMP_ENAME ENAME 1
EMP_NIC_U NIC 1
INDX_EMP_SAL_COMM SAL 1
INDX_EMP_SAL_COMM COMM 2

I want to retrieve index information in one query from the above data dictionary.

SQL> SELECT T.INDEX_NAME, C.COLUMN_NAME, C.COLUMN_POSITION, T.UNIQUENESS


2 FROM USER_INDEXES T, USER_IND_COLUMNS C
3 WHERE T.INDEX_NAME=C.INDEX_NAME AND
4 T.TABLE_NAME=C.TABLE_NAME AND
5 T.TABLE_NAME='EMP';

INDEX_NAME COLUMN_NAME COLUMN_POSITION UNIQUENES


-------------------- --------------- --------------- ---------
PK_EMP EMPNO 1 UNIQUE
INDX_EMP_ENAME ENAME 1 NONUNIQUE
EMP_NIC_U NIC 1 UNIQUE
INDX_EMP_SAL_COMM SAL 1 NONUNIQUE
INDX_EMP_SAL_COMM COMM 2 NONUNIQUE

Creating unique index

SQL> CREATE UNIQUE INDEX INDX_NIC


2 ON EMP (NIC);
ON EMP (NIC)
*
ERROR at line 2:
ORA-01408: such column list already indexed
159 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Function-Based Indexes

• A function-based index is an index based on expressions.


• The index expression is built from table columns, constants, SQL functions, and user-
defined functions.

SQL> CREATE INDEX INDX_EMP_UPPER


2 ON EMP (UPPER(ENAME));

Index created.

SQL> UPDATE EMP SET ENAME=LOWER(ENAME);

18 rows updated.

SQL> SELECT * FROM EMP WHERE UPPER(ENAME)='SMITH';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7369 smith CLERK 7902 17-DEC-80 800 20

Removing an Index

You cannot modify indexes. To change an index, you must drop it and then re-create it.
Remove an index definition from the data dictionary by issuing the DROP INDEX statement. To
drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.

SQL> DROP INDEX INDX_EMP_UPPER;

Index dropped.

When to Create an Index

You should create an index if:


• A column contains a wide range of values
• A column contains a large number of null values
• One or more columns are frequently used together in a WHERE clause or a join condition
• The table is large and most queries are expected to retrieve less than 2 to 4 percent of
the rows

When Not to Create an Index

It is usually not worth creating an index if:


• The table is small
• The columns are not often used as a condition in the query
• Most queries are expected to retrieve more than 2 to 4 percent of the rows in the table
• The table is updated frequently
• The indexed columns are referenced as part of an expression

160 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Synonyms

Simplify access to objects by creating a synonym


(another name for an object). With synonyms, you can:
• Ease referring to a table owned by another user
• Shorten lengthy object names

SQL> SELECT * FROM E;


SELECT * FROM E
*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> CREATE SYNONYM E


2 FOR EMP;

Synonym created.

SQL> SELECT * FROM E WHERE DEPTNO=10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- ---------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
4 ZIA CLERK 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10

If you want to access objects of another user you may get error

MEASURE is a table and it is owned by INVENTORY user. but the following is


applied from SCOTT user.

SQL> DESC MEASURE


ERROR:
ORA-04043: object MEASURE does not exist

SQL> SELECT * FROM MEASURE;


SELECT * FROM MEASURE
*
ERROR at line 1:
ORA-00942: table or view does not exist

How to access object of other user

SQL> SELECT * FROM INVENTORY.MEASURE;

MEASURE_ID MEASURE_DESC
---------- ----------------------------------------
BAGS BAGS
CAN
DRUM
JAR
COTTON

161 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

You can create synonym for accessing objects of other user


For example
SCOTT is a user from where I want to access objects of INVENTORY user. I will create a
synonym in SCOTT user.

SQL> SHOW USER


USER is "SCOTT"
SQL>

SQL> CREATE SYNONYM MSR


2 FOR INVENTORY.MEASURE;

Synonym created.

SQL> CREATE SYNONYM MEASURE


2 FOR INVENTORY.MEASURE;

Synonym created.

Now you can use MEASURE or MSR synonym from SCOTT user.
SQL> DESC MSR
Name Null? Type
------------------------------- -------- ----
MEASURE_ID NOT NULL VARCHAR2(10)
MEASURE_DESC VARCHAR2(40)

SQL> DESC MEASURE


Name Null? Type
------------------------------- -------- ----
MEASURE_ID NOT NULL VARCHAR2(10)
MEASURE_DESC VARCHAR2(40)

View Synonym information by using USER_SYNONYMS


SQL> SELECT SYNONYM_NAME, TABLE_OWNER, TABLE_NAME FROM USER_SYNONYMS;

SYNONYM_NAME TABLE_OWNER TABLE_NAME


------------------------------ ------------------------------ ----------------
E SCOTT EMP
MSR INVENTORY MEASURE
MEASURE INVENTORY MEASURE

You can also user USER_OBJECTS


COL OBJECT_NAME FORMAT A15
SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE='SYNONYM';

OBJECT_NAME
---------------
MSR
E
MEASURE

Removing a Synonym
To drop a synonym, use the DROP SYNONYM statement. Only the database administrator can drop a
public synonym

SQL> DROP SYNONYM MSR;

162 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Synonym dropped.

Chapter 13
Controlling User Access
Users in Oracle
In Oracle terminology, a user is someone who can connect to a database (if granted enough
privileges) and optionally (again, if granted the appropriate privileges) can own objects (such
as tables) in the database.

The objects a user owns are collectively called schema. A schema, on its part, is always bound
to exactly one user. Because there is obviously a 1 to 1 relationship between a user and a
schema, these two terms are often used interchangeable.

In order to find out what users are created on the database, one can use DBA_USERS.

Database rights (Privileges)


Users can be assigned rights what they're allowed to do in a database and what not. These
rights are called privileges.

Privileges
A privilege is a right to execute an SQL statement or to access another user's object.
In Oracle, there are two types of privileges:
• System privileges
• Object privileges.

A privilege can be assigned to a user or a privilege.

The set of privileges is fixed, that is, there is no SQL statement like create privilege xyz...

System privileges

Once a user is created, the DBA can grant specific system privileges to a user.

There are quite a few system privileges:


in Oracle 9.2, we count 157 of them, and 10g has even 173. Those can be displayed with:

SQL> SELECT NAME FROM SYSTEM_PRIVILEGE_MAP

Executing this statement, we find privileges like create session, drop user, alter database.

Arguably, the most important system privileges are:


• CREATE SESSION
(A user cannot login without this privilege. If he tries, he gets an ORA-01045).
• CREATE TABLE
• CREATE VIEW
• CREATE PROCEDURE
• SYSDBA
• SYSOPER

System privileges can be displayed using USER_SYS_PRIVS data dictionary view

163 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Object privileges

An object privilege is a privilege or right to perform a particular action on a specific object


(table, view, sequence, or procedure ect.) Each object has a particular set of grantable
privileges.

Some objects privileges are:

• Tables (SELECT, INSERT, UPDATE, DELETE, ALTER etc.)


• Views (SELECT, INSERT, UPDATE, DELETE etc.)
• Sequence (ALTER, SELECT)
• Packeges, Procedures, Functions (EXECUTE, DEBUG)
• Directories (READ, WRITE )
• …

For a user to be able to access an object in another user's schema, he needs the according
object privilege.

Object privileges can be displayed using all_tab_privs_made or user_tab_privs_made.

Public

If a privilege is granted to the special role public, this privilege can be executed by all other
users. However, sysdba cannot be granted to public.

Role

A role is a named group of related privileges that can be granted to the user. This method
makes it easier to revoke and maintain privileges.

A user can have access to several roles, and several users can be assigned the same role. Roles
are typically created for a database application.

Predefined Roles

Along with the installation, more exactly with the creation of an oracle database, Oracle creates
predefined roles. These are:
• connect, resource, dba
These might not be created anymore in future versions of Oracle.

Oracle 9.2 grants create session, alter session, create synonym, create view, create
database link, create table, create cluster and create sequence to connect.

It also grants create table, create cluster, create sequence, create trigger create procedure,
create type, create indextype and create operator to resource.

The role dba gets basically everything and that with admin option.

164 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Creating user

The DBA creates the user by executing the CREATE USER statement. The user does not have
any privileges at this point. The DBA can then grant privileges to that user. These privileges
determine what the user can do at the database level.

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.
SQL>

SQL> SHOW USER


USER is "SYS"
SQL>

SQL> CREATE USER MRAHEEM IDENTIFIED BY MCS298;

User created.

The user does not have any privileges at this point. The DBA can then grant privileges to that
user. These privileges determine what the user can do at the database level.

SQL> CONN MRAHEEM/MCS298


ERROR:
ORA-01045: user MRAHEEM lacks CREATE SESSION privilege; logon denied

Warning: You are no longer connected to ORACLE.


SQL>

Granting System Privileges

The DBA uses the GRANT statement to allocate system privileges to the user or role. Once the
user has been granted the privileges, the user can immediately use those privileges.

In the example, user mraheem has been assigned the privileges to create sessions, tables,
sequences, and views.

SQL> GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE VIEW
2 TO MRAHEEM;

Grant succeeded.

SQL> CONN MRAHEEM/MCS298


Connected.

Confirming system privileges granted to the user


SQL> SELECT * FROM USER_SYS_PRIVS;

USERNAME PRIVILEGE ADM


------------------------------ ---------------------------------------- ---
MRAHEEM CREATE VIEW NO
MRAHEEM CREATE TABLE NO
MRAHEEM CREATE SESSION NO
MRAHEEM CREATE SEQUENCE NO

165 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>

SQL> DESC USER_USERS


Name Null? Type
----------------------------------------- -------- ----------------------------
USERNAME NOT NULL VARCHAR2(30)
USER_ID NOT NULL NUMBER
ACCOUNT_STATUS NOT NULL VARCHAR2(32)
LOCK_DATE DATE
EXPIRY_DATE DATE
DEFAULT_TABLESPACE NOT NULL VARCHAR2(30)
TEMPORARY_TABLESPACE NOT NULL VARCHAR2(30)
CREATED NOT NULL DATE
INITIAL_RSRC_CONSUMER_GROUP VARCHAR2(30)
EXTERNAL_NAME VARCHAR2(4000)

SQL> COL USERNAME FORMAT A10


SQL> COL ACCOUNT_STATUS FORMAT A10
SQL> COL DEFAULT_TABLESPACE FORMAT A10
SQL> COL TEMPORARY_TABLESPACE FORMAT A10

SQL> SELECT USERNAME, ACCOUNT_STATUS, DEFAULT_TABLESPACE,


2 TEMPORARY_TABLESPACE, CREATED FROM USER_USERS;

USERNAME ACCOUNT_ST DEFAULT_TA TEMPORARY_ CREATED


---------- ---------- ---------- ---------- ---------
MRAHEEM OPEN USERS TEMP 07-AUG-08

SQL> CREATE TABLE EMPLOYEE


2 (
3 EMPNO NUMBER(4) PRIMARY KEY,
4 ENAME VARCHAR2(20)
5 );
CREATE TABLE EMPLOYEE
*
ERROR at line 1:
ORA-01950: no privileges on tablespace 'USERS'

SQL> DESC USER_TS_QUOTAS


Name Null? Type
----------------------------------------- -------- --------------------------
TABLESPACE_NAME NOT NULL VARCHAR2(30)
BYTES NUMBER
MAX_BYTES NUMBER
BLOCKS NUMBER
MAX_BLOCKS NUMBER
DROPPED VARCHAR2(3)

SQL> SELECT * FROM USER_TS_QUOTAS;

no rows selected

166 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Assigning quota to mraheem on USERS tablespace

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.

SQL> ALTER USER MRAHEEM QUOTA 5M ON USERS;

User altered.

SQL> CONN MRAHEEM/MCS298


Connected.

SQL> SELECT * FROM USER_TS_QUOTAS;

TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DRO


------------------------------ ---------- ---------- ---------- ---------- ---
USERS 0 5242880 0 640 NO

SQL> CREATE TABLE EMPLOYEE


2 (
3 EMPNO NUMBER(4) PRIMARY KEY,
4 ENAME VARCHAR2(20)
5 );

Table created.

SQL> SELECT * FROM USER_TS_QUOTAS;

TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DR


------------------------------ ---------- ---------- ---------- ---------- --
USERS 131072 5242880 16 640 NO

SQL> CREATE TABLE STUDENT


2 (
3 GRNO NUMBER(4) PRIMARY KEY,
4 NAME VARCHAR2(20) NOT NULL,
5 FNAME VARCHAR2(20)
6 );

Table created.

SQL> SELECT * FROM USER_TS_QUOTAS;

TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DRO


------------------------------ ---------- ---------- ---------- ---------- ---
USERS 262144 5242880 32 640 NO

SQL> SELECT * FROM USER_SYS_PRIVS;

USERNAME PRIVILEGE ADM


------------------------------ ---------------------------------------- ---
MRAHEEM CREATE VIEW NO
MRAHEEM CREATE TABLE NO
MRAHEEM CREATE SESSION NO
MRAHEEM CREATE SEQUENCE NO

167 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>

The REVOKE statement

You can remove privileges granted to other users by using the REVOKE statement. When you
use the REVOKE statement, the privileges that you specify are revoked from the users you
name and from any other users to whom those privileges were granted through the WITH
GRANT OPTION clause.

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.

SQL> REVOKE CREATE TABLE FROM MRAHEEM;

Revoke succeeded.

SQL> CONN MRAHEEM/MCS298


Connected.
SQL>
SQL> SELECT * FROM USER_SYS_PRIVS;

USERNAME PRIVILEGE ADM


------------------------------ ---------------------------------------- ---
MRAHEEM CREATE VIEW NO
MRAHEEM CREATE SESSION NO
MRAHEEM CREATE SEQUENCE NO

SQL> CREATE TABLE STUDENT


2 (
3 GRNO NUMBER(4) PRIMARY KEY,
4 NAME VARCHAR2(20)
5 );
CREATE TABLE STUDENT
*
ERROR at line 1:
ORA-01031: insufficient privileges

SQL>

168 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

Granting object privileges

You are trying to access EMP table, but you don’t have rights/privileges to access the EMP
table.

SQL> SHOW USER


USER is "MRAHEEM"

SQL> SELECT COUNT(*) FROM SCOTT.EMP;


SELECT COUNT(*) FROM SCOTT.EMP
*
ERROR at line 1:
ORA-00942: table or view does not exist

If you want to access objects of any other user, then you must have rights/privileges on that
objects to access them. Owner of objects grants rights on his objects.

SQL> CONN SCOTT/TIGER


Connected.

SQL> GRANT SELECT


2 ON EMP
3 TO MRAHEEM;

Grant succeeded.

SQL> GRANT SELECT, INSERT, UPDATE, DELETE


2 ON EMP
3 TO MRAHEEM;

Grant succeeded.

How to view granted object privileges

SQL> COL GRANTEE FORMAT A10


SQL> COL OWNER FORMAT A10
SQL> COL TABLE_NAME FORMAT A10
SQL> COL GRANTOR FORMAT A10
SQL> COL PRIVILEGE FORMAT A10
SQL>
SQL> SELECT * FROM USER_TAB_PRIVS_MADE;

GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE GRA HIE


---------- ---------- ---------- ---------- ---------- --- ---
MRAHEEM SCOTT EMP SCOTT INSERT NO NO
MRAHEEM SCOTT EMP SCOTT UPDATE NO NO
MRAHEEM SCOTT EMP SCOTT DELETE NO NO
MRAHEEM SCOTT EMP SCOTT SELECT NO NO

SQL> CONN MRAHEEM/MCS298


Connected.

SQL> SELECT COUNT(*) FROM SCOTT.EMP;

COUNT(*)
----------
18

169 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.

SQL> CREATE USER MR IDENTIFIED BY MCS298;

User created.

SQL> GRANT CREATE SESSION, CREATE TABLE TO MR;

Grant succeeded.

SQL> ALTER USER MR QUOTA 5M ON USERS;

User altered.

SQL> CONN MR/MCS298


Connected.

SQL> SELECT * FROM SCOTT.EMP;


SELECT * FROM SCOTT.EMP
*
ERROR at line 1:
ORA-00942: table or view does not exist

MRAHEEM is not authorized to grant privileges on SCOTT’s EMP table

SQL> CONN MRAHEEM/MCS298


Connected.

SQL> GRANT SELECT ON SCOTT.EMP TO MR;


GRANT SELECT ON SCOTT.EMP TO MR
*
ERROR at line 1:
ORA-01031: insufficient privileges

Grant privilege with grant option


(MRAHEEM is now authorized to grant privileges on SCOTT’s EMP table)
SQL> CONN SCOTT/TIGER
Connected.

SQL> GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO MRAHEEM WITH GRANT OPTION;

Grant succeeded.

SQL> CONN MRAHEEM/MCS298


Connected.

SQL> GRANT SELECT ON SCOTT.EMP TO MR;

Grant succeeded.

SQL>
170 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550

SCOTT can not revoke privileges directly on EMP table from MR user
SCOTT can revoke privileges from MRAHEEM user, and indirectly revoke from MR user

SQL> CONN SCOTT/TIGER


Connected.

SQL> REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM MR;


REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM MR
*
ERROR at line 1:
ORA-01927: cannot REVOKE privileges you did not grant

SQL> REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM MRAHEEM;

Revoke succeeded.

SQL>

171 [email protected]

You might also like