Oracle SQL PDF
Oracle SQL PDF
Oracle SQL PDF
What is a Database?
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
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.
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
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
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
EMP
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
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.
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.
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:
8 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
• 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.
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
1 2 4
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.
11 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
12 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
14 rows selected.
13 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
14 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
14 rows selected.
D
-
X
16 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SYSDATE
---------
14-JUL-08
USER
------------------------------
SCOTT
SQL>
PRECEDENCE
1. ( ) Parenthesis has the highest precedence
2. * / Multiplication and Division have the same precedence
3. + - Addition and Subtraction have the same precedence
7+10
----------
17
7+10-2+5
----------
20
7+10*2+5
----------
32
7+10-2*5
----------
7
17 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
7*10-2+5
----------
73
7*10-2*5
----------
60
7+10/2+5
----------
17
7*10/2+5
----------
40
7*10/2*5
----------
175
7+10/2*5
----------
32
7*10/(2+5)
----------
10
7*10+2+5
----------
77
7*(10+2)+5
----------
89
18 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL> SELECT EMPNO, ENAME, SAL, SAL+100, SAL-100, SAL*12 FROM EMP;
SQL> SELECT EMPNO, ENAME, SAL, SAL*12, SAL+100*12, (SAL+100)*12 FROM EMP;
SQL> SELECT EMPNO, ENAME, COMM, COMM+100, COMM-100, COMM*12 FROM EMP;
19 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL> SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM*12, (SAL+COMM)*12 FROM EMP;
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
14 rows selected.
14 rows selected.
21 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
14 rows selected.
22 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
AS is optional
SQL> SELECT EMPNO, ENAME, JOB AS DESIGNATION, SAL AS SALARY, COMM COMMISSION
FROM EMP;
14 rows selected.
14 rows selected.
SQL>
23 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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;
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.
EMPNO||ENAME
--------------------------------------------------
7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
7934MILLER
14 rows selected.
EMPLOYEE_INFO
-----------------------------------------------------------
7369SMITHCLERK
7499ALLENSALESMAN
7521WARDSALESMAN
7566JONESMANAGER
7654MARTINSALESMAN
7698BLAKEMANAGER
7782CLARKMANAGER
7788SCOTTANALYST
7839KINGPRESIDENT
7844TURNERSALESMAN
7876ADAMSCLERK
7900JAMESCLERK
7902FORDANALYST
7934MILLERCLERK
14 rows selected.
SQL>
25 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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;
14 rows selected.
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.
26 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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;
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.
DEPTNO
---------
30
20
10
JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST
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
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.
SQL>
SQL>
The following query retrieves records of all employees who are working
as CLERK.
SQL> SELECT * FROM EMP WHERE JOB='CLERK';
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.
no rows selected
SQL>
29 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>
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:
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.
30 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
SQL> SELECT EMPNO, ENAME, JOB FROM EMP WHERE ENAME BETWEEN 'K' AND 'P';
IN ( )
SQL> SELECT * FROM EMP WHERE EMPNO IN(7788,7839,7968,7654) ;
31 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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 who contain sequentially A and then M in their name
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_';
Retrieve all employees who contain first character A and third character L in
their name
SQL> SELECT * FROM EMP WHERE ENAME LIKE 'A_L%';
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
34 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
7 rows selected.
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;
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.
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.
14 rows selected.
14 rows selected.
37 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL> SELECT EMPNO, ENAME, SAL SALARY FROM EMP ORDER BY SALARY;
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
14 rows selected.
39 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
LENGTH('ORACLESQL')
-------------------
10
SUBST
-----
ROMAN
SUB
---
ROM
40 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
INSTR('PAKISTAN','I')
---------------------
0
INSTR('PAKISTAN','TA')
----------------------
6
INSTR('PAKISTAN','A')
---------------------
2
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
INSTR('PAKISTAN','A',3)
-----------------------
7
42 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
LPAD('P
-------
****PAK
LPAD('P
-------
PAK
LPAD('P
-------
->->PAK
LPAD('P
-------
123-PAK
CELL_NO
------------
0321-4265550
PTCL_NO
-----------
021-4265550
14 rows selected.
43 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
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;
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;
SQL>
45 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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;
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;
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;
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;
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;
The example calculates the remainder of the salary after dividing it by 500 for all employees.
14 rows selected.
SQL>
47 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
14 rows selected.
SQL>
48 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
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.
• 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;
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;
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;
SQL>
SQL>
50 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
14 rows selected.
SQL>
51 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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 (DAY)
BEFORE 12:00PM WEDNESDAY, PREVIOUS SUNDAY OF THE WEEK
AFTER 12:00PM WEDNESDAY, NEXT SUNDAY OF THE WEEK
SQL> SELECT
2 SYSDATE-10,
3 ROUND(SYSDATE-10,'MONTH'),
4 TRUNC(SYSDATE-10,'MONTH')
5 FROM DUAL;
SQL> SELECT
2 SYSDATE-30,
3 ROUND(SYSDATE-30,'MONTH'),
4 TRUNC(SYSDATE-30,'MONTH')
5 FROM DUAL;
52 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL> SELECT
2 SYSDATE-10,
3 ROUND(SYSDATE-10,'YEAR'),
4 TRUNC(SYSDATE-10,'YEAR')
5 FROM DUAL;
SQL> SELECT
2 SYSDATE-30,
3 ROUND(SYSDATE-30,'MONTH'),
4 TRUNC(SYSDATE-30,'MONTH')
5 FROM DUAL;
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;
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.
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.
TO_NUMBER TO_DATE
TO_CHAR TO_CHAR
54 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
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
24/07/08 02:38:33 PM
24/07/08 02:38:44 PM
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;
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;
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;
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
14 rows selected.
Assignment
59 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
TO_NUMBER ( )
4+3
---------
7
'4'+'3'
---------
7
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
SUBSTR('HOUSE#5,SEC11,KARACHI',9,1)*10
--------------------------------------
50
TO_DATE ( )
SQL> SELECT '14-AUG-1947' A FROM DUAL;
14-AUG-1947
14-AUG-47
17-AUG-47
17-AUG-47
60 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
14-AUG-47
14-AUG-47
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
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;
14 rows selected.
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;
14 rows selected.
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;
64 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
• 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.
Table created.
Table created.
Table created.
Table created.
65 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
TABLE_NAME
------------------------------
DEPT
EMP
BONUS
SALGRADE
STD_GRADE
STD_MARKS
CLASS
STUDENT
8 rows selected.
OBJECT_NAME
---------------------------------------------------------------------
DEPT
EMP
BONUS
SALGRADE
STD_GRADE
STD_MARKS
CLASS
STUDENT
8 rows selected.
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
8 rows selected.
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
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.
1 row created.
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.
In this example NULL value is moved in NIC column by using NULL keyword for NIC column.
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
CID CDESC
---------- --------------------
1 CLASS ONE
2 CLASS TWO
3 CLASS THREE
4 CLASS FOUR
5 CLASS FIVE
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
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.
71 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
1 row created.
SQL> COMMIT;
Commit complete.
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.
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
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.
73 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
6 rows selected.
OR
6 rows selected.
Cartesian / Cross Products (rows of one table multiply with rows of another table)
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
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.
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.
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
77 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
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.)
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
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.
• 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.
15 rows selected.
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.
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.”
1 row deleted.
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.
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
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
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;
The following example displays the number of employees who are earning more than 2000.
SQL> SELECT COUNT(*) FROM EMP WHERE SAL>2000;
COUNT(*)
---------
6
83 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
SQL> SELECT
2 SUM(COMM), COUNT(COMM), AVG(COMM),
3 COUNT(NVL(COMM,0)), AVG(NVL(COMM,0))
4 FROM EMP;
84 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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 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;
85 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
86 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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;
11 rows selected.
87 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
Any column or expression in the SELECT list that is not an aggregate function must be in the
GROUP BY clause.
88 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
TO_C COUNT(*)
---- ---------
1981 10
1987 2
TO_C COUNT(*)
---- ---------
1980 1
1981 10
1987 2
2082 1
MAX(AVG(SAL))
-------------
2916.6667
MAX(SUM(SAL))
-------------
10875
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.
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:
DEPTNO
---------
20
And now use department number 20 for retrieving all employees of that department.
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');
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.
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:
JOB
---------
MANAGER
And now use MANAGER in criteria for retrieving all employees of that job.
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');
Department names are not saved in EMP table. Now you have to use DEPT table in subquery
because DEPT table contains department names.
In the following query you used two tables DEPT in inner query and EMP in outer query.
92 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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);
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
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.
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:
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);
8 rows selected.
JOB
---------
MANAGER
PRESIDENT
CLERK
8 rows selected.
96 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
ANY Æ OR
ALL Æ AND
List all employees having salaries more then the minimum salary of department # 30
SAL
---------
1600
1250
1250
2850
1500
950
6 rows selected.
MIN(SAL)
---------
950
12 rows selected.
SQL>
97 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
12 rows selected.
12 rows selected.
12 rows selected.
98 [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 department # 30
SAL
---------
1600
1250
1250
2850
1500
950
6 rows selected.
9 rows selected.
9 rows selected.
99 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SAL
---------
1600
1250
1250
2850
1500
950
6 rows selected.
6 rows selected.
6 rows selected.
6 rows selected.
100 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
List of all employees having salaries more then the maximum salary of department # 30
SAL
---------
1600
1250
1250
2850
1500
950
6 rows selected.
101 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SAL
---------
1600
1250
1250
2850
1500
950
6 rows selected.
MIN(SAL)
---------
950
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');
SQL> SELECT * FROM EMP WHERE SAL <ANY (SELECT SAL FROM EMP WHERE JOB='CLERK');
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);
AVG(SAL)
---------
1566.6667
2175
2916.6667
103 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
14 rows selected.
COMM
---------
no rows selected
10 rows selected.
104 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
6 rows selected.
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);
8 rows selected.
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.
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)
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
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
108 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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)
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)
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
111 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Environmental Setting
3 rows selected.
112 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
113 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
14 rows selected.
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 SQL*Plus
• A language • An environment
• Runs on a browser
115 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL> @D:\Q1
SQL> R
1 SELECT EMPNO, ENAME, JOB, SAL
2 FROM EMP
3 WHERE DEPTNO=10
4* ORDER BY EMPNO
Chapter 8
Manipulating Data
Data Manipulation Language
You can add new rows to a table by issuing the INSERT statement.
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.
1 row created.
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.
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.
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.
You are inserting duplicate value in DEPTNO column, DEPTNO is primary key.
You are inserting a value 70 in DEPTNO column which is not present in DEPT table.
1 row created.
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
1 row created.
7 rows selected.
17 rows selected.
119 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
10 rows selected.
6 rows selected.
120 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
7 rows selected.
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.
16 rows selected.
17 rows selected.
122 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
INSERT is a DML statement. For saving data permanently into database, commit may be applied either
implicitly or explicitly.
SQL> COMMIT;
Commit complete.
SQL>
SQL> ROLLBACK;
Rollback complete.
SQL>
123 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
Table created.
Notice the EMPNO column in both EMP and EMP_INS tables in the below:
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
7 rows selected.
124 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
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.
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).
11 rows selected.
125 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
• 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.
1 row updated.
1 row updated.
1 row updated.
SQL> SELECT * FROM EMP WHERE EMPNO=2;
1 row updated.
126 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
1 row updated.
SQL> COMMIT;
Commit complete.
17 rows selected.
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
17 rows selected.
Give 10% increment to all employees who have hired before 12 or more months.
15 rows updated.
17 rows selected.
SQL> ROLLBACK;
Rollback complete.
128 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
11 rows selected.
11 rows updated.
11 rows selected.
11 rows selected.
129 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
3 rows deleted.
3 rows deleted.
All rows in the table are deleted if you omit the WHERE clause.
14 rows deleted.
14 rows deleted.
SQL> ROLLBACK;
Rollback complete.
6 rows deleted.
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.
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.
131 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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
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
Tables can have up to 1,000 columns and must conform to standard database object-naming
conventions.
Create tables to store data by executing the SQL CREATE TABLE statement. This statement is
one of the data definition language (DDL) statements
Table created.
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
By SELECT Statement
no rows selected
no rows selected
134 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
The following queries will create a table as well as copy all rows:
Table created.
Table created.
Table created.
Table created.
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.
Table altered.
Table altered.
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.
Table altered.
Table altered.
136 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
Table altered.
Table altered.
Table altered.
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.
Table dropped.
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.
COUNT(*)
---------
17
Table truncated.
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.
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.
Table created.
139 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
1 row created.
1 row created.
1 row created.
1 row created.
Note the errors in the following queries and give the reason of errors
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
You can view constraints information by using user_constraints but you can not view the
column names for which constraints are used.
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.
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.
CONSTRAINT_NAME COLUMN_NAME C
------------------------------ --------------- -
SYS_C0011126 DNAME C
SYS_C0011127 DEPTNO P
Table created.
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
Table created.
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
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
1 row created.
SQL> SELECT EMP_ID, JOIN_DATE, DESG, SALARY, NIC, DEPTNO FROM EMPLOYEE2;
SQL>
144 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Table created.
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.
Table altered.
Table altered.
145 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
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.
Table altered.
Table altered.
Table altered.
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
Table altered.
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.
Table altered.
Enabling Constraints
You can enable a constraint without dropping it or re-creating it by using the ALTER TABLE
statement with the ENABLE clause.
Table altered.
Cascading Constraints
SQL> ALTER TABLE DEPARTMENT
2 DROP (DEPTNO);
DROP (DEPTNO)
*
ERROR at line 2:
ORA-12992: cannot drop parent key column
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.
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.
View created.
148 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
17 rows selected.
1 row created.
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.
150 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Create a complex view that contains group functions to display summary information.
View created.
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.
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.
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:
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
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 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.
NEXTVAL
---------
1
NEXTVAL
---------
2
CURRVAL
---------
2
NEXTVAL
---------
3
153 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Sequence created.
NEXTVAL
---------
10
NEXTVAL
---------
12
NEXTVAL
---------
14
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.
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.
Sequence altered.
NEXTVAL
---------
16
NEXTVAL
---------
18
Sequence altered.
NEXTVAL
---------
23
Sequence altered.
CYCLE | NOCYCLE specifies whether the sequence continues to generate values after reaching its maximum or
minimum value (NOCYCLE is the default option.)
Sequence altered.
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.
1 row created.
SQL> /
1 row created.
9 rows selected.
SQL> ROLLBACK;
Rollback complete.
Sequence created.
Table altered.
4 rows updated.
SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, SNO FROM EMP WHERE DEPTNO=10;
156 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Table altered.
Table created.
18 rows selected.
1 row created.
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
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.
Table altered.
Create an index on ENAME to improve the speed of query access to the ENAME column in the
EMP table.
Index created.
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.
You can also check the columns involved in an index by querying the USER_IND_COLUMNS
view.
I want to retrieve index information in one query from the above data dictionary.
Function-Based Indexes
Index created.
18 rows updated.
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.
Index dropped.
160 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Synonyms
Synonym created.
If you want to access objects of another user you may get error
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
Synonym created.
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)
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
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.
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.
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.
Executing this statement, we find privileges like create session, drop user, alter database.
163 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
Object privileges
For a user to be able to access an object in another user's schema, he needs the according
object privilege.
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.
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.
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.
165 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>
no rows selected
166 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
User altered.
Table created.
Table created.
167 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>
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.
Revoke succeeded.
SQL>
168 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
You are trying to access EMP table, but you don’t have rights/privileges to access the EMP
table.
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.
Grant succeeded.
Grant succeeded.
COUNT(*)
----------
18
169 [email protected]
Prepared by Muhammad Raheem
Oracle SQL Phone: 021-4265550, Cell: 0321-4265550
SQL>
User created.
Grant succeeded.
User altered.
SQL> GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO MRAHEEM WITH GRANT OPTION;
Grant succeeded.
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
Revoke succeeded.
SQL>