You are on page 1of 211

Treasure Island Training Service Ph:09691011157

Oracle Basic SQL and Advanced SQL

1.1 Creating Users

The DBA creates users with the CREATE USER statement.

CREATE USER user IDENTIFIED BY password;

CREATE USER demo IDENTIFIED BY demo;

1.2 User System Privileges


 After a user is created, the DBA can grant specific system privileges to that user.

GRANT privilege [, privilege ...] TO user [,user| role, PUBLIC…];

 An application developer, for example, may have the following system privileges:

– CREATE SESSION
– CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE

1.3 Granting System Privileges


The DBA can grant specific system privileges to a user.
GRANT create session, create table, create sequence, create view TO demo;

Grant create table to thawtest;

Grant create table, select on thawtest.thaw_tb to thawdba; xxxxxxxxxxxxxx

1.4 What Is a Role?

Thawzh818@gmail.com Page 1
Treasure Island Training Service Ph:09691011157

1.5 Creating and Granting Privileges to a Role

 Create a role:

CREATE ROLE manager;

 Grant privileges to a role:

GRANT create table, create view TO manager;

 Grant manager To alice;

GRANT manager TO alice;

1.6 Changing Your Password (sys,dba,alter user privilege ) owner

 The DBA creates your user account and initializes your password.
 You can change your password by using the ALTER USER statement.

ALTER USER demo IDENTIFIED BY employ;


Alter user hr identified by oraclesql account unlock;

Thawzh818@gmail.com Page 2
Treasure Island Training Service Ph:09691011157

1.7 Object Privileges (owner,sys,dba)

Object Privilege Table View Sequence


ALTER
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE

 Object privileges vary from object to object.


 An owner has all the privileges on the object.
 An owner can give specific privileges on that owner‟s object.

GRANT object_priv [(columns)]


ON object
TO {user |role |PUBLIC}
[WITH GRANT OPTION];

1.8 Granting Object Privileges


 Grant query privileges on the EMPLOYEES table:
GRANT select ON employees TO demo;

 Grant privileges to update specific columns to users and roles:


GRANT update (department_name, location_id)
ON departments
TO demo, manager;

Thawzh818@gmail.com Page 3
Treasure Island Training Service Ph:09691011157

1.9 Passing On Your Privileges

 Give a user authority to pass along privileges:

GRANT select, insert


ON departments
TO demo
WITH GRANT OPTION;

 Allow all users on the system to query data from DEPARTMENTS table:

GRANT select
ON departments
TO PUBLIC;
1.10 Confirming Granted Privileges

Data Dictionary View Description


ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_SYS_PRIVS System privileges granted to the user
USER_TAB_PRIVS_MADE Object privileges granted on the user‟s
objects
USER_TAB_PRIVS_RECD Object privileges granted to the user
USER_COL_PRIVS_MADE Object privileges granted on the
columns of the user‟s object
USER_COL_PRIVS_RECD Object privileges granted to the user on
specific columns
1.11 Revoking Object Privileges

 You use the REVOKE statement to revoke privileges granted to other users.

Thawzh818@gmail.com Page 4
Treasure Island Training Service Ph:09691011157

 Privileges granted to others through the WITH GRANT OPTION clause are also
revoked.

REVOKE {privilege [, privilege...]|ALL}


ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];

1.12 Revoking Object Privileges

Revoke the SELECT and INSERT privileges given to the demo user on the
DEPARTMENTS table.

REVOKE select, insert


ON departments
FROM demo;

Practice 1-1:Introduction
1. Start Oracle SQL Developer by using the SQL Developer Desktop icon.
2. Create a New Oracle SQL Developer Database Connection
a. To create a new database connection, in the Connections Navigator, right-click
Connections and select New Connection from the context menu. The New/Select
Database Connection dialog box appears.
b. Create a database connection by using the following information: Connection
Name: myconnection Username: ora1 Password: ora1 Hostname: localhost
(192.168.56.101)
Port: 1521
SID: oraclesql
Ensure that you select the Save Password check box.

Thawzh818@gmail.com Page 5
Treasure Island Training Service Ph:09691011157

3. Testing the Oracle SQL Developer Database Connection and Connecting to the
Database
a. Test the new connection.
b. If the status is Success, connect to the database by using this new
connection.
4. Browsing the Tables in the Connections Navigator
a. In the Connections Navigator, view the objects that are available to you in the
Tables node. Verify that the following tables are present:
COUNTRIES
DEPARTMENTS
EMPLOYEES

JOB_GRADES
JOB_HISTORY
JOBS
LOCATIONS
REGIONS
b. Browse the structure of the EMPLOYEES table.
c. View the data of the DEPARTMENTS table.

2.1 Relational and Object Relational Database Management Systems


• Relational model and object relational model
• User-defined data types and objects
• Fully compatible with relational database
• Supports multimedia and large objects
• High-quality database server features
2.2 Relation Database

Thawzh818@gmail.com Page 6
Treasure Island Training Service Ph:09691011157

A relational database uses relations or two-dimensional tables to store information. For


example, you might want to store information about all the employees in your
company. In a relational database, you create several tables to store different pieces of
information about your employees, such as an employee table, a department table, and
a salary table.

2.3 ERD (Entity Relation Diagram)

Thawzh818@gmail.com Page 7
Treasure Island Training Service Ph:09691011157

2.4 Entity Relationship Model (continued)


Benefits of ER Modeling:
• Documents information for the organization in a clear, precise format
• Provides a clear picture of the scope of the information requirement
• Provides an easily understood pictorial map for database design
• Offers an effective framework for integrating multiple applications
Key Components
• Entity: An aspect of significance about which information must be known. Examples
are departments, employees, and orders.
• Attribute: Something that describes or qualifies an entity. For example, for the
employee entity, the attributes would be the employee number, name, job title, hire
date, department number, and so on. Each of the attributes is either required or
optional. This state is called optionality.

Thawzh818@gmail.com Page 8
Treasure Island Training Service Ph:09691011157

• Relationship: A named association between entities showing optionality and degree.


Examples are employees and departments, and orders and items

2.5 ER Modeling Conventions


Entities
To represent an entity in a model, use the following conventions:
• Singular, unique entity name
• Entity name in uppercase
• Soft box
• Optional synonym names in uppercase within parentheses: ( )
Attributes
To represent an attribute in a model, use the following conventions:

Thawzh818@gmail.com Page 9
Treasure Island Training Service Ph:09691011157

• Singular name in lowercase


• Asterisk (*) tag for mandatory attributes (that is, values that must be known)
• Letter “o” tag for optional attributes (that is, values that may be known)

2.6 Relationships

Relating Multiple Tables (continued)


Guidelines for Primary Keys and Foreign Keys

Thawzh818@gmail.com Page 10
Treasure Island Training Service Ph:09691011157

• You cannot use duplicate values in a primary key.


• Primary keys generally cannot be changed.
• Foreign keys are based on data values and are purely logical (not physical) pointers.
• A foreign key value must match an existing primary key value or unique key value,
otherwise it must be null.

• A foreign key must reference either a primary key or a unique key column.

2.7 Using SQL to Query Your Database


In a relational database, you do not specify the access route to the tables, and you do
not need to know how the data is arranged physically.
To access the database, you execute a structured query language (SQL) statement,
which is the American National Standards Institute (ANSI) standard language for
operating relational databases. SQL is a set of statements with which all programs and

Thawzh818@gmail.com Page 11
Treasure Island Training Service Ph:09691011157

users access data in an Oracle database. Application programs and Oracle tools often
allow users access to the database without using SQL directly, but these applications, in
turn, must use SQL when executing the user‟s request.
SQL provides statements for a variety of tasks, including:
• Querying data • Inserting, updating, and deleting rows in a table
• Creating, replacing, altering, and dropping objects
• Controlling access to the database and its objects
• Guaranteeing database consistency and integrity

SQL unifies all of the preceding tasks in one consistent language and enables you to
work with data at a logical level.

2.8 SQL Statements

Thawzh818@gmail.com Page 12
Treasure Island Training Service Ph:09691011157

SQL statements supported by Oracle comply with industry standards. Oracle


Corporation ensures future compliance with evolving standards by actively involving key
personnel in SQL standards committees. The industry-accepted committees are ANSI
and International Standards Organization (ISO). Both ANSI and ISO have accepted SQL
as the standard language for relational databases

Thawzh818@gmail.com Page 13
Treasure Island Training Service Ph:09691011157

2.9 Basic SELECT Statement


SELECT
FROM
AS OF TIMESTAMP/ VERSION BETWEEN SCN
WHERE
GROUP BY
HAVING
ORDER BY
OFFSET
FETCH
2.10 Selecting All Columns

SELECT *
FROM table_name;

Thawzh818@gmail.com Page 14
Treasure Island Training Service Ph:09691011157

Selecting Specific Columns


SELECT department_id,location_id
FROM departments;

2.11 Writing SQL Statements


• SQL statements are not case-sensitive.
• SQL statements can be entered on one or more lines.
• Keywords cannot be abbreviated or split across lines.
• Clauses are usually placed on separate lines.
• Indents are used to enhance readability.
• In SQL Developer, SQL statements can optionally be terminated by a semicolon (;).
Semicolons are required when you execute multiple SQL statements.
• In SQL*Plus, you are required to end each SQL statement with a semicolon (;).
Column Heading Defaults
• SQL Developer:
– Default heading alignment: Left-aligned
– Default heading display: Uppercase
• SQL*Plus:
– Character and Date column headings are left-aligned.
– Number column headings are right-aligned.
– Default heading display: Uppercase

Thawzh818@gmail.com Page 15
Treasure Island Training Service Ph:09691011157

2.12 Arithmetic Expressions


Create expressions with number and date data by using arithmetic operators.

Thawzh818@gmail.com Page 16
Treasure Island Training Service Ph:09691011157

2.13 Using Arithmetic Operators

2.14 Operator Precedence

If an arithmetic expression contains more than one operator, multiplication and division
are evaluated first. If operators in an expression are of the same priority, then
evaluation is done from left to right. You can use parentheses to force the expression
that is enclosed by the parentheses to be evaluated first. Rules of Precedence:
• Multiplication and division occur before addition and subtraction.
• Operators of the same priority are evaluated from left to right.
• Parentheses are used to override the default precedence or to clarify the
statement.
2.15 Defining a Null Value
• Null is a value that is unavailable, unassigned, unknown, or inapplicable.
• Null is not the same as zero or a blank space.
Null Values in Arithmetic Expressions
Arithmetic expressions containing a null value evaluate to null.

Thawzh818@gmail.com Page 17
Treasure Island Training Service Ph:09691011157

2.16 Defining a Column Alias

A column alias:
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name (There can also be the optional AS keyword
between the column name and alias.)
• Requires double quotation marks if it contains spaces or special characters, or if it is
case-sensitive

Thawzh818@gmail.com Page 18
Treasure Island Training Service Ph:09691011157

1 SELECT first_name, last_name


FROM employees
ORDER BY first_name;
2 Select first_name forename, first_name “forename” ,first_name as first
name,first_name as “first name” from employees;
3 SELECT first_name AS forename, last_name AS surname
FROM employees;
4 SELECT first_name forename, last_name surname
FROM employees;
5 SELECT first_name "Forename", last_name "Surname"
FROM employees;
6 SELECT first_name "First Name", last_name "Family Name"
FROM employees;

2.17 Concatenation Operator

A concatenation operator:
• Links columns or character strings to other columns

Thawzh818@gmail.com Page 19
Treasure Island Training Service Ph:09691011157

• Is represented by two vertical bars (||)


• Creates a resultant column that is a character expression

Using Literal Character Strings

Thawzh818@gmail.com Page 20
Treasure Island Training Service Ph:09691011157

2.18 Alternative Quote (q) Operator


• Specify your own quotation mark delimiter.
• Select any delimiter.
• Increase readability and usability.

1 SELECT first_name || ' ' || last_name


FROM employees;
2 SELECT first_name || ' ' || last_name AS "Full Name"
FROM employees;
3 SELECT product_name, list_price - standard_cost AS gross_profit
FROM products;

Thawzh818@gmail.com Page 21
Treasure Island Training Service Ph:09691011157

4 SELECT product_name, list_price - standard_cost AS gross_profit


FROM products;
5 select department_name || „ Department ‟ || q‟ [„s manager id:]‟ || manager_id
as “Department and Manager” , department_name,manager_id
from departments;
2.19 Duplicate Rows

The default display of queries is all rows, including duplicate rows.

1 SELECT DISTINCT column_1


FROM table;
2 SELECT DISTINCT column_1, column_2, ...
FROM table_name;
3 SELECT first_name
FROM contacts;
4 SELECT DISTINCT first_name
FROM contacts;
5 SELECT DISTINCT product_id, quantity
FROM ORDER_ITEMS;

Thawzh818@gmail.com Page 22
Treasure Island Training Service Ph:09691011157

6 SELECT DISTINCT state


FROM locations;

2.20 Displaying the Table Structure


• Use the DESCRIBE command to display the structure of a table.
• Or, select the table in the Connections tree and use the Columns tab to view the table
structure.

DESCRIBE employees;

Desc employees;

Practice 2-1: Retrieving Data Using the SQL SELECT Statement


1. The following SELECT statement executes successfully:
SELECT last_name, job_id, salary AS Sal
FROM employees;

Thawzh818@gmail.com Page 23
Treasure Island Training Service Ph:09691011157

True/Flase

2. The following SELECT statement executes successfully:


SELECT *
FROM job_grades;

True/False

3. There are four coding errors in the following statement. Can you identify
them?
SELECT employee_id, last_name sal x 12 ANNUAL SALARY
FROM employees;

4. Your first task is to determine the structure of the DEPARTMENTS table and
its contents.

5. Your task is to determine the structure of the EMPLOYEES table and its
contents.
a. Determine the structure of the EMPLOYEES table.
b. The HR department wants a query to display the last name, job ID,
hire date, and employee ID for each employee, with the employee ID

Thawzh818@gmail.com Page 24
Treasure Island Training Service Ph:09691011157

appearing first. Provide an alias STARTDATE for the HIRE_DATE


column. Save your SQL statement to a file named lab_02_5b.sql so
that you can dispatch this file to the HR department. Test your query
in the lab_02_5b.sql file to ensure that it runs correctly.
Note: After you have executed the query, make sure that you do not enter your
next query in the same worksheet. Open a new worksheet.
6. The HR department wants a query to display all unique job IDs from the
EMPLOYEES table.

7. The HR department wants more descriptive column headings for its report on
employees. Copy the statement from lab_02_5b.sql to a new SQL Worksheet.
Name the columns Emp #, Employee, Job, and Hire Date, respectively. Then
run the query again.

8. The HR department has requested a report of all employees and their job
IDs. Display the last name concatenated with the job ID (separated by a
comma and space) and name the column Employee and Title.

9. To familiarize yourself with the data in the EMPLOYEES table, create a query
to display all the data from that table. Separate each column output by a
comma. Name the column THE_OUTPUT.
1 True
2 True
3 select employee_id,last_name,salary*12 "Annual Salary"
from hr.employees;
4 desc hr.departments;
5 desc hr.employees;
5 select employee_id,last_name,job_id,hire_date startdate
from hr.employees;

Thawzh818@gmail.com Page 25
Treasure Island Training Service Ph:09691011157

6 select distinct job_id from hr.employees;


7 select employee_id "Emp#",last_name "Employee",job_id "Job",hire_date "Hire
Date"
from hr.employees;
8 select last_name ||', '||job_id "Employee and Titile"
from hr.employees;
9
select EMPLOYEE_ID || ', '||FIRST_NAME|| ', '||LAST_NAME|| ', '||EMAIL|| ',
'||PHONE_NUMBER|| ', '||HIRE_DATE|| ', '||JOB_ID || ', '||SALARY|| ',
'||COMMISSION_PCT || ', '||MANAGER_ID|| ', '||DEPARTMENT_ID the_output
from hr.employees;

3.1 Limiting the Rows that Are Selected


• Restrict the rows that are returned by using the WHERE clause:
• The WHERE clause follows the FROM clause
In the syntax:
WHERE restricts the query to rows that meet a condition
condition is composed of column names, expressions, constants, and a
comparison operator. A condition specifies a combination of one or more
expressions and logical (Boolean) operators, and returns a value of TRUE, FALSE, or
UNKNOWN.
The WHERE clause can compare values in columns, literal, arithmetic expressions, or
functions. It consists of three elements:
• Column name
• Comparison condition
• Column name, constant, or list of values
Using the WHERE Clause

Thawzh818@gmail.com Page 26
Treasure Island Training Service Ph:09691011157

Character Strings and Dates


• Character strings and date values are enclosed with single quotation marks.
• Character values are case-sensitive and date values are format-sensitive.
• The default date display format is DD-MON-RR.

3.2 Comparison Operators

Thawzh818@gmail.com Page 27
Treasure Island Training Service Ph:09691011157

3.3 Extend Operator

Operator Description
!=,<>,^= Inequality
Compare a value to a list or subquery. It must be preceded by
ANY/ SOME / ALL
another operator such as =, >, <.
NOT IN Not equal to any value in a list of values
[NOT] BETWEEN
Equivalent to [Not] >= n and <= y.
n and m
[NOT] EXISTS Return true if subquery returns at least one row
IS [NOT] NULL NULL test
1 SELECT product_name, list_price
FROM products
WHERE list_price > 500;
2 SELECT product_name, list_price
FROM products
WHERE list_price > 500 AND category_id = 4;
3 SELECT product_name, list_price
FROM products
WHERE list_price BETWEEN 650 AND 680;

Note that the following expressions are equivalent:


list_price BETWEEN 650 AND 680
list_price >= 650 AND list_price <= 680
5 SELECT product_name, category_id
FROM products
WHERE category_id IN(1, 4)
ORDER BY product_name;

Category_id in (1,4) is the same as categorly_id=1 or category_id=4

Thawzh818@gmail.com Page 28
Treasure Island Training Service Ph:09691011157

6 SELECT last_name
FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith';

3.4 Pattern Matching Using the LIKE Operator


• Use the LIKE operator to perform wildcard searches of valid search string values.
• Search conditions can contain either literal characters or numbers:
– % denotes zero or many characters.
– _ denotes one character.
1 SELECT last_name, hire_date
FROM employees
WHERE hire_date LIKE '%95';

3.5 Combining Wildcard Characters


• You can combine the two wildcard characters (%, _) with literal characters for pattern
matching:
1 SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;

• You can use the ESCAPE identifier to search for the actual % and _ symbols.
1 SELECT employee_id, last_name, job_id
FROM employees
WHERE job_id LIKE '%SA_%;
2 SELECT employee_id, last_name, job_id

Thawzh818@gmail.com Page 29
Treasure Island Training Service Ph:09691011157

FROM employees
WHERE job_id LIKE '%SA\_%' ESCAPE '\';

3.6 Using the NULL Conditions


Test for nulls with the IS NULL operator.
1 SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL ;
2 SELECT last_name, job_id, commission_pct
FROM employees
WHERE commission_pct IS NULL;

3.7 Defining Conditions Using the Logical Operators

1 SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000 AND job_id LIKE '%MAN%' ;
2 SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000 OR job_id LIKE '%MAN%' ;

Thawzh818@gmail.com Page 30
Treasure Island Training Service Ph:09691011157

3 SELECT last_name, job_id


FROM employees
WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
4 SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE job_id NOT IN ('AC_ACCOUNT', 'AD_VP');
5 SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary NOT BETWEEN 10000 AND 15000;
6 SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE last_name NOT LIKE '%A%';
7 SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE commission_pct IS NOT NULL;

3.8 Rules of Precedence

Thawzh818@gmail.com Page 31
Treasure Island Training Service Ph:09691011157

3.9 Using the ORDER BY Clause

• Sort retrieved rows with the ORDER BY clause:


– ASC: Ascending order, default
– DESC: Descending order
• The ORDER BY clause comes last in the SELECT statement:
• Null first and Null last (default)

1. SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY hire_date ;

Note: today > yesterday


2 SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;

Thawzh818@gmail.com Page 32
Treasure Island Training Service Ph:09691011157

3 SELECT employee_id, last_name, salary*12 annsal


FROM employees
ORDER BY annsal ;

Note: column alias can use in order by clause only


4 SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY 3;

Note: 3 means third column from select clause.


5 SELECT last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC;
6 SELECT country_id, city, state
FROM locations
ORDER BY state ASC NULLS LAST;
7 SELECT customer_id,name
FROM customers
ORDER BY name ;
8 SELECT customer_id,name
FROM customers
ORDER BY UPPER( name );

3.10 Oracle FETCH clause syntax


[ OFFSET offset ROWS]
FETCH NEXT [ row_count | percent PERCENT ] ROWS [ ONLY | WITH TIES ]

Thawzh818@gmail.com Page 33
Treasure Island Training Service Ph:09691011157

3.11 OFFSET clause

The OFFSET clause specifies the number of rows to skip before the row limiting starts.
The OFFSET clause is optional. If you skip it, then offset is 0 and row limiting starts
with the first row.

The offset must be a number or an expression that evaluates to a number. The offset is
subjected to the following rules:

 If the offset is negative, then it is treated as 0.


 If the offset is NULL or greater than the number of rows returned by the query,
then no row is returned.
 If the offset includes a fraction, then the fractional portion is truncated.

3.12 FETCH clause

The FETCH clause specifies the number of rows or percentage of rows to return.

For the semantic clarity purpose, you can use the keyword ROW instead of ROWS,
FIRST instead of NEXT. For example, the following clauses behavior the same:

FETCH NEXT 1 ROWS


FETCH FIRST 1 ROW
3.13 Oracle FETCH clause examples
A) Top N rows example
The following statement returns the top 10 products with the highest inventory level:

SELECT product_name, quantity


FROM inventories
INNER JOIN products
USING(product_id)

Thawzh818@gmail.com Page 34
Treasure Island Training Service Ph:09691011157

ORDER BY quantity DESC


FETCH NEXT 10 ROWS ONLY;

B) WITH TIES example

The following query uses the row limiting clause with the WITH TIES option:

SELECT product_name, quantity


FROM inventories
INNER JOIN products
USING(product_id)
ORDER BY quantity DESC
FETCH NEXT 10 ROWS WITH TIES;

Even though the query requested 10 rows, because it had the WITH TIES option, the
query returned two more additional rows. Notice that these two additional rows have
the same value in the quantity column as the row 10.

C) Limit by percentage of rows example

The following query returns top 5% products with the highest inventory level:

SELECT product_name, quantity


FROM inventories
INNER JOIN products
USING(product_id)
ORDER BY quantity DESC
FETCH FIRST 5 PERCENT ROWS ONLY;

The inventories table has 1112 rows, therefore, 5% of 1112 is 55.6 which is rounded up
to 56 (rows).

Thawzh818@gmail.com Page 35
Treasure Island Training Service Ph:09691011157

D) OFFSET example

The following query skips the first 10 products with the highest level of inventory and
returns the next 10 ones:

SELECT product_name,quantity
FROM inventories
INNER JOIN products
USING(product_id)
ORDER BY quantity DESC
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;

3.14 Substitution Variables


• Use substitution variables to:
– Temporarily store values with single-ampersand (&) and double-ampersand (&&)
substitution
• Use substitution variables to supplement the following:
– WHERE conditions
– ORDER BY clauses
– Column expressions
– Table names
– Entire SELECT statement
1 SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE employee_id = &employee_num ;
2 SELECT last_name, department_id, salary*12
FROM employees
WHERE job_id = '&job_title' ;
3 SELECT employee_id, last_name, job_id,&column_name

Thawzh818@gmail.com Page 36
Treasure Island Training Service Ph:09691011157

FROM employees
WHERE &condition
ORDER BY &order_column ;
4 SELECT employee_id, last_name, job_id, &&column_name
FROM employees
ORDER BY &column_name ;

3.15 Using the DEFINE Command


• Use the DEFINE command to create and assign a value to a variable.
• Use the UNDEFINE command to remove a variable.
1 DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;

UNDEFINE employee_num

3.16 Using the VERIFY Command


Use the VERIFY command to toggle the display of the substitution variable, both before
and after SQL Developer replaces substitution variables with values:

1 SET VERIFY ON
SELECT employee_id, last_name, salary
FROM hr.employees
WHERE employee_id = &employee_num;

Practices 3-1: Restricting and Sorting Data

Thawzh818@gmail.com Page 37
Treasure Island Training Service Ph:09691011157

The HR department needs your assistance in creating some queries.


1. Because of budget issues, the HR department needs a report that displays the last
name
and salary of employees who earn more than $12,000. Save your SQL statement as a
file named lab_03_01.sql. Run your query.
2. Open a new SQL Worksheet. Create a report that displays the last name and
department number for employee number 176. Run the query.
3. The HR department needs to find high-salary and low-salary employees. Modify
lab_03_01.sql to display the last name and salary for any employee whose salary is not
in the range $5,000 through $12,000. Save your SQL statement as lab_03_03.sql.
4. Create a report to display the last name, job ID, and hire date for employees with
the last names of Matos and Taylor. Order the query in ascending order by hire date.
5. Display the last name and department ID of all employees in departments 20 or 50 in
ascending alphabetical order by last_name.
6. Modify lab_03_03.sql to display the last name and salary of employees who earn
between $5,000 and $12,000, and are in department 20 or 50. Label the columns
Employee and Monthly Salary, respectively. Save lab_03_03.sql as lab_03_06.sql again.
Run the statement in lab_03_06.sql.
7. The HR department needs a report that displays the last name and hire date of all
employees who were hired in 2006.
8. Create a report to display the last name and job title of all employees who do not
have a manager.
9. Create a report to display the last name, salary, and commission of all employees
who earn commissions. Sort the data in descending order of salary and commissions.
Use the column‟s numeric position in the ORDER BY clause.
10. Members of the HR department want to have more flexibility with the queries that
you are writing. They would like a report that displays the last name and salary of

Thawzh818@gmail.com Page 38
Treasure Island Training Service Ph:09691011157

employees who earn more than an amount that the user specifies after a prompt. Save
this query to a file named lab_03_10.sql. (You can use the query created in Task 1 and
modify it.) If you enter 12000 when prompted, the report displays the following results:
11. The HR department wants to run reports based on a manager. Create a query that
prompts the user for a manager ID, and generates the employee ID, last name, salary,
and department for that manager‟s employees. The HR department wants the ability to
sort the report on a selected column. You can test the data with the following values:
manager_id = 103, sorted by last_name:
manager_id = 201, sorted by salary:
manager_id = 124, sorted by employee_id:
12. Display the last names of all employees where the third letter of the name is “a.”
13. Display the last names of all employees who have both an “a” and an “e” in their
last name.
14. Display the last name, job, and salary for all employees whose jobs are either that
of a sales representative or a stock clerk, and whose salaries are not equal to $2,500,
$3,500, or $7,000.
15. Modify lab_03_06.sql to display the last name, salary, and commission for all
employees whose commission is 20%. Save lab_03_06.sql as lab_03_15.sql again.
Rerun the statement in lab_03_15.sql.
Solution

1 select *
from hr.employees
where salary>12000;
2 select *
from hr.employees
where employee_id=176;
3 select *
from hr.employees

Thawzh818@gmail.com Page 39
Treasure Island Training Service Ph:09691011157

where salary not between 5000 and 12000;


4 select *
from hr.employees
where last_name in ('Matos','Taylor');
5 select *
from hr.employees
where department_id in (20,50)
order by last_name ;
6 select *
from hr.employees
where salary not between 5000 and 12000
and department_id in (20,50);
7 select *
from hr.employees
where extract(year from hire_date)=2006;
8 select *
from hr.employees
where manager_id is null;
9 select *
from hr.employees
where commission_pct is not null
order by 3;
10 select *
from hr.employees
where salary>&salary;
11 select *
from hr.employees
where manager_id=&manager_id
order by &column_name;
12 select *
from hr.employees

Thawzh818@gmail.com Page 40
Treasure Island Training Service Ph:09691011157

where last_name like '__a%';


13 select *
from hr.employees
where last_name like '%e%a%' or last_name like '%a%e%';
14 select *
from hr.employees
where job_id='SA_REP'
and salary in (2500,3500,7000);
15 select *
from hr.employees
where commission_pct=.20;

4. Using Single-Row Functions to Customize Output

4.1 Two Types of SQL Functions

Two Types of SQL Functions

Thawzh818@gmail.com Page 41
Treasure Island Training Service Ph:09691011157

There are two types of functions:


 Single-row functions
 Multiple-row functions
Single-Row Functions
These functions operate on single rows only and return one result per row.

There are different types of single-row functions.


This lesson covers the following ones:
• Character
• Number
• Date
• Conversion
• General

Multiple-Row Functions (number function)


Functions can manipulate groups of rows to give one result per group of rows. These
functions are also known as group functions (covered in lesson 5 titled “Reporting
Aggregated Data Using the Group Functions”).

Thawzh818@gmail.com Page 42
Treasure Island Training Service Ph:09691011157

Thawzh818@gmail.com Page 43
Treasure Island Training Service Ph:09691011157

1 SELECT 'The job id for '||UPPER(last_name)||' is ' ||LOWER(job_id) AS


"EMPLOYEE DETAILS"
FROM employees;
2 SELECT employee_id, last_name, department_id
FROM employees
WHERE last_name = 'higgins';
3 SELECT employee_id, last_name, department_id
FROM employees
WHERE LOWER(last_name) = 'higgins';

Thawzh818@gmail.com Page 44
Treasure Island Training Service Ph:09691011157

4 SELECT employee_id, last_name, department_id


FROM employees
WHERE LOWER(last_name) = lower('HIGGINS');
5 SELECT employee_id, UPPER(last_name), department_id
FROM employees
WHERE INITCAP(last_name) = 'Higgins';
6 Select CONCAT('Hello', 'World')
from dual;
7 Select SUBSTR('HelloWorld',1,5)
from dual;
8 Select LENGTH('HelloWorld')
from dual;
9 Select INSTR('HelloWorld', 'W‟)
from dual;
10 Selec t LPAD(salary,10,'*')
from employees;
11 Select RPAD(salary, 10, '*')
from employees;
13 Select TRIM('H' FROM 'HelloWorld')
from dual;
14 SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH
(last_name), INSTR(last_name, 'a') "Contains 'a'?"
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';

4.3 `Number Functions


• ROUND: Rounds value to a specified decimal
• TRUNC: Truncates value to a specified decimal
• MOD: Returns remainder of division

Thawzh818@gmail.com Page 45
Treasure Island Training Service Ph:09691011157

1 Select ROUND(45.926, 2)
from dual;
2 Select TRUNC(45.926, 2)
from dual;
3 Select TRUNC(45.926, -2)
from dual;
4 SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1)
FROM DUAL;
5 SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-1)
FROM DUAL;
6 SELECT last_name, salary, MOD(salary, 5000) FROM employees
WHERE job_id = 'SA_REP';

4.4 Working with Dates

• The Oracle database stores dates in an internal numeric format: century, year, month,
day, hours, minutes, and seconds.
• The default date display format is DD-MON-RR.
– Enables you to store 21st-century dates in the 20th century by specifying only
the last two digits of the year
– Enables you to store 20th-century dates in the 21st century in the same way

SELECT last_name, hire_date


FROM employees

Thawzh818@gmail.com Page 46
Treasure Island Training Service Ph:09691011157

WHERE hire_date < '01-FEB-88 ' ';

4.5 Oracle Date Format This data is stored internally as follows:

CENTURY YEAR MONTH DAY HOUR MINUTE SECOND


19 87 06 17 17 10 43

4.6 Using the SYSDATE Function

SYSDATE is a function that returns:


• Date
• Time

SELECT sysdate
FROM dual;

4.7 Arithmetic with Dates


• Add or subtract a number to or from a date for a resultant date value.
• Subtract two dates to find the number of days between those dates.
• Add hours to a date by dividing the number of hours by 24.

1 SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS


FROM employees
WHERE department_id = 90;

Thawzh818@gmail.com Page 47
Treasure Island Training Service Ph:09691011157

Date-Manipulation Functions

1 Select months_between(sysdate,hire_date)
from hr.employees;
2 Select add_months(sysdate,10)
from hr.employees;
3 Select next_day(hire_date,‟Monday‟)
from hr.employees;
4 Select last_day(hire_date)
From hr.employees;
5 SELECT ROUND(TO_DATE ('16-SEP-2015'),'MONTH') "New Month",
ROUND(TO_DATE ('16-SEP-2015'),'YEAR') "New Year"
FROM DUAL;
6 SELECT TRUNC(TO_DATE ('16-SEP-2015'),'MONTH') "New Month",
TRUNC(TO_DATE ('16-SEP-2015'),'YEAR') "New Year"
FROM DUAL;
7 SELECT employee_id, hire_date, ROUND(hire_date, 'MONTH'),
TRUNC(hire_date, 'MONTH') FROM employees
WHERE hire_date LIKE '%97';

Practices 4-1: Using Single-Row Functions to Customize Output


1. Write a query to display the system date. Label the column Date.

Thawzh818@gmail.com Page 48
Treasure Island Training Service Ph:09691011157

Note: Note: If your database is remotely located in a different time zone, the output will
be the date for the operating system on which the database resides.
2. The HR department needs a report to display the employee number, last name,
salary, and salary increased by 15.5% (expressed as a whole number) for each
employee. Label the column New Salary. Save your SQL statement in a file named
lab_04_02.sql.
3. Run your query in the lab_04_02.sql file.
4. Modify your query in lab_04_02.sql to add a column that subtracts the old salary
from the new salary. Label the column Increase. Save the contents of the file as
lab_04_04.sql. Run the revised query.
5. Perform the following tasks:
a. Write a query that displays the last name (with the first letter in uppercase
and all the other letters in lowercase) and the length of the last name for all
employees whose name starts with the letters “J,” “A,” or “M.” Give each column
an appropriate label. Sort the results by the employees‟ last names.
b. Rewrite the query so that the user is prompted to enter the letter that the last
name starts with. For example, if the user enters “H” (capitalized) when
prompted for a letter, the output should show all employees whose last name
starts with the letter “H.”
c. Modify the query such that the case of the letter that is entered does not
affect the output. The entered letter must be capitalized before being processed
by the SELECT query.
6. The HR department wants to find the duration of employment for each employee.
For each employee, display the last name and calculate the number of months between
today and the date on which the employee was hired. Label the column as
MONTHS_WORKED. Order your results by the number of months employed. The
number of months must be rounded to the closest whole number.

Thawzh818@gmail.com Page 49
Treasure Island Training Service Ph:09691011157

Note: Because this query depends on the date when it was executed, the values in the
MONTHS_WORKED column will differ for you.
7. Create a query to display the last name and salary for all employees. Format the
salary to be 15 characters long, left-padded with the $ symbol. Label the column
SALARY.
8.Create a query that displays the employees‟ last names, and indicates the amounts of
their salaries with asterisks. Each asterisk signifies a thousand dollars. Sort the data in
descending order of salary. Label the column EMPLOYEES_AND_THEIR_SALARIES.
9. Create a query to display the last name and the number of weeks employed for all
employees in department 90. Label the number of weeks column as TENURE. Truncate
the number of weeks value to 0 decimal places. Show the records in descending order
of the employee‟s tenure.
Note: The TENURE value will differ because it depends on the date on which you run
the query.

1 select sysdate "Date"


from dual;
2 select employee_id,last_name,salary,salary*1.155 "New Salary",
salary*.155 "Interest"
from hr.employees;
3 select employee_id,last_name,salary "Old Salary",salary*1.155 "New Salary",
salary*.155 "Interest"
from hr.employees;
4 select employee_id,last_name,salary "Old Salary",salary*1.155 "New Salary",
salary*.155 "Interest"
from hr.employees;
5(A) select initcap(last_name)
from hr.employees
where last_name like 'J%' or last_name like 'A%' or last_name like 'M%';

Thawzh818@gmail.com Page 50
Treasure Island Training Service Ph:09691011157

5(B) select *
from hr.employees
where last_name like '&FirstLetter%';
5(C) select *
from hr.employees
where lower(last_name) like lower('&FirstLetter%');
6 select last_name,months_between(sysdate,hire_date),
round(months_between(sysdate,hire_date)) "MONTHS_WORKED"
from hr.employees;
7 select last_name,lpad(salary,15,'$')
from hr.employees;
8 select last_name,lpad(' ',round(salary/1000),'*')
from hr.employees;
9 select last_name,round((sysdate-hire_date)/7) tenure
from hr.employees;

5.Using Conversion Functions and Conditional Expressions

5.1 Implicit Data Type Conversion

In expressions, the Oracle server can automatically convert the following:

Thawzh818@gmail.com Page 51
Treasure Island Training Service Ph:09691011157

1 SELECT employee_id, TO_CHAR(hire_date, 'MM/YY') Month_Hired


FROM employees
WHERE last_name = 'Higgins';

Thawzh818@gmail.com Page 52
Treasure Island Training Service Ph:09691011157

1 SELECT last_name, TO_CHAR(hire_date, 'fmDD Month YYYY') AS HIREDATE


FROM employees;
2 SELECT last_name,
TO_CHAR(hire_date, 'fmDdspth "of" Month YYYY fmHH:MI:SS AM') HIREDATE
FROM employees;

5.2 Using the TO_CHAR Function with Numbers

1 SELECT TO_CHAR(salary, '$99,999.00') SALARY


FROM employees
WHERE last_name = 'Ernst';
2 SELECT last_name, hire_date
FROM employees
WHERE hire_date = TO_DATE('May 24, 1999', 'fxMonth DD, YYYY');
3 SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')
FROM employees
WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');
4 SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-yyyy')
FROM employees
WHERE TO_DATE(hire_date, 'DD-Mon-yy') < '01-Jan-1990';

Thawzh818@gmail.com Page 53
Treasure Island Training Service Ph:09691011157

5.3 Nesting Functions


• Single-row functions can be nested to any level.
• Nested functions are evaluated from the deepest level to the least deep level.

1 SELECT last_name, UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))


FROM employees
WHERE department_id = 60;
SELECT TO_CHAR(NEXT_DAY(ADD_MONTHS (hire_date, 6), 'FRIDAY'),
'fmDay, Month ddth, YYYY') "Next 6 Month Review"
FROM employees
ORDER BY hire_date;

5.4 General Functions

These functions work with any data type and pertain to the use of null values in the
expression list.

Thawzh818@gmail.com Page 54
Treasure Island Training Service Ph:09691011157

1 Select nvl(commission_pct,0) ,commission_pct


from hr.employees;
2 Select NVL(hire_date,'01-JAN-97'),hire_date
from hr.emloyees;
3 Select nvl(job_id,‟No Job Yet‟) ,job_id
From hr.employees;
4 SELECT last_name, salary, commission_pct,
NVL2(commission_pct, 'SAL+COMM', 'SAL') income
FROM employees
WHERE department_id IN (50, 80);
5 SELECT first_name, LENGTH(first_name) "expr1", last_name,
LENGTH(last_name) "expr2", NULLIF(LENGTH(first_name),
LENGTH(last_name)) result
FROM employees;
6 SELECT last_name, employee_id, COALESCE(TO_CHAR(commission_pct),
TO_CHAR(manager_id), 'No commission and no manager')
FROM employees;
7 SELECT last_name, salary, commission_pct,
COALESCE((salary+(commission_pct*salary)),
salary+2000, salary) "New Salary"
FROM employees;

5.9 Using the CASE and DECODE Expression

Thawzh818@gmail.com Page 55
Treasure Island Training Service Ph:09691011157

1 SELECT last_name, job_id, salary,


CASE job_id
WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary END "REVISED_SALARY"
FROM employees;
2 SELECT last_name,salary,
(CASE WHEN salary <5000 THEN „low‟
WHEN salary< 10000 THEN 'Medium'
WHEN salary< 20000 THEN 'Good'
ELSE 'Excellent'
END) qualified_salary
FROM employees;
3 SELECT last_name, job_id, salary,
DECODE(job_id,
'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary) REVISED_SALARY
FROM employees;
4 SELECT last_name, salary,
DECODE (TRUNC(salary/2000, 0),
0, 0.00,
1, 0.09,
2, 0.20,
3, 0.30,
4, 0.40,
5, 0.42,
6, 0.44,
0.45) TAX_RATE

Thawzh818@gmail.com Page 56
Treasure Island Training Service Ph:09691011157

FROM employees
WHERE department_id = 80;

Practice 5-1: Using Conversion Functions and Conditional Expressions

1. Create a report that produces the following for each employee: <employee last
name> earns <salary> monthly but wants <3 times salary.>. Label the column
Dream Salaries.
2. Display each employee‟s last name, hire date, and salary review date, which is
the first Monday after six months of service. Label the column REVIEW. Format
the dates to appear in a format that is similar to “Monday, the Thirty-First of
July, 2000.”
3. Create a query that displays employees‟ last names and commission amounts. If
an employee does not earn commission, show “No Commission.” Label the
column COMM.
4. Using the CASE function, write a query that displays the grade of all employees
based on the value of the JOB_ID column, using the following data:

5. Rewrite the statement in the preceding exercise by using the searched CASE
syntax.
6. Rewrite the statement in the preceding exercise by using the searched DECODE
syntax.

1 Select last_name || 'earns '|| salary ||' monthly but wants ' || salary *3 ||'.'
"Dream Salaries "
From hr.employees ;
2 Select last_name,hire_date,to_char(next_day(add_months(hire_date,6)
,'Monday'),'Day ",the " ddspth "of " Month, yyyy') review
From hr.employees;
3 Select last_name,nvl(to_char(commission_pct) ,'No Commission')

Thawzh818@gmail.com Page 57
Treasure Island Training Service Ph:09691011157

from hr.employees;
4 SELECT last_name,salary, job_id,case
when job_id='AD_PRES' then 'Grade 1'
when job_id='AD_VP' then 'Grade 2'
when job_id='SA_MAN' then 'Grade 3'
when job_id='MK_MAN' then 'Grade 4'
when job_id='FI_MGR' then 'Grade 5'
when job_id='AC_MGR' then 'Grade 6'
when job_id='PU_MAN' then 'Grade 7'
when job_id='SA_REP' then 'Grade 8'
when job_id='ST_MAN' then 'Grade 9'
when job_id='PR_REP' then 'Grade 10'
when job_id='FI_ACCOUNT' then 'Grade 11'
when job_id='AC_ACCOUNT' then 'Grade 12'
when job_id='IT_PROG' then 'Grade 13'
when job_id='MK_REP' then 'Grade 14'
when job_id='HR_REP' then 'Grade 15'
when job_id='AD_ASST' then 'Grade 16'
when job_id='PU_CLERK' then 'Grade 17'
when job_id='SH_CLERK' then 'Grade 18'
when job_id='ST_CLERK' then 'Grade 19'
else 'Excellent' end Grade
from hr.employees;
5 SELECT last_name,salary, job_id,(case job_id
when 'AD_PRES' then 'Grade 1'
when 'AD_VP' then 'Grade 2'
when 'SA_MAN' then 'Grade 3'
when 'MK_MAN' then 'Grade 4'
when 'FI_MGR' then 'Grade 5'
when 'AC_MGR' then 'Grade 6'
when 'PU_MAN' then 'Grade 7'

Thawzh818@gmail.com Page 58
Treasure Island Training Service Ph:09691011157

when 'SA_REP' then 'Grade 8'


when 'ST_MAN' then 'Grade 9'
when 'PR_REP' then 'Grade 10'
when 'FI_ACCOUNT' then 'Grade 11'
when 'AC_ACCOUNT' then 'Grade 12'
when 'IT_PROG' then 'Grade 13'
when 'MK_REP' then 'Grade 14'
when 'HR_REP' then 'Grade 15'
when 'AD_ASST' then 'Grade 16'
when 'PU_CLERK' then 'Grade 17'
when 'SH_CLERK' then 'Grade 18'
when 'ST_CLERK' then 'Grade 19'
else 'Excellent' end) Grade
from hr.employees;
6 select last_name,salary,job_id,decode(job_id,
'AD_PRES' , 'Grade 1',
'AD_VP' , 'Grade 2',
'SA_MAN' , 'Grade 3',
'MK_MAN' , 'Grade 4',
'FI_MGR' , 'Grade 5',
'AC_MGR' , 'Grade 6',
'PU_MAN' , 'Grade 7',
'SA_REP' , 'Grade 8',
'ST_MAN' , 'Grade 9',
'PR_REP' , 'Grade 10',
'FI_ACCOUNT', 'Grade 11',
'AC_ACCOUNT', 'Grade 12',
'IT_PROG' , 'Grade 13',
'MK_REP' , 'Grade 14',
'HR_REP' , 'Grade 15',
'AD_ASST' , 'Grade 16',

Thawzh818@gmail.com Page 59
Treasure Island Training Service Ph:09691011157

'PU_CLERK' , 'Grade 17',


'SH_CLERK' , 'Grade 18',
'ST_CLERK' , 'Grade 19',
'Excellent') Greade
from hr.employees;

6.1 Reporting Aggregated Data Using the Group Functions

What Are Group Functions?


Group functions operate on sets of rows to give one result per group.

6.2 Types of Group Functions

1 SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary)


FROM employees
WHERE job_id LIKE '%REP%';
2 SELECT MIN(hire_date), MAX(hire_date)

Thawzh818@gmail.com Page 60
Treasure Island Training Service Ph:09691011157

FROM employees;
3 SELECT MIN(last_name), MAX(last_name)
FROM employees;
4 SELECT COUNT(*)
FROM employees
WHERE department_id = 50;
5 SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;
6 SELECT COUNT(DISTINCT department_id)
FROM employees;
7 SELECT AVG(commission_pct)
FROM employees;
8 SELECT AVG(NVL(commission_pct, 0))
FROM employees;

6.3 Using the GROUP BY Clause

1 SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id ;
2 SELECT AVG(salary)
FROM employees
GROUP BY department_id ;
3 SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id
ORDER BY AVG(salary);
4 SELECT department_id , job_id, SUM(salary)
FROM employees
GROUP BY department_id, job_id

Thawzh818@gmail.com Page 61
Treasure Island Training Service Ph:09691011157

ORDER BY department_id;
5 SELECT department_id, COUNT(last_name)
FROM employees;
6 SELECT department_id, job_id, COUNT(last_name)
FROM employees
GROUP BY department_id;
7 SELECT department_id, count(last_name)
FROM employees
GROUP BY department_id;
8 SELECT department_id, job_id, COUNT(last_name)
FROM employees
GROUP BY department_id, job_id;
9 SELECT department_id, AVG(salary)
FROM employees
WHERE AVG(salary) > 8000
GROUP BY department_id;
10 SELECT department_id, AVG(salary) avg_salary
FROM employees
WHERE avg_salary > 8000
GROUP BY department_id;

6.4 Using Having clause for group function

1 SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id
HAVING AVG(salary) > 8000;
2 SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 ;

Thawzh818@gmail.com Page 62
Treasure Island Training Service Ph:09691011157

3 SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id
HAVING max(salary)>10000;
4 SELECT job_id, SUM(salary) PAYROLL
FROM employees
WHERE job_id NOT LIKE '%REP%'
GROUP BY job_id
HAVING SUM(salary) > 13000
ORDER BY SUM(salary);

Nesting Group Functions

1 SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;

Practice 6-1: Reporting Aggregated Data by Using Group Functions Determine the
validity of the following statements. Circle either True or False.

1. Group functions work across many rows to produce one result per group.
True/False

2. Group functions include nulls in calculations. True/False

3. The WHERE clause restricts rows before inclusion in a group calculation. True/False

The HR department needs the following reports:

Thawzh818@gmail.com Page 63
Treasure Island Training Service Ph:09691011157

4. Find the highest, lowest, sum, and average salary of all employees. Label the
columns Maximum, Minimum, Sum, and Average, respectively. Round your results
to the nearest whole number. Save your SQL statement as lab_06_04.sql. Run the
query.

5. Modify the query in lab_06_04.sql to display the minimum, maximum, sum, and
average salary for each job type. Save lab_06_04.sql as lab_06_05.sql again. Run
the statement in lab_06_05.sql.

 Write a query to display the number of people with the same job.
Generalize the query so that the user in the HR department is prompted for a job title.
Save the script to a file named lab_06_06.sql. Run the query. Enter IT_PROG when
prompted.
 Determine the number of managers without listing them. Label the column Number of
Managers. Hint: Hint: Use the MANAGER_ID column to determine the number of
managers.
 Find the difference between the highest and lowest salaries. Label the column
DIFFERENCE.
 Create a report to display the manager number and the salary of the lowest-paid
employee for that manager. Exclude anyone whose manager is not known. Exclude any
groups where the minimum salary is $6,000 or less. Sort the output in descending order
of salary.
 Create a query to display the total number of employees and, of that total, the
number of employees hired in 2005, 2006, 2007, and 2008. Create appropriate column
headings
 Create a matrix query to display the job, the salary for that job based on the
department number, and the total salary for that job, for departments 20, 50, 80, and
90, giving each column an appropriate heading.

1 True
2 Flase

Thawzh818@gmail.com Page 64
Treasure Island Training Service Ph:09691011157

3 True
4 select max(salary) "Maximum",min(salary) "Minimum",sum(salary) "Sum" ,
avg(salary) "Average"
from hr.employees;
5(1) select job_id,count(job_id)
from employees
group by job_id;
5(1) select job_id,count(job_id)
from employees
where job_id='&EnterJob_id'
group by job_id;
5(2) select count (distinct nvl(manager_id,0))
from hr.employees;
5(3) select max(salary)-min(salary) difference
from hr.employees;
select manager_id,min(salary)
5(4) from hr.employees
where manager_id is not null
group by manager_id
having min(salary) not between 0 and 6000
order by min(salary);
5(5) select extract(year from hire_date), count(employee_id)
from hr.employees
where extract(year from hire_date) in (2005,2006,2007,2008)
group by extract(year from hire_date);
5(6) select job_id,department_id,sum(salary)
from hr.employees
where department_id in (20,50,80,90)
group by job_id,department_id;

Thawzh818@gmail.com Page 65
Treasure Island Training Service Ph:09691011157

7.1 Displaying Data from Multiple Tables

Use a join to query data from more than one table:

SELECT table1.column, table2.column


FROM table1, table2
WHERE table.column1=table2.column2;

 Write the join condition in the WHERE clause.


 Prefix the column name with the table name when the same column name
appears in more than one table.

7.2 Types of Joins

 Natural join
 Equijoin
 Nonequijoin
 Outer join
 Self-join
 Cross join

7.3 Qualifying Ambiguous Column Names

 Use table prefixes to qualify column names that are in multiple tables.
 Use table prefixes to improve performance.
 Use table aliases, instead of full table name prefixes.
 Table aliases give a table a shorter name.
– This keeps SQL code smaller and uses less memory.
 Use column aliases to distinguish columns that have identical names, but reside
in different tables

Thawzh818@gmail.com Page 66
Treasure Island Training Service Ph:09691011157

7.4 Natural Join


 The NATURAL JOIN clause is based on all the columns in the two tables that
have the same name.
 It selects rows from tables that have the same names and data values of
columns.
 Example:

SELECT country_id, location_id, country_name,city


FROM countries NATURAL JOIN locations;

7.5 Equijoins

7.6 Retrieving Records with Equijoins

SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id


FROM employees e JOIN departments d
ON e.department_id =d . epartment_ id;

7.7 Additional Search Conditions Using the AND and WHERE Operators

Thawzh818@gmail.com Page 67
Treasure Island Training Service Ph:09691011157

SELECT d.department_id, d.department_name, l.city


FROM departments d JOIN locations l
ON d.location_id = l.location_id
AND d.department__id IN (20, 50);

SELECT d.department_id, d.department_name, l.city


FROM departments d JOIN locations l
ON d.location_id = l.location_id
WHERE d.department_id IN (20, 50);

7.8 Retrieving Records with Nonequijoins

SELECT e.last_name, e.salary, j.grade_level


FROM employees e JOIN job_grades j
ON e.salary BETWEEN j.lowest_sal AND j.highest_sal;

7.9 Retrieving Records by Using the USING Clause

 You can use the USING clause to match only one column when more than one
column matches.
 You cannot specify this clause with a NATURAL join.
 Do not qualify the column name with a table name or table alias.
 Examples:

SELECT country_id, country_name, location_id, city


FROM countries JOIN locations
USING (country_id) ;

7.10 Retrieving Records by Using the ON Clause

Thawzh818@gmail.com Page 68
Treasure Island Training Service Ph:09691011157

 The join condition for the natural join is basically an equijoin of all columns with
the same name.
 Use the ON clause to specify arbitrary conditions or specify columns to join.
 The ON clause makes code easy to understand.

7.11 Left Outer Join

 A join between two tables that returns all matched rows, as well as the
unmatched rows from the left table is called a LEFT OUTER JOIN.
 Example:

SELECT c.country_id, c.country_name, l.location_id, l.city


FROM countries c LEFT OUTER JOIN locations l
ON (c.country_id = l.country_id) ;

7.12 Right Outer Join

 A join between two tables that returns all matched rows, as well as the
unmatched rows from the right table is called a RIGHT OUTER JOIN.
 Example:

SELECT e.last_name, d.department_id, d.department_name


FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

7.13 Full Outer Join

 A join between two tables that returns all matched rows, as well as the
unmatched rows from both tables is called a FULL OUTER JOIN.
 Example:

Thawzh818@gmail.com Page 69
Treasure Island Training Service Ph:09691011157

SELECT e.last_name, d.department_id, d.manager_id,d.department_name


FROM employees e FULL OUTER JOIN departments d
ON (e.manager_id = d.manager_id) ;

7.14 Self-Join: Example

SELECT worker.last_name || ' works for ' || manager.last_name


FROM employees worker JOIN employees manager
ON worker.manager_id=manager.employee_id
ORDER BY worker.last_name;

7.15 Cross Join

 A CROSS JOIN is a JOIN operation that produces the Cartesian product of two
tables.
 Example:

SELECT department_name, city


FROM department CROSS JOIN location;

create table table_a


(id int,
color VARCHAR(20));

create table table_b


(id int,
color VARCHAR(20));

insert into table_a values(1,'white');


insert into table_a values(2,'red');

Thawzh818@gmail.com Page 70
Treasure Island Training Service Ph:09691011157

insert into table_a values(3,'blue');


insert into table_a values(4,'black');

insert into table_b values(1,'white');


insert into table_b values(2,'red');
insert into table_b values(3,'purple');
insert into table_b values(4,'green');

1 SELECT department_id, department_name, location_id, city


FROM departments NATURAL JOIN locations ;
2 SELECT department_id, department_name, location_id, city
FROM departments NATURAL JOIN locations
WHERE department_id IN (20, 50);
3 SELECT employee_id, last_name, location_id, department_id
FROM employees JOIN departments
USING (department_id) ;
4 SELECT l.city, d.department_name
FROM locations l JOIN departments d
USING (location_id)
WHERE d.location_id = 1400;
5 SELECT l.city, d.department_name
FROM locations l JOIN departments d
USING (location_id)
WHERE location_id = 1400;
6 SELECT first_name, d.department_name, d.manager_id
FROM employees e JOIN departments d
USING (department_id)
WHERE department_id = 50;
7 SELECT e.employee_id, e.last_name, e.department_id, d.department_id,
d.location_id

Thawzh818@gmail.com Page 71
Treasure Island Training Service Ph:09691011157

FROM employees e JOIN departments d


ON (e.department_id = d.department_id);
8 SELECT employee_id, city, department_name
FROM employees e JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;
9 SELECT e.employee_id, l.city, d.department_name
FROM employees e JOIN departments d
USING (department_id)
JOIN locations l
USING (location_id)
10 SELECT e.employee_id, e.last_name, e.department_id, d.department_id,
d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
AND e.manager_id = 149 ;
11 SELECT e.employee_id, e.last_name, e.department_id, d.department_id,
d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
WHERE e.manager_id = 149 ;
12 SELECT worker.last_name emp, manager.last_name mgr
FROM employees worker JOIN employees manager
ON (worker.manager_id = manager.employee_id);
13 SELECT e.last_name, e.salary, j.grade_level
FROM employees e JOIN job_grades j
ON e.salary BETWEEN j.lowest_sal AND j.highest_sal;
14 SELECT e.last_name, e.department_id, d.department_name
FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

Thawzh818@gmail.com Page 72
Treasure Island Training Service Ph:09691011157

15 SELECT e.last_name, e.department_id, d.department_name


FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
16 SELECT e.last_name, d.department_id, d.department_name
FROM employees e FULL OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
17 SELECT last_name, department_name
FROM employees CROSS JOIN departments ;

Practices 7-1: Displaying Data from Multiple Tables by Using Joins

1. Write a query for the HR department to produce the addresses of all the
departments. Use the LOCATIONS and COUNTRIES tables. Show the location ID, street
address, city, state or province, and country in the output. Use a NATURAL JOIN to
produce the results.

2. The HR department needs a report of all employees with corresponding departments.


Write a query to display the last name, department number, and department name for
these employees.

3. The HR department needs a report of employees in Toronto. Display the last name,
job, department number, and the department name for all employees who work in
Toronto.

4. Create a report to display employees‟ last names and employee numbers along with
their managers‟ last names and manager numbers. Label the columns Employee,
Emp#, Manager, and Mgr#, respectively. Save your SQL statement as lab_07_04.sql.
Run the query.

Thawzh818@gmail.com Page 73
Treasure Island Training Service Ph:09691011157

5. Modify lab_07_04.sql to display all employees, including King, who has no manager.
Order the results by employee number. Save your SQL statement as lab_07_05.sql. Run
the query in lab_07_05.sql.

6. Create a report for the HR department that displays employee last names,
department numbers, and all the employees who work in the same department as a
given employee. Give each column an appropriate label. Save the script to a file named
lab_07_06.sql.

7. The HR department needs a report on job grades and salaries. To familiarize yourself
with the JOB_GRADES table, first show the structure of the JOB_GRADES table. Then
create a query that displays the name, job, department name, salary, and grade for all
employees.

8. The HR department wants to determine the names of all employees who were hired
after Davies. Create a query to display the name and hire date of any employee hired
after employee Davies.
9. The HR department needs to find the names and hire dates of all employees who
were hired before their managers, along with their managers‟ names and hire dates.
Save the script to a file named lab_07_09.sql.

1 select department_id,department_name,city,country_name
from hr.departments
natural join hr.locations
natural join hr.countries;
2 select last_name,department_id,department_name
from hr.employees natural join hr.departments;
3 select *
from hr.departments natural join hr.locations l
where l.city='Toronto';
4 select *

Thawzh818@gmail.com Page 74
Treasure Island Training Service Ph:09691011157

from hr.employees e , hr.departments d


on e.department_id=d.department_id;
5 select *
from hr.employees e left join hr.departments d
on e.department_id=d.department_id;
6 select * from hr.employees e ,hr.employees e1
where e.employee_id<>e1.employee_id
and e.department_id=e1.department_id;
7 select last_name,hire_date
from hr.employees e1
where e1.hire_date> (select hire_date
from hr.employees e2
where e2.last_name='Davies');
8 select e1.last_name,e1.hire_date
from hr.employees e1,hr.employees e2
where e1.employee_id<>e2.employee_id
and e2.last_name='Davies'
and e1.hire_date>e2.hire_date;
9 select
e.last_name,e.hire_date,e.manager_id,m.employee_id,m.last_name,m.hire_date
from hr.employees e join hr.employees m
on e.manager_id=m.employee_id
and e.hire_date<m.hire_date;

8.1 Oracle Subquery

There are three types of subqueries:


 Single-row subquery
 Multiple-row subquery

Single-Row Subquery

Thawzh818@gmail.com Page 75
Treasure Island Training Service Ph:09691011157

Single row subquery return zero or one row and one column.

Select * from employees


Where department_id = (select department_id from departments
Where department_name =‟Sales‟);

Multiple-Row Subquery

Multiple row subquery return zero or more rows and one column.

Select *
From Employees
Where department_id in (select department_id from departments
Where location_id=1700);

Multiple-Column Subqueries

Multiple column subqueries return zero or more rows and two or more columns.

Select * from employees


Where (manager_id,department_id) in (select manager_id,department_id
from departments );

1 SELECT MAX( list_price )


FROM products;
2 SELECT product_id, product_name, list_price
FROM products
WHERE list_price = 8867.99;
3 SELECT product_id, product_name, list_price
FROM products
WHERE list_price = (
SELECT MAX( list_price )

Thawzh818@gmail.com Page 76
Treasure Island Training Service Ph:09691011157

FROM products
);
4 SELECT product_name, list_price,
ROUND( ( SELECT AVG( list_price )
FROM products p1
WHERE p1. category_id = p2.category_id),2 ) avg_list_price
FROM products p2
ORDER BY product_name;
5 SELECT order_id, order_value
FROM
(
SELECT order_id, SUM( quantity * unit_price ) order_value
FROM order_items
GROUP BY order_id
ORDER BY order_value DESC
)
WHERE rownum >10;
6 SELECT product_id, product_name, list_price
FROM products
WHERE list_price > ( SELECT AVG( list_price )
FROM products
)
ORDER BY product_name;
7 SELECT employee_id, first_name, last_name
FROM employees
WHERE employee_id IN(
SELECT salesman_id
FROM orders
INNER JOIN order_items
USING(order_id)
WHERE status = 'Shipped'

Thawzh818@gmail.com Page 77
Treasure Island Training Service Ph:09691011157

GROUP BY salesman_id, EXTRACT(YEAR FROM order_date )


HAVING SUM( quantity * unit_price ) >= 1000000
AND EXTRACT( YEAR FROM order_date) = 2017
AND salesman_id IS NOT NULL
)
ORDER BY first_name, last_name;
8 SELECT name
FROM customers
WHERE customer_id NOT IN

( SELECT customer_id
FROM orders
WHERE EXTRACT( YEAR FROM order_date) = 2017
)
ORDER BY name;
9 SELECT department_name, city
FROM departments
NATURAL JOIN (SELECT l.location_id, l.city, l.country_id
FROM locations l
JOIN countries c
ON (l.country_id = c.country_id)
JOIN regions
USING (region_id)
WHERE region_name = 'Europe');
10 Select * from employees
Where department_id,manager_id in
(select department_id,manager_id
from departments);

Thawzh818@gmail.com Page 78
Treasure Island Training Service Ph:09691011157

8.2.1 Column Comparisons

Multiple-column comparisons involving subqueries can be:


 Pairwise comparisons
 Nonpairwise comparisons

8.3 Pairwise Comparison Subquery

Display the details of the employees who are managed by the same manager and work
in the same department as the employees with EMPLOYEE_ID 199 or 174.

SELECT employee_id, manager_id, department_id


From employees
WHERE (manager_id, department_id) IN (
SELECT manager_id,
department_id
FROM employees
WHERE employee_id IN (174,
199))
AND employee_id NOT IN (174,199);

8.4 Nonpairwise Comparison Subquery

Display the details of the employees who are managed by the same manager as the
employees with EMPLOYEE_ID 174 or 141 and work in the same department as the
employees with EMPLOYEE_ID 174 or 141.

SELECT employee_id, manager_id, department_id


FROM employees
WHERE manager_id IN (

Thawzh818@gmail.com Page 79
Treasure Island Training Service Ph:09691011157

SELECT manager_id
FROM employees
WHERE employee_id IN (174,141))
AND department_id IN (
SELECT department_id
FROM employees
WHERE employee_id IN (174,141))
AND employee_id NOT IN (174,141);

8.4 Scalar Subquery Expressions


 A scalar subquery expression is a subquery that returns exactly one column value
from one row.
 Scalar subqueries can be used in:
 The condition and expression part of DECODE and CASE
 All clauses of SELECT except GROUP BY
 The SET clause and WHERE clause of an UPDATE statement

8.5 Scalar Subqueries: Examples


 Scalar subqueries in CASE expressions:

SELECT employee_id, last_name, (CASE


WHEN department_id = (
SELECT department_id
FROM departments
WHERE location_id = 1800)
THEN 'Canada' ELSE 'USA' END) location
FROM employees;
 Scalar subqueries in the SELECT statement:

select department_id, department_name, (

Thawzh818@gmail.com Page 80
Treasure Island Training Service Ph:09691011157

select count(*)
from employees e
where e.department_id = d.department_id) as emp_count
from departments d;

8.6 Correlated Subqueries

Correlated subqueries are used for row-by-row processing. Each subquery is executed
once for every row of the outer query. The subquery references a column from a table
in the parent query.

SELECT column1, column2, ...


FROM table1 outer_table
WHERE column1 operator (
SELECT column1, column2
FROM table2
WHERE expr1 =outer_table.expr2);

8.7 Using Correlated Subqueries:

Example 1 Find all employees who earn more than the average salary in their
department.

SELECT last_name, salary, department_id


FROM employees outer_table
WHERE salary > (SELECT AVG(salary)
FROM employees inner_table
WHERE inner_table.department_id =outer_table.department_id);

8.8 Using Correlated Subqueries:

Thawzh818@gmail.com Page 81
Treasure Island Training Service Ph:09691011157

Example 2: Display details of highest earning employee in each department.

SELECT department_id, employee_id, salary


FROMEMPLOYEES e
WHERE 1 =
(SELECT COUNT(DISTINCT salary)
FROM EMPLOYEES
WHERE e.department_id = department_id
AND e.salary <= salary

8.9 Using the EXISTS Operator

 The EXISTS operator tests for existence of rows in the results set of the
subquery.
 If a subquery row value is found:
– The search does not continue in the inner query
– The condition is flagged TRUE
 If a subquery row value is not found:
– The condition is flagged FALSE
– The search continues in the inner query

SELECT employee_id, last_name, job_id, department_id


FROM employees outer
WHERE EXISTS ( SELECT NULL
FROM employees
WHERE manager_id =outer.employee_id);

8.10 Find All Departments That Do Not Have Any Employees

SELECT department_id, department_name

Thawzh818@gmail.com Page 82
Treasure Island Training Service Ph:09691011157

FROM departments d
WHERE NOT EXISTS (SELECT NULL
FROM employees
WHERE department_id = d.department_id);

8.11 WITH Clause

 Using the WITH clause, you can use the same query block in a SELECT
statement when it occurs more than once within a complex query.
 The WITH clause retrieves the results of a query block and stores it in the
user‟s temporary tablespace.
 The WITH clause may improve performance.
8.12 WITH Clause: Example

WITH CNT_DEPT AS
(
SELECT department_id,COUNT(1) NUM_EMP
FROM EMPLOYEES
GROUP BY department_id
)
SELECT employee_id, SALARY/NUM_EMP
FROM EMPLOYEES E JOIN CNT_DEPT C
ON (e.department_id = c.department_id);

8.13 Recursive WITH Clause

The Recursive WITH clause:


 Enables formulation of recursive queries
 Creates a query with a name, called the Recursive WITH element name
 Contains two types of query block members: an anchor and a recursive

Thawzh818@gmail.com Page 83
Treasure Island Training Service Ph:09691011157

 Is ANSI-compatible

8.14 Recursive WITH Clause: Example

CREATE TABLE flights (


source VARCHAR (20),
destin VARCHAR (20),
flight_time DECIMAL (10,2));

INSERT INTO FLIGHTS VALUES ('San Jose','Los Angeles',1.3);


INSERT INTO FLIGHTS VALUES ('New York','Boston',1.1);
INSERT INTO FLIGHTS VALUES ('Los Angeles','New York',5.8);

WITH Reachable_From (Source, Destin, TotalFlightTime)


AS (
SELECT Source,Destin,Flight_time FROM Flights

UNION ALL

SELECT incoming.Source,
outgoing.Destin,incoming.TotalFlightTime+outgoing.Flight_time
FROM Reachable_
From incoming, Flights outgoing
WHERE incoming.Destin = outgoing.Source

) SELECT Source, Destin, TotalFlightTime


FROM Reachable_From;

Quiz

Thawzh818@gmail.com Page 84
Treasure Island Training Service Ph:09691011157

With a correlated subquery, the inner SELECT statement drives the outer SELECT
statement.
a. True
b. False
Answer: b

Thawzh818@gmail.com Page 85
Treasure Island Training Service Ph:09691011157

Practices 8-1: Using Subqueries to Solve Queries

1. The HR department needs a query that prompts the user for an employee‟s last
name. The query then displays the last name and hire date of any employee in the
same department as the employee whose name the user supplies (excluding that
employee). For example, if the user enters Zlotkey, find all employees who work with
Zlotkey (excluding Zlotkey).

2. Create a report that displays the employee number, last name, and salary of all
employees who earn more than the average salary. Sort the results in ascending order
by salary.

3. Write a query that displays the employee number and last name of all employees
who work in a department with any employee whose last name contains the letter “u.”
Save your SQL statement as lab_08_03.sql. Run your query.

4. The HR department needs a report that displays the last name, department number,
and job ID of all employees whose department location ID is 1700. Modify the query so
that the user is prompted for a location ID. Save this to a file named lab_08_04.sql.

5. Create a report for HR that displays the last name and salary of every employee who
reports to King.

6. Create a report for HR that displays the department number, last name, and job ID
for every employee in the Executive department.

7. Create a report that displays a list of all employees whose salary is more than the
salary of any employee from department 60.

Thawzh818@gmail.com Page 86
Treasure Island Training Service Ph:09691011157

8. Modify the query in lab_08_03.sql to display the employee number, last name, and
salary of all employees who earn more than the average salary, and who work in a
department with any employee whose last name contains the letter “u.” Save
lab_08_03.sql as lab_08_08.sql again. Run the statement in lab_08_08.sql.

1 select *
from hr.employees
where lower(last_name)<>lower('&&name2')
and department_id in
(select department_id from hr.employees
where lower(last_name)=lower('&name2'))
;
2 select *
from hr.employees
where salary> (select avg(salary)
from hr.employees);
3 select employee_id,last_name
from hr.employees
where department_id in (select department_id
from hr.employees
where last_name like '%u%');
4 select * from hr.employees
where department_id in (select department_id
from hr.departments
where location_id=1700);
5 select * from hr.employees
where manager_id in (select employee_id
from hr.employees
where last_name='King');
6 select * from hr.employees

Thawzh818@gmail.com Page 87
Treasure Island Training Service Ph:09691011157

where department_id in (select department_id


from hr.departments
where department_name='Executive');
7 select * from hr.employees
where salary>all (select salary
from hr.employees
where department_id=60);
8 select * from hr.employees
where salary >all (select salary
from hr.employees
where last_name like '%u%');

9.1 Oracle UNION

The UNION operator is a set operator that combines result sets of two or more SELECT
statements into a single result set.

The following illustrates the syntax of the UNION operator that combines the result sets
of two queries:

SELECT column_list_1
FROM T1
UNION
SELECT column_list_1
FROM T2;

In this statement, the column_list_1 and column_list_2 must have the same number of
columns presented in the same order. In addition, the data type of the corresponding
column must be in the same data type group such as number or character.

By default, the UNION operator returns the unique rows from both result sets. If you
want to retain the duplicate rows, you explicitly use UNION ALL as follows:

Thawzh818@gmail.com Page 88
Treasure Island Training Service Ph:09691011157

SELECT column_list
FROM T1
UNION ALL
SELECT column_list
FROM T2;

9.2 Oracle UNION illustration

Suppose, we have two tables T1 and T2:

 T1 has three rows 1, 2 and 3


 T2 also has three rows 2, 3 and 4

The following picture illustrates the UNION of T1 and T2 tables:

The UNION removed the duplicate rows 2 and 3

The following picture illustrates the result of the UNION ALL of the T1 and T2 tables:

As you can see, the UNION ALL retains the duplicate rows 2 and 3.

2.35 Oracle UNION examples

See the following employees and contacts tables in the sample database.

Thawzh818@gmail.com Page 89
Treasure Island Training Service Ph:09691011157

A) Oracle UNION example

Suppose, you have to send out emails to the email addresses from both employees
and contacts tables. To accomplish this, first, you need to compose a list of email
addresses of employees and contacts. And then send out the emails to the list.

The following statement uses the UNION operator to build a list of contacts from the
employees and contacts tables:

SELECT first_name, last_name, email, 'contact'


FROM contacts
UNION SELECT first_name, last_name, email, 'employee'
FROM employees;

B) Oracle UNION and ORDER BY example

To sort the result set returned by the UNION operator, you add an ORDER BY clause to
the last SELECT statement as shown below:

SELECT first_name || ' ' || last_name name, email, 'contact'


FROM contacts
UNION SELECT first_name || ' ' || last_name name, email, 'employee'
FROM employees

Thawzh818@gmail.com Page 90
Treasure Island Training Service Ph:09691011157

ORDER BY name DESC;

In this example, we sorted the list by name concatenated from the first and last names.

C) Oracle UNION ALL example

The following statement returns the unique last names of employees and contacts:

SELECT last_name
FROM employees
UNION SELECT last_name
FROM contacts
ORDER BY last_name;

However, if you use UNION ALL instead of UNION in the query as follows:

SELECT last_name
FROM employees
UNION ALL SELECT last_name
FROM contacts
ORDER BY last_name;

9.3 Oracle UNION vs. JOIN

A UNION places a result set on top another, meaning that it appends result sets
vertically. However, a join such as INNER JOIN or LEFT JOIN combines result sets
horizontally.

The following picture illustrates the difference between union and join:

Thawzh818@gmail.com Page 91
Treasure Island Training Service Ph:09691011157

9.4 Oracle INTERSECT

The Oracle INTERSECT operator compares the result of two queries and returns the
distinct rows that are output by both queries.

The following statement shows the syntax of the INTERSECT operator:

SELECT column_list_1
FROM T1
INTERSECT
SELECT column_list_2
FROM T2;

Similar to the UNION operator, you must follow these rules when using the INTERSECT
operator:

 The number and the order of columns must be the same in the two queries.
 The data type of the corresponding columns must be in the same data type
group such as numeric or character.

9.5 Oracle INTERSECT illustration

Suppose we have two queries that return the T1 and T2 result set.

 T1 result set includes 1, 2, 3.

Thawzh818@gmail.com Page 92
Treasure Island Training Service Ph:09691011157

 T2 result set includes 2, 3, 4.

The intersect of T1 and T2 result returns 2 and 3. Because these are distinct values that
are output by both queries.

The following picture illustrates the intersection of T1 and T2:

The illustration showed that the INTERSECT returns the intersection of two circles (or
sets).

9.6 Oracle INTERSECT example

See the following contacts and employees tables in the sample database.

The following statement uses the INTERSECT operator to get the last names used by
people in both contacts and employees tables:

SELECT last_name
FROM contacts
INTERSECT
SELECT last_name
FROM employees

Thawzh818@gmail.com Page 93
Treasure Island Training Service Ph:09691011157

ORDER BY last_name;

Note that we placed the ORDER BY clause at the last queries to sort the result set
returned by the INTERSECT operator.

9.7 Oracle MINUS

The Oracle MINUS operator compares two queries and returns distinct rows from the
first query that are not output by the second query. In other words, the MINUS
operator subtracts one result set from another.

The following illustrates the syntax of the Oracle MINUS operator:

SELECT column_list_1
FROM T1
MINUS
SELECT column_list_2
FROM T2;

Similar to the UNION and INTERSECT operators, the queries above must conform with
the following rules:

 The number of columns and their orders must match.


 The data type of the corresponding columns must be in the same data type
group such as numeric or character.

Suppose the first query returns the T1 result set that includes 1, 2 and 3. And the
second query returns the T2 result set that includes 2, 3 and 4.

The following picture illustrates the result of the MINUS of T1 and T2:

Thawzh818@gmail.com Page 94
Treasure Island Training Service Ph:09691011157

Oracle MINUS examples

See the following contacts and employees tables in the sample database:

The following statement returns distinct last names from the query to the left of the
MINUS operator which are not also found in the right query.

SELECT last_name
FROM contacts
MINUS
SELECT last_name
FROM employees
ORDER BY last_name;

Here are the last names returned by the first query but are not found in the result set
of the second query:

See the following products and inventories tables:

Thawzh818@gmail.com Page 95
Treasure Island Training Service Ph:09691011157

The following statement returns a list of product id from the products table, but do not
exist in the inventories table:

SELECT product_id
FROM products
MINUS
SELECT product_id
FROM inventories;

Thawzh818@gmail.com Page 96
Treasure Island Training Service Ph:09691011157

Practices 9-1: Using the Set Operators


1. The HR department needs a list of department IDs for departments that do not
contain the job ID ST_CLERK. Use the set operators to create this report.
2. The HR department needs a list of countries that have no departments located in
them. Display the country IDs and the names of the countries. Use the set operators to
create this report.
3. Produce a list of all the employees who work in departments 50 and 80. Display the
employee ID, job ID, and department ID by using the set operators.
4. Create a report that lists the detail of all employees who are sales representatives
and are currently working in the sales department.
5. The HR department needs a report with the following specifications:
• Last names and department IDs of all employees from the EMPLOYEES table,
regardless of whether or not they belong to a department
• Department IDs and department names of all departments from the DEPARTMENTS
table, regardless of whether or not they have employees working in them Write a
compound query to accomplish this report
1 select department_id
from hr.departments
minus
select department_id
from hr.employees
where job_id='ST_CLERK';
2 select country_id,country_name
from hr.countries

Thawzh818@gmail.com Page 97
Treasure Island Training Service Ph:09691011157

minus
select country_id,country_name
from hr.departments natural join hr.locations
natural join hr.countries;
3 select * from hr.employees
where department_id=50
union all
select * from hr.employees
where department_id=80;
4 select employee_id from hr.employees where job_id='SA_REP'
intersect
select employee_id from hr.employees where department_id=80;
5 SELECT last_name,department_id,TO_CHAR(null)dept_name
FROM employees
UNION
SELECT TO_CHAR(null),department_id,department_name
FROM departments;

10.1 Oracle Data Types

Code Data Type

1 VARCHAR2(size [BYTE | CHAR])

1 NVARCHAR2(size)

2 NUMBER[(precision [, scale]])

8 LONG

12 DATE

Thawzh818@gmail.com Page 98
Treasure Island Training Service Ph:09691011157

21 BINARY_FLOAT

22 BINARY_DOUBLE

23 RAW(size)

24 LONG RAW

69 ROWID

96 CHAR [(size [BYTE | CHAR])]

96 NCHAR[(size)]

112 CLOB

112 NCLOB

113 BLOB

114 BFILE

180 TIMESTAMP [(fractional_seconds)]

181 TIMESTAMP [(fractional_seconds)] WITH TIME ZONE

182 INTERVAL YEAR [(year_precision)] TO MONTH

183 INTERVAL DAY [(day_precision)] TO SECOND[(fractional_seconds)]

208 UROWID [(size)]

231 TIMESTAMP [(fractional_seconds)] WITH LOCAL TIMEZONE

Thawzh818@gmail.com Page 99
Treasure Island Training Service Ph:09691011157

10.2 NUMBER[(precision [, scale])]

1. NUMBER
2. NUMBER(p,s)
3. NUMBER(p)
4. NUMBER(p,0)
5. NUMBER(5,-2)

1 CREATE TABLE number_demo (


number_value NUMERIC(6, 2)
);
2 INSERT INTO number_demo
VALUES(100.99);
3 INSERT INTO number_demo
VALUES(90.551);
INSERT INTO number_demo
VALUES(87.556);
4 INSERT INTO number_demo
VALUES(-10000);
5 INSERT INTO number_demo
VALUES(9999.999);

10.3 Introduction to Oracle FLOAT data type


1 CREATE TABLE float_demo (
f1 FLOAT(1),
f2 FLOAT(4),
f3 FLOAT(7)
);
2 INSERT INTO float_demo( f1, f2, f3 )

Thawzh818@gmail.com Page 100


Treasure Island Training Service Ph:09691011157

VALUES( 1 / 3, 1 / 3, 1/3 );
3 SELECT *
FROM float_demo;

10.4 Oracle Identity Column

 GENERATED ALWAYS: Oracle always generates a value for the identity column.
Attempt to insert a value into the identity column will cause an error.
 GENERATED BY DEFAULT: Oracle generates a value for the identity column if you
provide no value. If you provide a value, Oracle will insert that value into the
identity column. For this option, Oracle will issue an error if you insert a NULL
value into the identity column.
 GENERATED BY DEFAULT ON NULL: Oracle generates a value for the identity
column if you provide a NULL value or no value at all.

1 CREATE TABLE identity_demo (


id NUMBER GENERATED ALWAYS AS IDENTITY,
description VARCHAR2(100) NOT NULL);
2 INSERT INTO identity_demo(description)
VALUES('Oracle identity column demo with GENERATED ALWAYS');
3 SELECT *
FROM identity_demo;
4 INSERT INTO identity_demo(id,description)
VALUES(2, 'Oracle identity column example with GENERATED ALWAYS ');
5
CREATE TABLE identity_demo1 (
id NUMBER GENERATED BY DEFAULT AS IDENTITY,
description VARCHAR2(100) not null
);
6 INSERT INTO identity_demo1(description)
VALUES('Oracle identity column demo with GENERATED BY DEFAULT');
7 INSERT INTO identity_demo1(id,description)

Thawzh818@gmail.com Page 101


Treasure Island Training Service Ph:09691011157

VALUES(2, 'Oracle identity column example with GENERATED BY DEFAULT');


8 SELECT *
FROM identity_demo1;
9 INSERT INTO identity_demo1(id,description)
VALUES(NULL,'Oracle identity column demo with GENERATED BY DEFAULT, NULL
value');
10 CREATE TABLE identity_demo2 (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
description VARCHAR2(100) not null
);
11 INSERT INTO identity_demo2(description)
VALUES('Oracle identity column demo with no value');
12 INSERT INTO identity_demo2(description)
VALUES('Oracle identity column demo with null');
13 CREATE TABLE identity_demo3 (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY START WITH
100,
description VARCHAR2(100) not null
);
14 INSERT INTO identity_demo3(description)
VALUES('Oracle identity column demo with START WITH option');
15
SELECT *
FROM identity_demo3;

16 CREATE TABLE identity_demo4 (


id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY START WITH 10
INCREMENT BY 10,
description VARCHAR2(100) not null
);
17 INSERT INTO identity_demo4(description)
VALUES('Oracle identity column demo 1 with INCREMENT BY option');

Thawzh818@gmail.com Page 102


Treasure Island Training Service Ph:09691011157

18 INSERT INTO identity_demo4(description)


VALUES('Oracle identity column demo 2 with INCREMENT BY option');
19 SELECT * FROM
identity_demo4;

10.5 Introduction to Oracle CHAR data type


CHAR(length BYTE)
CHAR(length CHAR)
1 CREATE TABLE t (
x CHAR(10),
y VARCHAR2(10) );
2 INSERT INTO t(x, y ) VALUES('Oracle', 'Oracle');
3 SELECT * FROM t;
4 SELECT x, DUMP(x), y, DUMP(y)
FROM t;
5 SELECT LENGTHB(x), LENGTHB(y)
FROM t;
6 SELECT * FROM t WHERE x = 'Oracle';
SELECT * FROM t WHERE y = 'Oracle';

10.6 Overview of Oracle NCHAR data type

1 CREATE TABLE nchar_demo (


description NCHAR(10) );
2 description NCHAR(10 BYTE) -- not possible

10.8 Introduction to Oracle NVARCHAR2 data type


1 CREATE TABLE nvarchar2_demo (
description NVARCHAR2(50) );

Thawzh818@gmail.com Page 103


Treasure Island Training Service Ph:09691011157

2 INSERT INTO nvarchar2_demo VALUES('ABCDE');

Oracle date format


3 SELECT sysdate
FROM dual;
4 ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';
5 SELECT sysdate FROM dual;
6 SELECT value
FROM V$NLS_PARAMETERS
WHERE parameter = 'NLS_DATE_LANGUAGE';
7 ALTER SESSION SET NLS_DATE_LANGUAGE = 'FRENCH';
8 SELECT TO_CHAR( SYSDATE, 'FMMonth DD, YYYY' )
FROM dual;
9 ALTER SESSION SET NLS_DATE_LANGUAGE = 'AMERICAN';
10 CREATE TABLE my_events (
event_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
event_name VARCHAR2 ( 255 ) NOT NULL,
location VARCHAR2 ( 255 ) NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
PRIMARY KEY ( event_id ) );
11 INSERT INTO my_events (event_name, location, start_date, end_date)
VALUES ( 'TechEd Europe', 'Barcelona, Spain', DATE '2017-11-14', DATE '2017-11-
16' );
12 INSERT INTO my_events (event_name,location, start_date, end_date)
VALUES ( 'Oracle OpenWorld', 'San Francisco, CA, USA',
TO_DATE( 'October 01, 2017', 'MONTH DD, YYYY' ),
TO_DATE( 'October 05, 2017', 'MONTH DD, YYYY'));
13 INSERT INTO my_events (event_name, location, start_date, end_date)
VALUES ( 'TechEd US', 'Las Vegas, NV, USA' DATE '2017-09-25', DATE '2017-09-
29' );

Thawzh818@gmail.com Page 104


Treasure Island Training Service Ph:09691011157

14 SELECT *
FROM my_events;
15 SELECT event_name, location, TO_CHAR( start_date, 'FMMonth DD, YYYY' )
start_date, TO_CHAR( end_date, 'FMMonth DD, YYYY' ) end_date
from my_events;

Oracle TIMESTAMP
1 CREATE TABLE logs (
log_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
message VARCHAR(2) NOT NULL,
logged_at TIMESTAMP (2) NOT NULL,
PRIMARY KEY (log_id) );
INSERT INTO logs ( message, logged_at )
2 VALUES ( 'Invalid username/password for root user', LOCALTIMESTAMP(2) );

INSERT INTO logs ( message, logged_at ) VALUES ( 'User root logged in


successfully', LOCALTIMESTAMP(2) )
3 SELECT log_id, message, logged_at
FROM logs;
4 SELECT message, TO_CHAR(logged_at, 'MONTH DD, YYYY "at" HH24:MI')
FROM logs;
5 SELECT message,
EXTRACT(year FROM logged_at) year,
EXTRACT(month FROM logged_at) month,
EXTRACT(day FROM logged_at) day,
EXTRACT(hour FROM logged_at) hour,
EXTRACT(minute FROM logged_at) minute,
EXTRACT(second FROM logged_at) second
FROM logs;
6 INSERT INTO logs ( message, logged_at )
VALUES ( 'Test default Oracle timestamp format', TO_TIMESTAMP('03-AUG-17

Thawzh818@gmail.com Page 105


Treasure Island Training Service Ph:09691011157

11:20:30.45 AM') );
7 SELECT log_id, message, logged_at
FROM logs;
8 SELECT DECODE( TIMESTAMP '1999-01-15 8:00:00 -8:00', TIMESTAMP '1999-01-
15 11:00:00 -5:00', 'Equal', 'Not Equal' )
FROM dual;
9 CREATE TABLE logs (
log_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
log_message VARCHAR2(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY(log_id) );
10 SELECT SESSIONTIMEZONE
FROM dual;
11 INSERT INTO logs(log_message, created_at)
VALUES('Insert a timestamp',TIMESTAMP '2017-08-08 2:00:00');
12 SELECT * FROM logs;
13 INSERT INTO logs(log_message, created_at)
VALUES('Insert a timestamp with timezone as a character string','08-AUG-2017
2:00:00 PM -05:00');
14 INSERT INTO logs(log_message, created_at)
VALUES('Insert a timestamp with time zone literal',TIMESTAMP '2017-08-08
2:00:00 -08:00');
15 INSERT INTO logs(log_message, created_at)
VALUES('Use current_timestamp function',CURRENT_TIMESTAMP);

10.9 Oracle Constraints


Introduction to Oracle PRIMARY KEY

The following are rules that make a column a primary key:


• A primary key column cannot contain a NULL value or an empty string.

Thawzh818@gmail.com Page 106


Treasure Island Training Service Ph:09691011157

• A primary key value must be unique within the entire table.


• A primary key value should not be changed over time.
Creating a primary key that consists of one column

Introduction to Oracle foreign key constraint

 Foreign key value is reference on primary key


 Foreign key column can insert null value.

Introduction to Oracle unique key constraint

 Unique key value doesn‟t duplicate.


 Unique key column can insert null value

Introduction to Oracle not null constraint

 Unique key column can not insert null value

create table emp_thaw


(id integer primary key,
first_name varchar2(20),
last_name varchar2(20) not null,
email varchar2(20) unique,
salary number(6) check (salary>0),
department_id integer ,
foreign key (department_id) references departments(department_id));
create table emp_thaw2
(id integer ,
first_name varchar2(20),
last_name varchar2(20) not null,
email varchar2(20) ,
salary number(6) ,

Thawzh818@gmail.com Page 107


Treasure Island Training Service Ph:09691011157

department_id integer ,
primary key(id),
unique(email),
check (salary >0),
foreign key (department_id) references dept(department_id));
create table emp_thaw3
(id integer constraint emp_thaw_pk primary key,
first_name varchar2(20),
last_name varchar2(20) constraint emp_ln_nn not null,
email varchar2(20) constraint emp_email_u unique,
salary number(6) constraint sal_c check (salary>0),
department_id integer ,
constraint thaw_dept_fk foreign key (department_id) references
dept(department_id));
create table emp_thaw4
(id integer ,
first_name varchar2(20),
last_name varchar2(20) constraint thaw_ln_nn not null,
email varchar2(20) ,
salary number(6) ,
department_id integer ,
constraint thaw_id_pk primary key(id),
constraint thaw_email_u unique(email),
constraint thaw_sal_c check (salary >0),
constraint thaw_dept2_fk foreign key (department_id) references
dept(department_id));
create table emp_thaw5
(id integer ,
first_name varchar2(20),
last_name varchar2(20),
email varchar2(20) ,
salary number(6) ,

Thawzh818@gmail.com Page 108


Treasure Island Training Service Ph:09691011157

department_id integer);
alter table emp_thaw5 add primary key(id);

alter table emp_thaw5 add unique(email);

alter table emp_thaw5 add check(salary >0);

alter table emp_thaw5 add foreign key(department_id) references


dept(department_id);

alter table emp_thaw5 modify last_name not null;


create table emp_thaw6
(id integer ,
first_name varchar2(20),
last_name varchar2(20),
email varchar2(20) ,
salary number(6) ,
department_id integer);

alter table emp_thaw6 add constraint id_pk primary key(id);

alter table emp_thaw6 add constraint email_u unique(email);

alter table emp_thaw6 add constraint sal_c_thaw check(salary >0);

alter table emp_thaw6 add constraint dep_id_fk foreign key(department_id)


references dept(department_id);

alter table emp_thaw6 modify last_name not null;


select * from user_constraints where table_name='EMP_THAW';

Thawzh818@gmail.com Page 109


Treasure Island Training Service Ph:09691011157

alter table emp_thaw6 disable constraint sys_c0011020;

alter table emp_thaw6 disable constraint sys_c0011021;

alter table emp_thaw6 disable constraint sys_c0011022;

alter table emp_thaw6 disable constraint sys_c0011023;

alter table emp_thaw6 disable constraint sys_c0011024;


select * from user_constraints where table_name='EMP_THAW';

alter table emp_thaw6 enable constraint sys_c0011020;

alter table emp_thaw6 enable constraint sys_c0011021;

alter table emp_thaw6 enable constraint sys_c0011022;

alter table emp_thaw6 enable constraint sys_c0011023;

alter table emp_thaw6 enable constraint sys_c0011024;

10.10 Using Constraints

select * from dept;

insert into dept values (1,'it',1,1);

insert into dept values (2,'hr',1,1);

select * from emp_thaw;

select * from user_constraints where table_name='EMP_THAW';

Thawzh818@gmail.com Page 110


Treasure Island Training Service Ph:09691011157

insert into emp_thaw values (1,'thaw','thaw','thaw@gmail.com',10000,1);


insert into emp_thaw values (2,'treasure','treasure','treasure@gmail.com',10000,1);
insert into emp_thaw values (3,'win','win','win@gmail.com',10000,2);
insert into emp_thaw values (3,'win','win','win@gmail.com',10000,3);

commit;

delete from dept where department_id=1;

10.11 TRUNCATE TABLE Statement


 Use the TRUNCATE TABLE statement to remove all the rows from a table.
 Example:

TRUNCATE TABLE employees_demo;

 By default, Oracle Database performs the following tasks:


– Deallocates space used by the removed rows
– Sets the NEXT storage parameter to the size of the last TRUNCATE TABLE
employees_demo;
extent removed from the segment by the truncation process

10.12 Data Manipulation Language


 DML statements query or manipulate data in the existing schema objects.
 A DML statement is executed when:
– New rows are added to a table by using the INSERT statement
– Existing rows in a table are modified using the UPDATE statement
– Existing rows are deleted from a table by using the DELETE statement
 A transaction consists of a collection of DML statements that form a logical unit
of work.

Thawzh818@gmail.com Page 111


Treasure Island Training Service Ph:09691011157

10.13 INSERT Statement

 Use the INSERT statement to add new rows to a table.


 Example:

INSERT INTO departments VALUES (200,'Development',104,1400);

10.14 UPDATE Statement Syntax

 Use the UPDATE statement to modify the existing rows in a table.


 Update more than one row at a time (if required).
 Specify SET column_name= NULL to update a column value to NULL

UPDATE employees
SET salary = 17500
WHERE employee_id = 102;

10.15 DELETE Statement


 Use the DELETE statement to delete the existing rows from a table.
 Write the DELETE statement using the WHERE clause to delete specific rows
from a table.

Delete from departments;


Delete departments;

DELETE FROM departments Where Department_name = „Finance‟ ;


SELECT * FROM departments WHERE department_name = 'Finance';

10.16 Transaction Control Statements

Thawzh818@gmail.com Page 112


Treasure Island Training Service Ph:09691011157

 Transaction control statements are used to manage the changes made by DML
statements.
 The DML statements are grouped into transactions.
 Transaction Control statement include:

– COMMIT
– ROLLBACK
– SAVEPOINT

INSERT INTO departments VALUES (201, 'Engineering', 106, 1400);

COMMIT;

10.16 ROLLBACK Statement

 Use the ROLLBACK statement to undo changes made to the database during the
current transaction.
 Use the TO SAVEPOINT clause to undo a part of the transaction after the
savepoint.
 Example:
UPDATE employees
SET salary = 7000
WHERE last_name = 'Ernst';

SAVEPOINT Ernst_sal;

UPDATE employees
SET salary = 12000
WHERE last_name = 'Mourgos';

ROLLBACK TO SAVEPOINT Ersnt_sal;

Thawzh818@gmail.com Page 113


Treasure Island Training Service Ph:09691011157

10.17 SAVEPOINT Statement

 Use the SAVEPOINT statement to name and mark the current point in the
processing of a transaction.
 Specify a name to each savepoint.
 Use distinct savepoint names within a transaction to avoid overriding.
 Syntax:

SAVEPOINT savepoint;

Practice 10-1: Managing Tables by Using DML Statements

The HR department wants you to create SQL statements to insert, update, and delete
employee data. As a prototype, you use the MY_EMPLOYEE table before giving the
statements to the HR department.

1. Create a table called MY_EMPLOYEE.

2. Describe the structure of the MY_EMPLOYEE table to identify the column names.

3. Create an INSERT statement to add the first row of data to the MY_EMPLOYEE table
from the following sample data. Do not list the columns in the INSERT clause. Do not
enter all rows yet.

4. Populate the MY_EMPLOYEE table with the second row of the sample data from the
preceding list. This time, list the columns explicitly in the INSERT clause.

5. Confirm your addition to the table.

6. Write an INSERT statement in a dynamic reusable script file to load the remaining
rows into the MY_EMPLOYEE table. The script should prompt for all the columns (ID,

Thawzh818@gmail.com Page 114


Treasure Island Training Service Ph:09691011157

LAST_NAME, FIRST_NAME, USERID, and SALARY). Save this script to a lab_10_06.sql


file.

7. Populate the table with the next two rows of the sample data listed in step 3 by
running the INSERT statement in the script that you created.

8. Confirm your additions to the table.

9. Make the data additions permanent. Update and delete data in the MY_EMPLOYEE
table.

10. Change the last name of employee 3 to Drexler.

11. Change the salary to $1,000 for all employees who have a salary less than $900.

12. Verify your changes to the table.

13. Delete Betty Dancs from the MY_EMPLOYEE table.

14. Confirm your changes to the table. 15. Commit all pending changes.

16. Populate the table with the last row of the sample data listed in step 3 by using the
statements in the script that you created in step 6. Run the statements in the script.
Note: Perform the steps (17-23) in one session only.

17. Confirm your addition to the table.

18. Mark an intermediate point in the processing of the transaction.

19. Delete all the rows from the MY_EMPLOYEE table.

20. Confirm that the table is empty.

21. Discard the most recent DELETE operation without discarding the earlier INSERT
operation.

Thawzh818@gmail.com Page 115


Treasure Island Training Service Ph:09691011157

22. Confirm that the new row is still intact.

23. Make the data addition permanent.

24. Modify the lab_10_06.sql script such that the USERID is generated automatically by
concatenating the first letter of the first name and the first seven characters of the last
name. The generated USERID must be in lowercase. Therefore, the script should not
prompt for the USERID. Save this script to a file named lab_10_24.sql.

25. Run the lab_10_24.sql script to insert the following record:

26. Confirm that the new row was added with the correct USERID.
1 create table my_employee

as select *

from hr.employees

where 1=2;
2 desc my_employee;
3 insert into my_employee values (1,null,'thaw','thaw@gmail.com',null,to_date('20-
Dec-2020','DD-Mon-yyyy'),'IT',null,null,null,null);
4 insert into my_employee(employee_id,last_name,email,hire_date,job_id)

values (2,'zin','zin@gmail.com',to_date('20-Dec-2020','DD-Mon-yyyy'),'IT');
5 select * from my_employee;
6 insert into my_employee

values
(&employee_id,'&first_name','&last_name','&emailOrUser_id',&salary,to_date('20-
Dec-2020','DD-Mon-yyyy'),'IT',null,null,null,null);
7 insert into my_employee

values (4,null,'tay','tay@gmail.com',null,to_date('20-Dec-2020','DD-Mon-

Thawzh818@gmail.com Page 116


Treasure Island Training Service Ph:09691011157

yyyy'),'IT',null,null,null,null);
8 insert into my_employee

values (5,null,'ei','ei@gmail.com',null,to_date('20-Dec-2020','DD-Mon-
yyyy'),'IT',null,null,null,null);
9 select * from my_employee;
1 commit;
0
1 update my_employee
1
set last_name='Drexler'

where employee_id=3;
1 update my_employee
2
set salary=1000

where salary<900;
1 select * from my_employee;
3
1 delete from my_employee where last_name='Betty Dancs';
4
1 select * from my_employee;
5
1 commit;
6
1 insert into my_employee
7
values (8,null,'cho','cho@gmail.com',null,to_date('20-Dec-2020','DD-Mon-
yyyy'),'IT',null,null,null,null);
1 insert into my_employee
8
values

Thawzh818@gmail.com Page 117


Treasure Island Training Service Ph:09691011157

(&employee_id,'&first_name','&last_name','&emailOrUser_id',&salary,to_date('20-
Dec-2020','DD-Mon-yyyy'),'IT',null,null,null,null);
1 select * from my_employee;
9
2 savepoint a;
0
2 delete from my_employee;
1
2 select * from my_employee;
2
2 rollback to savepoint a;
3
2 select * from my_employee;
4
2 commit;
5
2 insert into my_employee
6
values
(&employee_id,'&&first_name','&&last_name',lower(substr('&first_name',1,1)||subs
tr('&last_name',1,7)),&salary,to_date('20-Dec-2020','DD-Mon-
yyyy'),'IT',null,null,null,null);
select * from my_employee;

11.1 Introdution to Data Dictionary Views

Thawzh818@gmail.com Page 118


Treasure Island Training Service Ph:09691011157

11.2 Data Dictionary Structure

View naming convention:

View Prefix Purpose

USER User‟s view (what is in your schema: what you own

ALL Expanded user‟s view (what you can access)

DBA Database administrator‟s view (what is in everyone‟s schemas)

V$ Performance-related data

11.3 How to Use the Dictionary Views

Start with DICTIONARY. It contains the names and descriptions of the dictionary
tables and views.

DESCRIBE DICTIONARY;

Thawzh818@gmail.com Page 119


Treasure Island Training Service Ph:09691011157

SELECT *
From dictionary
WHERE table_name = 'USER_OBJECTS';

11.4 USER_OBJECTS and ALL_OBJECTS Views


USER_OBJECTS:
 Query USER_OBJECTS to see all the objects that you own.
 Using USER_OBJECTS, you can obtain a listing of all object names and
types in your schema, plus the following information:
 Date created
 Date of last modification
Status (valid or invalid)

ALL_OBJECTS:
 Query ALL_OBJECTS to see all the objects to which you have access.

11.5 USER_OBJECTS View


SELECT object_name, object_type, created, status
FROM user_objects
ORDER BY object_type;

11.6 Table Information

USER_TABLES:

DESCRIBE user_tables;
SELECT table_name
FROM user_tables;

11.7 Column Information


USER_TAB_COLUMNS:
DESCRIBE user_tab_columns;

Thawzh818@gmail.com Page 120


Treasure Island Training Service Ph:09691011157

SELECT column_name, data_type, data_length,


data_precision, data_scale, nullable
FROM user_tab_columns
table_name = „EMPLOYEES‟ ;
11.8 Constraint Information

USER_CONSTRAINTS describes the constraint definitions on your tables.

USER_CONS_COLUMNS describes columns that are owned by you and that are
specified in constraints.

DESCRIBE user_constraints;
SELECT *
FROM user_constraints
WHERE table_name=‟EMPLOYEES‟;

11.9 Querying USER_CONS_COLUMNS

DESCRIBE user_cons_columns;
SELECT constraint_name, column_name
FROM user_cons_columns
WHERE table_name = 'EMPLOYEES';

11.10 Adding Comments to a Table


 You can add comments to a table or column by using the COMMENT statement:

COMMENT ON TABLE employees is „Employee Information‟;


COMMENT ON COLUMN employes.first_name IS „First name of the employee‟;

 Comments can be viewed through the data dictionary views:

 ALL_COL_COMMENTS

Thawzh818@gmail.com Page 121


Treasure Island Training Service Ph:09691011157

 USER_COL_COMMENTS
 ALL_TAB_COMMENTS
 USER_TAB_COMMENTS
Quiz

The dictionary views that are based on the dictionary tables contain information such
as:
 Definitions of all the schema objects in the database
 Default values for the columns
 Integrity constraint information
 Privileges and roles that each user has been granted

Ans: All of the above

12.1 Creating sequences, synonyms, an indexes

After completing this lesson, you should be able to:


 Create, maintain, and use sequences
 Create private and public synonyms
 Create and maintain indexes
 Query various data dictionary views to find information for sequences,
synonyms, and indexes

Database Objects

Object Description
Table Basic unit of storage; Table composed of rows
View Logically represents subsets of data from one or more tables
Sequence Generates numeric values
Index Improves the performance of data retrieval queries
Synonym Gives alternative names to objects

Thawzh818@gmail.com Page 122


Treasure Island Training Service Ph:09691011157

12.2 Referencing Another User‟s Tables


 Tables belonging to other users are not in the user‟s schema.
 You should use the owner‟s name as a prefix to those tables.
12.3 Sequences
A sequence:
 Can automatically generate unique numbers
 Is a shareable object
 Can be used to create a primary key value
 Replaces application code
 Speeds up the efficiency of accessing sequence values when cached in memory
12.4 CREATE SEQUENCE Statement: Syntax

Define a sequence to generate sequential numbers automatically:

CREATE SEQUENCE [ schema. ] sequence


[ { START WITH | increment by integer
| {MAXVALUE interger | NOMAXVALUE }
| {MINVALUE integer | NOMINVALUE}
| { CYCLE | NOCYCLE }
| { CACHE integer
| NOCACHE }
| { ORDER
| NOORDER }
];

12.5 Creating a Sequence

 Create a sequence named DEPT_DEPTID_SEQ to be used for the primary key of


the DEPARTMENTS table.
 Do not use the CYCLE option.

Thawzh818@gmail.com Page 123


Treasure Island Training Service Ph:09691011157

CREATE SEQUENCE dept_deptid_seq


START WITH 280
INCREMENT BY 10
MAXVALUE 9999
NOCACHE
NOCYCLE;

12.6 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 must be issued for that sequence before CURRVAL contains a value.

12.7 Using a Sequence

 Insert a new department named “Support” in location ID2500:

INSERT INTO departments(department_id, department_name, locaton_id)


VALUES (dept_deptid_seq.NEXTVAL,'Support', 2500);

 View the current value for the DEPT_DEPTID_SEQ sequence.

SELECT dept_deptid_seq.CURRVAL FROM dual;

12.8 SQL Column Defaulting Using a Sequence

 SQL syntax for column defaults allow .nextval, .currval as a SQL column
defaulting expression for numeric columns, where is an Oracle database
sequence.
 The DEFAULT expression can include the sequence pseudocolumns CURRVAL
and NEXTVAL, as long as the sequence exists and you have the privileges
necessary to access it.

Thawzh818@gmail.com Page 124


Treasure Island Training Service Ph:09691011157

CREATE SEQUENCE s1 START WITH 1;

CREATE TABLE emp (

a1 NUMBER DEFAULT s1.NEXTVAL NOT NULL,

a2 VARCHAR2(10)); INSERT INTO emp (a2) VALUES („john');

INSERT INTO emp (a2) VALUES („mark');

SELECT * FROM emp;

12.9 Caching Sequence Values

 Caching sequence values in memory gives faster access to those values.


 Gaps in sequence values can occur when:

– A rollback occurs
– The system crashes
– A sequence is used in another table

12.10 Modifying a Sequence

Change the increment value, maximum value, minimum value, cycle option, or cache
option:

ALTER SEQUENCE dept_deptid_seq


INCREMENT BY 20
MAXVAL 90
NOCACHE
NOCYCLE;

Thawzh818@gmail.com Page 125


Treasure Island Training Service Ph:09691011157

12.11 Guidelines for Modifying a Sequence

 You must be the owner or have the ALTER privilege for the sequence.
 Only future sequence numbers are affected.
 The sequence must be dropped and re-created to restart the sequence at a
different number.
 Some validation is performed.
 To remove a sequence, use the DROP statement:

DROP SEQUENCE dept_deptid_seq;

12.12 Sequence Information

 The USER_SEQUENCES view describes all sequences that you own.


DESCRIBE user_sequences;
 Verify your sequence values in the USER_SEQUENCES data dictionary table.

SELECT sequence_name, min_value, max_value, increment_by, last_number


FROM user_sequences;

12.13 Synonyms

A synonym:

 Is a database object
 Can be created to give an alternative name to a table or to another database
object
 Requires no storage other than its definition in the data dictionary

Thawzh818@gmail.com Page 126


Treasure Island Training Service Ph:09691011157

 Is useful for hiding the identity and location of an underlying schema object

12.14 Creating a Synonym for an Object

Simplify access to objects by creating a synonym (another name for an object). With
synonyms, you can:
 Create an easier reference to a table that is owned by another user
 Shorten lengthy object names

CREATE [PUBLIC] SYNONYM synonym


FOR object;

12.15 Creating and Removing Synonyms


 Create a shortened name for the DEPT_SUM_VU view:

CREATE SYNONYM d_sum FOR dept_sum_vu;


 Drop a synonym:
DROP SYNONYM d_sum;

12.16 Synonym Information

DESCRIBE user_synonyms;

SELECT *
FROM user_synonyms;

12.17 Indexes
An index:

Thawzh818@gmail.com Page 127


Treasure Island Training Service Ph:09691011157

 Is a schema object
 Can be used by the Oracle Server to speed up the retrieval of rows by using a
pointer
 Can reduce disk input/output (I/O) by using a rapid path access method to
locate data quickly
 Is dependent on the table that it indexes
 Is used and maintained automatically by the Oracle Serve

12.18 How Are Indexes Created?

 Automatically: A unique index is created automatically when you define a


PRIMARY KEY or UNIQUE constraint in a table definition.
 Manually: You can create unique or nonunique index on columns to speed up
access to the rows.

12.19 Creating an Index

 Create an index on one or more columns:


CREATE [UNIQUE]INDEX index
ON table (column[, column]...);

 Improve the speed of query access to the LAST_NAME column in the


EMPLOYEES table:

CREATE INDEX emp_last_name_idx


ON employees(last_name);

Thawzh818@gmail.com Page 128


Treasure Island Training Service Ph:09691011157

12.20 CREATE INDEX with the CREATE TABLE Statement

CREATE TABLE NEW_EMP (


employee_id NUMBER(6)
PRIMARY KEY USING INDEX
(CREATE INDEX em_id_idx
ON NEW_EMP(employee_id)),
first_name VARCHAR2(20),
last_name VARCHAR2(25));

SELECT INDEX_NAME, TABLE_NAME


FROM USER_INDEXES
WHERE TABLE_NAME = 'NEW_EMP';

The following examples illustrate this process:

Step 1: Create the table:


CREATE TABLE NEW_EMP2
(employee_id NUMBER(6),
first_name VARCHAR2(20),
last_name VARCHAR2(25)
);

Step 2: Create the index:


CREATE INDEX emp_id_idx2
ON new_emp2(employee_id);

Thawzh818@gmail.com Page 129


Treasure Island Training Service Ph:09691011157

Step3: Create the PRIMARY KEY:

ALTER TABLE new_emp2 ADD PRIMARY KEY (employee_id) USING INDEX


emp_id_idx2;

12.21 Function-Based Indexes

 A function-based index is based on expressions.


 The index expression is built from table columns, constants, SQL functions, and
userdefined functions.
CREATE INDEX upper_dept_name_idx
ON dept2(UPPER(department_name));

SELECT *
FROM dept2
WHERE UPPER(department_name) = 'SALES';
12.22 Creating Multiple Indexes on the Same Set Of columns
 You can create multiple indexes on the same set of columns.
 Multiple indexes can be created on the same set of columns if:
– The indexes are of different types
– The indexes uses different partitioning
– The indexes have different uniqueness properties

Example of Creating Multiple Indexes on the Same Set of columns

CREATE INDEX emp_id_name_ix1


ON employees(employee_id, first_name);

Thawzh818@gmail.com Page 130


Treasure Island Training Service Ph:09691011157

ALTER INDEX emp_id_name_ix1 INVISIBLE;

CREATE BITMAP INDEX emp_id_name_ix2


ON employees(employee_id, first_name);

12.23 Index Information

 USER_INDEXES provides information about your indexes.


 USER_IND_COLUMNS describes columns of indexes owned by you and columns
of indexes on your tables.

12.24 USER_INDEXES: Examples

SELECT index_name, table_name, uniqueness


FROM user_indexes
WHERE table_name = 'EMPLOYEES';

SELECT index_name, table_name


FROM user_indexes
WHERE table_name = 'EMP_LIB';

12.25 Querying USER_IND_COLUMNS

DESCRIBE user_ind_columns;

SELECT index_name, column_name, table_name


FROM user_ind_columns
WHERE index_name = 'LNAME_IDX';

Thawzh818@gmail.com Page 131


Treasure Island Training Service Ph:09691011157

CREATE TABLE emp_test AS SELECT * FROM employees;


CREATE INDEX lname_idx ON emp_test(last_name);

12.26 Removing an Index

 Remove an index from the data dictionary by using the DROP INDEX command:
DROP INDEX index ;

 Remove the emp_last_name_idx index from the data dictionary:


DROP INDEX emp_last_name_idx;

 To drop an index, you must be the owner of the index or have the DROP ANY
INDEX privilege.

Quiz
Indexes must be created manually and serve to speed up access to rows in a table.
a. True
b. False

Answer: b

13.1 Oracle CREATE VIEW


After completing this lesson, you should be able to do:

 Create simple and complex views


 Retrieve data from views
 Querying the dictionary views for the view information

Thawzh818@gmail.com Page 132


Treasure Island Training Service Ph:09691011157

10.17.1 Advantages of Views

13.2 Simple Views and Complex Views

Feature Simple Views Complex Views


Number of tables One One or more
Contain functions No yes
Contain groups of data No yes
DML operations through a Yes Not always
view

13.3 Creating a View

 Create the EMPVU80 view, which contains details of the employees in department 80:

CREATE VIEW empvu80


AS SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 80;

 Create a view by using column aliases in the subquery:

Thawzh818@gmail.com Page 133


Treasure Island Training Service Ph:09691011157

CREATE VIEW salvu50


AS SELECT employee_id ID_NUMBER, last_name NAME, salar *12 ANN_SALARY
FROM employees
WHERE department_id = 50;

CREATE OR REPLACE VIEW customer_credits( customer_id, name, credit )


AS SELECT customer_id, name, credit_limit
FROM customers
WITH READ ONLY;

 Select the columns from this view by the given alias names.

 Describe the structure of the view by using the SQL*Plus DESCRIBE command:

DESCRIBE empvu80;

DESCRIBE salvu50;

13.4 Retrieving Data from a View

Select * from empvu80;


Select * from salvu50;

13.5 Modifying a View

 Modify the EMPVU80 view by using a CREATE OR REPLACE VIEW clause. Add an
alias for each column name:

CREATE OR REPLACE VIEW empvu80

Thawzh818@gmail.com Page 134


Treasure Island Training Service Ph:09691011157

AS SELECT employee_id, first_name || ' ' || last_name, salary, department_id


FROM employees
WHERE department_id = 80;

 Column aliases in the CREATE OR REPLACE VIEW clause are listed in the same
order as the columns in the subquery.
13.6 Creating a Complex View

Create a complex view that contains group functions to display values from two tables:

CREATE OR REPLACE VIEW dept_sum_vu (name, minsal, maxsal, avgsal)


AS SELECT d.department_name, MIN(e.salary), MAX(e.salary), AVG(e.salary)
FROM employees e JOIN departments d
USING (department_id)
GROUP BY d.department_name;

SELECT * FROM dept_sum_vu;

13.7 View Information


DESCRIBE user_views;

SELECT view_name FROM user_views;

Select text from user_views Where view_name='EMP_DETAILS_VIEW';


13.8 Rules for Performing DML Operations on a View

 You can usually perform DML operations on simple views.


 You cannot remove a row if the view contains the following :
– Group functions
– A GROUP BY clause

Thawzh818@gmail.com Page 135


Treasure Island Training Service Ph:09691011157

– The DISTINCT keyword


– The pseudocolumn ROWNUM keyword

You cannot modify data in a view if it contains: Group functions

 A GROUP BY clause
 The DISTINCT keyword
 The pseudocolumn ROWNUM keyword
 Expressions

You cannot add data through a view if the view includes:

 Group functions
 A GROUP BY clause
 The DISTINCT keyword
 The pseudocolumn ROWNUM keyword
 Columns defined by expressions
 NOT NULL columns without default value in the base tables that are not selected
by the view

13.9 Using the WITH CHECK OPTION Clause

 You can ensure that DML operations performed on the view stay in the domain
of the view by using the WITH CHECK OPTION clause:
CREATE OR REPLACE VIEW empvu20
AS SELECT *
FROM employees
WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;

Thawzh818@gmail.com Page 136


Treasure Island Training Service Ph:09691011157

 Any attempt to INSERT a row with a department_id other than 20 or to UPDATE


the department number for any row in the view fails because it violates the
WITH CHECK OPTION.
13.10 Denying DML Operations
 You can ensure that no DML operations occur by adding the WITH READ ONLY
option to your view definition.
 Any attempt to perform a DML operation on any row in the view results in an
Oracle server error.
CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title)
AS SELECT employee_id, last_name, job_id
FROM employees
WHERE department_id = 10 WITH READ ONLY;

DELETE FROM empvu10 WHERE employee_number = 200;

13.11 Removing a View


You can remove a view without losing data because a view is based on underlying
tables in the database.
DROP VIEW view ;

DROP VIEW empvu80;

Quiz
You cannot add data through a view if the view includes a GROUP BY clause.
a. True
b. False
Answer: a

Thawzh818@gmail.com Page 137


Treasure Island Training Service Ph:09691011157

14.1 Managing Schema Objects

After completing this lesson, you should be able to:


 Manage constraints
 Create and use temporary tables
 Create and use external tables

14.2 Adding a Constraint Syntax Use the ALTER TABLE statement to:

 Add or drop a constraint, but not to modify its structure


 Enable or disable constraints
 Add a NOT NULL constraint by using the MODIFY clause

14.3 Adding a Constraint

Add a FOREIGN KEY constraint to the EMP2 table indicating that a manager must
already exist as a valid employee in the EMP2 table.

ALTER TABLE emp2 MODIFY employee_id PRIMARY_KEY;

ALTER TABLE emp2


ADD CONSTRAINT emp_mgr_fk
FOREIGN KEY (manager_id)
REFERENCES emp2 (employee_id);

Thawzh818@gmail.com Page 138


Treasure Island Training Service Ph:09691011157

14.4 Dropping a CONSTRAINT ONLINE

You can specify the ONLINE keyword to indicate that DML operations on the table are
allowed while dropping the constraint.

ALTER TABLE myemp


DROP CONSTRAINT emp_name_pk ONLINE;

14.5 ON DELETE Clause

 Use the ON DELETE CASCADE clause to delete child rows when a parent key is
deleted:

ALTER TABLE dept2 ADD CONSTRAINT dept_lc_fk


FOREIGN KEY (location id)
REFERENCES locations(location_id) ON DELETE CASCADE;

 Use the ON DELETE SET NULL clause to set the child rows value to null when a
parent key is deleted:
ALTER TABLE emp2 ADD CONSTRAINT empdt_fk
FOREIGN KEY (department_id)
REFERENCES departments (department_id) ON DELETE SET NULL;

14.6 Cascading Constraints

 The CASCADE CONSTRAINTS clause:


– Is used along with the DROP COLUMN clause

Thawzh818@gmail.com Page 139


Treasure Island Training Service Ph:09691011157

– Drops all referential integrity constraints that refer to the PRIMARY and
UNIQUE keys defined on the dropped columns
– Drops all multicolumn constraints defined on the dropped columns

CREATE TABLE test1 (


col1_pk NUMBER PRIMARY KEY,
col2_fk NUMBER, col1 NUMBER,
col2 NUMBER, CONSTRAINT fk_constraint FOREIGN KEY (col2_fk) REFERENCES test1,
CONSTRAINT ck1 CHECK (col1_pk > 0 and col1 > 0),
CONSTRAINT ck2 CHECK (col2_fk > 0));
 An error is returned for the following statements:

ALTER TABLE test1 DROP (col1_pk);


col1_pk is a parent key.
ALTER TABLE test1 DROP (col1);
col1 is referenced by the multicolumn constraint, ck1.
Example:

ALTER TABLE emp2 DROP COLUMN employee_id CASCADE CONSTRAINTS;

ALTER TABLE test1 DROP (col1_pk, col2_fk, col1);

14.7 Renaming Table Columns and Constraints

 Use the RENAME TABLE clause of the ALTER TABLE statement to rename tables.

ALTER TABLE old_tablename RENAME TO new_tablename

ALTER TABLE marketing RENAME TO new_marketing;

Thawzh818@gmail.com Page 140


Treasure Island Training Service Ph:09691011157

 Use the RENAME COLUMN clause of the ALTER TABLE statement to rename
table columns.

alter table tablename rename column old_columnname to new_columndname;

ALTER TABLE new_marketing RENAME COLUMN team_id TO id;

 Use the RENAME CONSTRAINT clause of the ALTER TABLE statement to rename
any existing constraint for a table.

ALTER TABLE tablename RENAME CONSTRAIT old_constraint_name TO


new_constraint_name;

ALTER TABLE new_marketing RENAME CONSTRAINT mktg_pk TO new_mktg_pk;

14.8 Disabling Constraints

 Execute the DISABLE clause of the ALTER TABLE statement to deactivate an


integrity constraint.

 Apply the CASCADE option to disable the primary key and it will disable all
dependent FOREIGN KEY constraints automatically as well.

ALTER TABLE emp2 DISABLE CONSTRAINTS emp_dt_pk;

ALTER TABLE dept2 DISABLE primary key CASCADE;

Thawzh818@gmail.com Page 141


Treasure Island Training Service Ph:09691011157

14.9 Enabling Constraints

 Activate an integrity constraint that is currently disabled in the table definition by


using the ENABLE clause.

ALTER TABLE emp2 ENABLE CONSTRAINT emp_dt_fk;

A UNIQUE index is automatically created if you enable a UNIQUE key or a PRIMARY


KEY constraint.

14.10 Constraint States

An integrity constraint defined on a table can be in one of the following states:


 ENABLE VALIDATE
 ENABLE NOVALIDATE
 DISABLE VALIDATE
 DISABLE NOVALIDATE

ALTER TABLE dept2 ENABLE NOVALIDATE PRIMARY KEY;

14.11 Deferring Constraints

Constraints can have the following attributes:


 DEFERRABLE or NOT DEFERRABLE
 INITIALLY DEFERRED or INITIALLY IMMEDIATE

Thawzh818@gmail.com Page 142


Treasure Island Training Service Ph:09691011157

ALTER TABLE dept2


ADD CONSTRAINT dept2_id_pk
PRIMARY KEY (department_id)
DEFERRABLE INITIALLY DEFERRED;

SET CONSTRAINTS dept2_id_pk IMMEDIATE;

ALTER SESSION SET CONSTRAINTS= IMMEDIATE;

14.12 Difference Between INITIALLY DEFFERED and INITIALLY IMMEDIATE

INITIALLY DEFERRED Waits until the transaction ends to check the constraint
INITIALLY Checks the constraints at the end of the statement execution
IMMEDIATE

CREATE TABLE emp_new_sal (


salary NUMBER CONSTRAINT sal_ck CHECK (salary > 100) DEFERRABLE INITIALLY
IMMEDIATE,
bonus NUMBER CONSTRAINT bonus_ck CHECK (bonus > 0) DEFERRABLE INITIALLY
DEFERRED);

Example 1
insert into emp_new_sal values (90,5);

Example 2.
insert into emp_new_sal values (110,-1);

Thawzh818@gmail.com Page 143


Treasure Island Training Service Ph:09691011157

Example 3.
SET CONSTRAINTS ALL DEFERRED;

Example 4.
SET CONSTRAINT ALL IMMEDIATE;

14.13 DROP TABLE ….. PURGE

DROP TABLE emp_ne_sal PURGE;

14.14 Temporary Tables

A temporary table is a table that holds data that exists only for the duration of a
transaction or session. Data in a temporary table is private to the session, which means
that each session can see and modify only its own data.

14.14 Creating a Temporary Table

CREATE GLOBAL TEMPORARY TABLE cart(


n NUMBER,
d DATE) ON COMMIT DELETE ROWS;

CREATE GLOBAL TEMPORARY TABLE today_sales


ON COMMIT PRESERVE ROWS
AS SELECT *
FROM orders
WHERE order_date=SYSDATE;

14.16 External Tables

Thawzh818@gmail.com Page 144


Treasure Island Training Service Ph:09691011157

An external table is a read-only table whose metadata is stored in the database but
whose data is stored outside the database. This external table definition can be thought
of as a view that is used for running any SQL query against external data without
requiring that the external data first be loaded into the database. The external table
data can be queried and joined directly and in parallel without requiring that the
external data first be loaded in the database.

14.17 Creating a Directory for the External Table

Create a DIRECTORY object that corresponds to the directory on the file system where
the external data source resides.

CREATE OR REPLACE DIRECTORY emp_dir as '/oracle/emp_dir';

GRANT READ ON DIRECTORY emp_dir to thaw_2;

14.18 Creating an External Table

CREATE TABLE extract_emps


ORGANIZATION EXTERNAL
(TYPE ORACLE_DATAPUMP
DEFAULT DIRECTORY …
ACCESS PARAMETERS (… )
LOCATIONS (…)
PARALLEL 4
REJECT LIMIT UNLIMITED
AS SELECT * FROM …;

14.19 Creating an External Table by Using ORACLE_LOADER

Thawzh818@gmail.com Page 145


Treasure Island Training Service Ph:09691011157

CREATE TABLE oldemp (fname char (25), lname CHAR (25))


ORGANIZATION EXTERNAL
(TYPE ORACLE_LOADER
DEFAULT DIRECTORY emp_dir
ACCESS PARAMETERS
(RECORDS DELIMITED BY NEWLINE FIELDS
(fname POSITION (1:20) CHAR,
lname POSITION (22:42) CHAR))
LOCATION ('emp.dat'));

14.20 Querying External Tables

Select * from oldemp;

Creating an External Table by Using ORACLE_DATAPUMP:Example

CREATE TABLE emp_ext (employee_id, first_name, last_name)


ORGANIZATION EXTERNAL (
TYPE ORACLE_DATAPUMP
DEFAULT DIRECTORY emp_dir
LOCATION
('emp1.exp','emp2.exp')
) PARALLEL
AS SELECT employee_id, first_name, last_name
FROM employees;

Thawzh818@gmail.com Page 146


Treasure Island Training Service Ph:09691011157

Quiz
A FOREIGN KEY constraint enforces the following action: When the data in the parent
key is deleted, all the rows in the child table that depend on the deleted parent key
values are also deleted.

a. True
b. False

Answer: b

15.1 Manipulating Data by Using subqueries

After completing this lesson, you should be able to:


 Use subqueries to manipulate data
 Insert values by using a subquery as a target
 Use the WITH CHECK OPTION keyword on DML statements
 Use correlated subqueries to update and delete row

15.2 Using Subqueries to Manipulate Data

You can use subqueries in data manipulation language (DML) statements to:
 Retrieve data by using an inline view
 Copy data from one table to another
 Update data in one table based on the values of another table
 Delete rows from one table based on rows in another table

Thawzh818@gmail.com Page 147


Treasure Island Training Service Ph:09691011157

15.3 Inserting by Using a Subquery as a Target

INSERT INTO (SELECT l.location_id, l.city, l.country_id


FROM loc l JOIN countries c
ON(l.country_id = c.country_id)
JOIN regions
USING(region_id)
WHERE region_name = 'Europe')
VALUES (3300, 'Cardiff', 'UK');

15.4 Inserting by Using a Subquery as a Target

Verify the results.

SELECT location_id, city, country_id


FROM loc;

15.5 Using the WITH CHECK OPTION Keyword on DML Statements

The WITH CHECK OPTION keyword prohibits you from changing rows that are not in
the subquery.
INSERT INTO ( SELECT location_id, city, country_id
FROM loc
WHERE country_id IN (
SELECT country_id
FROM countries NATURAL JOIN regions

Thawzh818@gmail.com Page 148


Treasure Island Training Service Ph:09691011157

WHERE region_name = 'Europe')


WITH CHECK OPTION )
VALUES (3600, ' Washington', 'US');

15.6 Correlated UPDATE

Use a correlated subquery to update rows in one table based on rows from another
table.

UPDATE table1 alias1


SET column = SELECT expression
FROM table2 alias2
WHERE alias1.column =alias2.column);

15.7 Using Correlated UPDATE


 Denormalize the EMPL6 table by adding a column to store the department name.
 Populate the table by using a correlated update.

ALTER TABLE empl6 ADD (department_name VARCHAR2(25));

UPDATE empl6 e
SET department_name =(SELECT department_name
FROM departments d
WHERE e.department_id=d.department_id);

15.8 Correlated DELETE


Use a correlated subquery to delete rows in one table based on rows from another table

DELETE FROM table1 alias1

Thawzh818@gmail.com Page 149


Treasure Island Training Service Ph:09691011157

WHERE column operator


(SELECT expression FROM table2 alias2 WHERE alias1.column = alias2.column);

15.9 Using Correlated DELETE

Use a correlated subquery to delete only those rows from the EMPL6 table that also
exist in the EMP_HISTORY table.
DELETE FROM empl6 E
WHERE employee_id = (
SELECT employee_id
FROM emp_history
WHERE employee_id = E.employee_id);

16.1 Manipulate Data


After completing this lesson, you should be able to:
 Specify explicit default values in the INSERT and UPDATE statements
 Describe the features of multitable INSERTs
 Use the following types of multitable INSERTs:
– Unconditional INSERT
– Conditional INSERT ALL
– Conditional INSERT FIRST
– Pivoting INSERT
 Merge rows in a table
 Perform flashback operations
 Track the changes made to data over a period of time

16.2 Explicit Default Feature: Overview

Thawzh818@gmail.com Page 150


Treasure Island Training Service Ph:09691011157

 Use the DEFAULT keyword as a column value where the default column value is
desired.
 This allows the user to control where and when the default value should be
applied to data.
 Explicit defaults can be used statements. in INSERT and UPDATE

16.3 Using Explicit Default Values

 DEFAULT with INSERT:

INSERT INTO deptm3 (department_id, department_name, manager_id)


VALUES (300, 'Engineering', DEFAULT);

 DEFAULT with UPDATE:

UPDATE deptm3
SET manager_id = DEFAULT
WHERE department_id = 10;

16.4 Multitable INSERT Statements: Overview

Thawzh818@gmail.com Page 151


Treasure Island Training Service Ph:09691011157

16.5 Multitable INSERT Statements: Overview

 Use the INSERT…SELECT statement to insert rows into multiple tables as part of
a single DML statement.
 Multitable INSERT statements are used in data warehousing systems to transfer
data from one or more operational sources to a set of target tables.
 They provide significant performance improvement over:
– Single DML versus multiple INSERT…SELECT statements
– Single DML versus a procedure to perform multiple inserts by using the
IF...THEN syntax

Thawzh818@gmail.com Page 152


Treasure Island Training Service Ph:09691011157

16.6 Types of Multitable INSERT Statements

The different types of multitable INSERT statements are:

 Unconditional INSERT
 Conditional INSERT ALL
 CONDITIONAL INSERT FIRST
 Pivoting INSERT

16.7 Multitable INSERT Statements

1. Unconditional INSERT ALL

 Select the EMPLOYEE_ID, HIRE_DATE, SALARY, and MANAGER_ID values from


the EMPLOYEES table for those employees whose EMPLOYEE_ID is greater than
200.
 Insert these values into the SAL_ HISTORY and MGR_HISTORY tables by using a
multitable INSERT.

INSERT ALL
INTO sal_history VALUES(EMPID,HIREDATE,SAL)
INTO mgr_history VALUES(EMPID,MGR,SAL)
SELECT employee_id EMPID, hire_date HIREDATE,salary SAL, manager_id MGR
FROM employees
WHERE employee_id > 200;

2. Conditional INSERT ALL

INSERT ALL
WHEN HIREDATE < '01-JAN-05' THEN
INTO emp_history VALUES(EMPID,HIREDATE,SAL)
WHEN COMM IS NOT NULL THEN

Thawzh818@gmail.com Page 153


Treasure Island Training Service Ph:09691011157

INTO emp_sales VALUES(EMPID,COMM,SAL)


SELECT employee_id EMPID, hire_date HIREDATE, salary SAL, commission_pct COMM
FROM employees;
3. Conditional INSERT FIRST: Example

INSERT FIRST
WHEN salary < 5000 THEN
INTO sal_low VALUES (employee_id, last_name, salary)
WHEN salary between 5000 and 10000 THEN
INTO sal_mid VALUES (employee_id, last_name, salary)
ELSE
INTO sal_high VALUES (employee_id, last_name, salary)
SELECT employee_id, last_name, salary
FROM employees;

4. Pivoting INSERT

Convert the set of sales records from the non relational database table to relational
format.

INSERT ALL
INTO sales_info VALUES (employee_id,week_id,sales_MON)

Thawzh818@gmail.com Page 154


Treasure Island Training Service Ph:09691011157

INTO sales_info VALUES (employee_id,week_id,sales_TUE)


INTO sales_info VALUES (employee_id,week_id,sales_WED)
INTO sales_info VALUES (employee_id,week_id,sales_THUR)
INTO sales_info VALUES (employee_id,week_id, sales_FRI)
SELECT EMPLOYEE_ID, week_id, sales_MON, sales_TUE, sales_WED,
sales_THUR,sales_FRI
FROM sales_source_data;

16.8 MERGE Statement

 Provides the ability to conditionally update, insert, or delete data into a database
table
 Performs an UPDATE if the row exists, and an INSERT if it is a new row:
– Avoids separate updates
– Increases performance and ease of use
– Is useful in data warehousing applications

16.9 MERGE Statement Syntax

You can conditionally insert, update, or delete rows in a table by using the MERGE
statement.

MERGE INTO table_name table_alias


USING (table view sub_query ) alias
ON (join condition )
WHEN MATCHED THEN

Thawzh818@gmail.com Page 155


Treasure Island Training Service Ph:09691011157

UPDATE SET
col1 = col1_val,
col2 = col2_val
WHEN NOT MATCHED THEN
INSERT (column_list)
VALUES (column_values);
16.10 Merging Rows: Example

Insert or update rows in the COPY_EMP3 table to match the EMPLOYEES table.

MERGE INTO copy_emp3 c


USING (SELECT * FROM EMPLOYEES ) e
On (e.employee_id =c.employee_id)
WHEN MATCHED THEN
UPDATE SET
c.first_name = e.first_name,
c.last_name = e.last_name,
...
DELETE WHERE (E.COMMISSION_PCT IS NOT NULL)
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name, e.last_name,e.email, e.phone_number,
e.hire_date, e.job_id, e.salary, e.commission_pct, e.manager_id, e.department_id);

TRUNCATE TABLE copy_emp3;


SELECT * FROM copy_emp3;

MERGE INTO copy_emp3 c


USING (SELECT * FROM EMPLOYEES ) e
On (e.employee_id =c.employee_id)

Thawzh818@gmail.com Page 156


Treasure Island Training Service Ph:09691011157

WHEN MATCHED THEN


UPDATE SET
c.first_name = e.first_name,
c.last_name = e.last_name,
...
DELETE WHERE (E.COMMISSION_PCT IS NOT NULL)
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name, e.last_name,e.email, e.phone_number,
e.hire_date, e.job_id, e.salary, e.commission_pct, e.manager_id, e.department_id);

SELECT * FROM copy_emp3;

16.11 FLASHBACK TABLE Statement

 Enables you to recover tables to a specified point in time with a single statement
 Restores table data along with associated indexes and constraints
 Enables you to revert the table and its contents to a certain point in time or system
change number (SCN) .
 Repair tool for accidental table modifications
– Restores a table to an earlier point in time
– Offers ease of use, availability, and fast execution

FLASHBACK TABLE [ schema. ] table [, [ schema.] table ]... TO { { { SCN | TIMESTAMP


} expr | RESTORE POINT restore_point } [ { ENABLE | DISABLE } TRIGGERS ] |
BEFORE DROP [ RENAME TO table ] } ;

16.12 Using the FLASHBACK TABLE Statement

DROP TABLE emp3;

Thawzh818@gmail.com Page 157


Treasure Island Training Service Ph:09691011157

SELECT srcinal_name, operation, recyclebin, droptime FROM recyclebin;

FLASHBACK TABLE emp3 TO BEFORE DROP;

16.13 Tracking Changes in Data

16.14 Flashback Query: Example

SELECT salary
FROM employees3
WHERE last_name = 'Chung';

Thawzh818@gmail.com Page 158


Treasure Island Training Service Ph:09691011157

UPDATE employees3 SET salary = 4000 WHERE last_name = 'Chung'; SELECT salary
FROM employees3
WHERE last_name = 'Chung';

SELECT salary
FROM employees3
AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '1' MINUTE)
WHERE last_name = 'Chung';

16.15 Flashback Version Query: Example

SELECT salary
FROM employees3
WHERE employee_id = 107;

UPDATE employees3
SET
salary = salary * 1.30
WHERE EMPLOYEE_ID=107;

COMMIT;

SELECT salary
FROM employees3
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE employee_id=107;

Thawzh818@gmail.com Page 159


Treasure Island Training Service Ph:09691011157

16.16 VERSIONS BETWEEN Clause

SELECT versions_starttime "START_DATE",versions_endtime "END_DATE",salary


FROM employees
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE last_name = 'Lorentz';

SELECT salary
FROM employees3
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE employee_id = 107;

Quiz
When you use the INSERT or UPDATE command, the DEFAULT keyword saves you
from hardcoding the default value in your programs or querying the dictionary to find it.
a. True
b. False
Answer: a
Quiz
In all the cases, when you execute a DROP TABLE command, the database renames the
table and places it in a recycle bin, from where it can later be recovered by using the
FLASHBACK TABLE statement.
a. True
b. False
Answer: b

Thawzh818@gmail.com Page 160


Treasure Island Training Service Ph:09691011157

17. Managing Data in Different Time Zones

After completing this lesson, you should be able to:

 Use data types similar to DATE that store fractional seconds and track time zones
 Use the following datetime functions:
– CURRENT_DATE
– CURRENT_TIMESTAMP
– TZ_OFFSET
– FROM_TZ
– LOCALTIMESTAMP
– DBTIMEZONE
– SESSIONTIMEZONE
– EXTRACT
– TO_TIMESTAMP
– TO_YMINTERVAL
– TO_DSINTERVAL

17.2 TIME_ZONE Session Parameter

TIME_ZONE may be set to:

Thawzh818@gmail.com Page 161


Treasure Island Training Service Ph:09691011157

 An absolute offset
 Database time zone
 OS local time zone
 A named region
ALTER SESSION SET TIME_ZONE = '-05:00';
ALTER SESSION SET TIME_ZONE = dbtimezone;
ALTER SESSION SET TIME_ZONE = local;
ALTER SESSION SET TIME_ZONE=‟America/New York‟;

17.3 CURRENT_DATE, CURRENT_TIMESTAMP and LOCALTIMESTAMP


 CURRENT_DATE :
– Returns the current date from the user session
– Has a data type of DATE
 CURRENT_TIMESTAMP:
– Returns the current date and time from the user session
– Has a data type of TIMESTAMP WITH TIME ZONE
 LOCALTIMESTAMP :
– Returns the current date and time from the user session
– Has a data type of TIMESTAMP

17.4 Comparing Date and Time IN A Session‟s Time Zone

The TIME_ZONE parameter is set to –5:00 and then SELECT statements for each date
and time are executed to compare differences.

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

ALTER SESSION SET TIME_ZONE = '-5:00';

SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;

Thawzh818@gmail.com Page 162


Treasure Island Training Service Ph:09691011157

SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM DUAL;

SELECT SESSIONTIMEZONE, LOCALTIMESTAMP FROM DUAL;

17.5 DBTIMEZONE and SESSIONTIMEZONE


 Display the value of the database time zone:
SELECT DBTIMEZONE FROM DUAL;

 Display the value of the session‟s time zone:


SELECT SESSIONTIMEZONE FROM DUAL;

17.6 TIMESTAMP Data Types


Data Type Fields
TIMESTAMP Year, Month, Day, Hour, Minute, Second with fractional
seconds
TIMESTAMP WITH TIME ZONE S Same as the TIMESTAMP data type: also includes:
TIMEZONE_HOUR, and TIMEZONE_MINUTE or
TIMEZONE_REGION
TIMESTAMP WITH LOCAL TIME Same as the TIMESTAMP data type; also includes a
ZONE time zone offset in its value

17.7 TIMESTAMP FIELDS


Datetime Field Valid Values
YEAR -4712 to 9999 (excluding year 0)
MONTH 01 to 12
DAY 01 to 31
HOUR 00 to 23
MINUTE 00 to 59

Thawzh818@gmail.com Page 163


Treasure Island Training Service Ph:09691011157

SECOND 00 to 59.9 (N) where 9(N) is precision


TIMEZONE_HOUR -12 to 14
TIMEZONE_MINUTE 00 to 59

17.8 Difference Between DATE and TIMESTAMP


-- when hire_date is of type DATE ALTER TABLE emp4 MODIFY hire_date
SELECT hire_date FROM emp4; TIMESTAMP(7); SELECT hire_date FROM emp4;
17.9 Comparing TIMESTAMP Data Types
CREATE TABLE web_orders
(order_date TIMESTAMP WITH TIME ZONE,
delivery_time TIMESTAMP WITH LOCAL TIME ZONE);

INSERT INTO web_orders values (current_date, current_timestamp + 2);

SELECT * FROM web_orders;

17.10 INTERVAL Data Types

 INTERVAL data types are used to store the difference between two datetime values.
 There are two classes of intervals:
– Year-month
– Day-time
 The precision of the interval is:

– The actual subset of fields that constitutes an interval


– Specified in the interval qualifier

Data Type Fields


INTERVAL YEAR TO Year, Month

Thawzh818@gmail.com Page 164


Treasure Island Training Service Ph:09691011157

MONTH
INTERVAL DAY TO Days, Hour, Minute, Second with fractional seconds
SECOND

17.11 INTERVAL Fields

INTERVAL Field Valid Values for Interval


YEAR Any positive or negative integer
MONTH 00 to 11
DAY Any positive or negative integer
HOUR 00 to 23
MINUTE 00 to 59
SECOND 00 to 59.9(N) where 9(N) is precision

17.12 INTERVAL YEAR TO MONTH: Example

CREATE TABLE warranty


(prod_id number, warranty_time INTERVAL YEAR(3) TO MONTH);

INSERT INTO warranty VALUES (123, INTERVAL '8' MONTH);


INSERT INTO warranty VALUES (155, INTERVAL '200' YEAR(3));
INSERT INTO warranty VALUES (678, '200-11');
SELECT * FROM warranty;

17.13 INTERVAL DAY TO SECOND Data Type: Example

Thawzh818@gmail.com Page 165


Treasure Island Training Service Ph:09691011157

CREATE TABLE lab


( exp_id number,
test_time INTERVAL DAY(2) TO SECOND);

INSERT INTO lab VALUES (100012, '90 00:00:00');

INSERT INTO lab VALUES (56098,INTERVAL '6 03:30:16' DAY TO SECOND);

SELECT * FROM lab;

17.14 EXTRACT

 Display all employees who were hired after 2007.

SELECT last_name, employee_id, hire_date


FROM employees
WHERE EXTRACT(YEAR FROM TO_DATE(hire _date, 'DD-MON-RR')) > 2007
ORDER BY hire_date;

 Display the MONTH component from the HIRE_DATE for those employees whose
MANAGER_ID is 100.

SELECT last_name, hire_date, EXTRACT (MONTH FROM HIRE_DATE)


FROM employees
WHERE manager_id = 100;

17.15 TZ_OFFSET

Thawzh818@gmail.com Page 166


Treasure Island Training Service Ph:09691011157

Display the time zone offset for the 'US/Eastern','Canada/Yukon' and 'Europe/London'
time zones:

SELECT TZ_OFFSET('US/Eastern'),
TZ_OFFSET(„Canda/Yukon‟),TZ_OFFSET('Europe/London')
FROM DUAL;

SELECT *
FROM V$TIMEZONE_NAMES;

17.16 FROM_TZ

Display the TIMESTAMP value '2000-07-12 08:00:00' as a TIMESTAMP WITH TIME


ZONE value for the 'Australia/North' time zone region.

SELECT FROM_TZ(TIMESTAMP '2000-07-12 08:00:00', 'Australia/North')


FROM DUAL;

17.17 TO_TIMESTAMP

Display the character string '2007-03-06 11:00:00' as a TIMESTAMP value:

SELECT TO_TIMESTAMP('2007-_ 03-06 11:00:00','YYYY-MM-DD HH:MI:SS')


FROM DUAL;

17.18 TO_YMINTERVAL
Display a date that is one year and two months after the hiredate for the employees
working in the department with the DEPARTMENT_ID 20.

Thawzh818@gmail.com Page 167


Treasure Island Training Service Ph:09691011157

SELECT hire_date,hire_date + TO_YMINTERVAL('01-02') AS


HIRE_DATE_YMININTERVAL
FROM employees
WHERE department_id = 20;

17.19 TO_DSINTERVAL

Display a date that is 100 days and 10 hours after the hire date for all the employees.

SELECT last_name,TO_CHAR(hire_date,‟mm-dd-yy:hh:mi:ss‟) hire_date,


TO_CHAR(hire_date +TO_DSINTERVAL('100 10:00:00'),'mm-dd-yy:hh:mi:ss') hiredate2
FROM employees;

17.20 Daylight Saving Time (DST)


 Start of Daylight Saving:
– Time jumps from 01:59:59 AM to 03:00:00 AM.
– Values from 02:00:00 AM to 02:59:59 AM are not valid.
 End of Daylight Saving:
– Time jumps from 02:00:00 AM to 01:00:01 AM.
– Values from 01:00:01 AM to 02:00:00 AM are ambiguous because they are
visited twice.

Quiz

Thawzh818@gmail.com Page 168


Treasure Island Training Service Ph:09691011157

The TIME_ZONE session parameter may be set to:


a. A relative offset
b. Database time zone
c. OS local time zone
d. A named region

Answer: b, c, d

18.1 Generating Reports by Grouping Related Data

After completing this appendix, you should be able to use the:


 ROLLUP operation to produce subtotal values
 CUBE operation to produce cross-tabulation values
 GROUPING function to identify the row values created by ROLLUP or CUBE
 GROUPING SETS to produce a single result set

18.2 Review of Group Functions


 Group functions operate on sets of rows to give one result per group.

SELECT AVG(salary), STDDEV(salary),COUNT(commission_pct),MAX(hire_date)


FROM employees
WHERE job_id LIKE 'SA%';

18.3 Review of the GROUP BY Clause

SELECT department_id , job _id , SUM( salary) ,COUNT(employee_id)


FROM employees
GROUP BY department_id, job_id

Thawzh818@gmail.com Page 169


Treasure Island Training Service Ph:09691011157

18.4 GROUP BY with ROLLUP and CUBE Operators

 Use ROLLUP or CUBE with GROUP BY to produce superaggregate rows by


crossreferencing columns.
 ROLLUP grouping produces a result set containing the regular grouped rows and the
subtotal values.
 CUBE grouping produces a result set containing the rows from ROLLUP and
crosstabulation rows

18.5 ROLLUP Operator

 ROLLUP is an extension to the GROUP BY clause.


 Use the ROLLUP operation to produce cumulative aggregates, such as subtotals

18.6 ROLLUP Operator: Example

SELECT department_id, job_id, SUM(salary)


FROM employees
WHERE department_id < 60
GROUP BY ROLLUP(department_id, job_id);

18.7 CUBE Operator

 CUBE is an extension to the GROUP BY clause.


 You can use the CUBE operator to produce crosstabulation values with a single SELECT
statement.

SELECT department_id, job_id, SUM(salary)


FROM employees
WHERE department_id < 60

Thawzh818@gmail.com Page 170


Treasure Island Training Service Ph:09691011157

GROUP BY CUBE (department_id, job_id) ;

18.8 GROUPING Function

The GROUPING function:


 Is used with either the CUBE or ROLLUP operator
 Is used to find the groups forming the subtotal in a row
 Is used to differentiate stored NULL values from NULL
 Returns 0 or 1 values created by ROLLUP or CUBE

SELECT department_id DEPTID, job_id JOB, SUM(salary), GROUPING(department_id)


GRP_DEPT, GROUPING(job_id) GRP_JOB
FROM employees
WHERE department_id < 50
GROUP BY ROLLUP(department_id, job_id);

18.9 GROUPING SETS

 The GROUPING SETS syntax is used to define multiple groupings in the same query.
 All groupings specified in the GROUPING SETS clause are computed and the results of
individual groupings are combined with a UNION ALL operation.
 Grouping set efficiency:
– Only one pass over the base table is required.
– There is no need to write complex UNION statements.
– The more elements GROUPING SETS has, the greater is the performance benefit.

SELECT department_id, job_id, manager_id, AVG(salary)


FROM employees
GROUP BY GROUPING SETS ((department_id, job_id, manager_id), (department_id,
manager_id),(job_id, manager_id));

Thawzh818@gmail.com Page 171


Treasure Island Training Service Ph:09691011157

SELECT department_id, job_id, manager_id, AVG(salary)


FROM employees
GROUP BY CUBE(department_id, job_id, manager_id);

SELECT department_id, job_id, manager_id, AVG(salary)


FROM employees
Group by department_id,job_id,manager_id
UNION ALL
SELECT department_id, NULL, manager_id, AVG(salary)
FROM employees
GROUP BY department_id, manager_id
UNION ALL
SELECT NULL, job_id, manager_id, AVG(salary)
FROM employees
GROUP BY job_id, manager_id

CUBE (a, b, c) Is equivalent GROUPING SET ((a, b, c), (a, b), (a, c), (b, c), (a), (b), (c), ())
to
ROLLUP(a, b, c) Is GROUPING SETS ((a, b, ROLLUP(a, b, c) c), (a, b),(a), ())
equivalent to

18.10 GROUPING SETS: Example


SELECT department_id, job_id, manager_id, AVG(salary)
FROM employees
GROUP BY GROUPING SETS ((department_id,job_id), (job_id,manager_id));

SELECT department_id, job_id, NULL as manager_id, AVG(salary) as AVGSAL


FROM employees
GROUP BY department_id, job_id
UNION ALL
SELECT NULL, job_id, manager_id, avg(salary) as AVGSAL
FROM employees
GROUP BY job_id, manager_id;

Thawzh818@gmail.com Page 172


Treasure Island Training Service Ph:09691011157

18.11 Composite Columns

 A composite column is a collection of columns that are treated as a unit. ROLLUP (a,
(b,c), d)
 Use parentheses within the GROUP BY clause to group (b, c) columns, so that they are
treated as a unit while computing ROLLUP or CUBE operations.
 When used with ROLLUP or CUBE, composite columns would require skipping
aggregation across certain levels.

GROUPING SETS Statements Equivalent GROUP BY Statements


GROUP BY GROUPING SETS (a, b, c) GROUP BY a UNION ALL
GROUP BY b UNION ALL
GROUP BY c
GROUP BY GROUPING SETS (a, b, (b, c)) (The GROUP BY a UNION ALL
GROUPING SETS expression has a composite GROUP BY b UNION ALL
column) GROUP BY b, c
GROUP BY GROUPING SETS ((a, b, c)) GROUP BY a, b, c
GROUP BY GROUPING SETS ((b) ( )) GROUP BY a UNION ALL
GROUP BY b UNION ALL
GROUP BY ()
GROUP BY GROUPING SETS (a, ROLLUP (b, GROUP BY a UNION ALL
c)) (The GROUPING SETS expression has a GROUP BY ROLLUP (b, c)
composite column. )

SELECT department_id, job_id, manager_id,SUM(salary)


FROM employees
GROUP BY ROLLUP( department_id,(job_id, manager_id));

This query results in the Oracle server computing the following groupings:
 (job_id, manager_id)
 (department_id, job_id, manager_id)

Thawzh818@gmail.com Page 173


Treasure Island Training Service Ph:09691011157

 (department_id)
 Grand total
The example in the slide can also be written as:

SELECT department_id, job_id, manager_id, SUM(salary)


FROM employees
GROUP BY department_id,job_id, manager_id
UNION ALL
SELECT department_id, TO_CHAR(NULL),TO_NUMBER(NULL), SUM(salary)
FROM employees
GROUP BY department_id
UNION ALL
SELECT TO_NUMBER(NULL), TO_CHAR(NULL),TO_NUMBER(NULL), SUM(salary)
FROM employees
GROUP BY ();

18.12 Concatenated Groupings


 Concatenated groupings offer a concise way to generate useful combinations of
groupings.
 To specify concatenated grouping sets, you separate multiple grouping sets, ROLLUP,
and CUBE operations with commas so that the Oracle server combines them into a
single GROUP BY clause.
 The result is a cross-product of groupings from each GROUPING SET

GROUP BY GROUPING SETS(a, b), GROUPING SETS(c, d)

SELECT department_id, job_id, manager_id, SUM(salary)


FROM employees
GROUP BY department_id, ROLLUP(job_id), CUBE(manager_id);

Thawzh818@gmail.com Page 174


Treasure Island Training Service Ph:09691011157

The example in the slide results in the following groupings:


 (department_id, job_id,) (1)
 (department_id, manager_id) (2)
 (department_id) (3)
The total salary for each of these groups is calculated. The following is another example of a
concatenated grouping.

SELECT department_id, job_id, manager_id, SUM (salary) totsal


FROM employees
WHERE department_id<60
GROUP BY GROUPING SETS (department_id), GROUPING SETS (job_id, manager_id);

19.1 Hierarchical Retrieval

 After completing this appendix, you should be able to:


 Interpret the concept of a hierarchical query

Thawzh818@gmail.com Page 175


Treasure Island Training Service Ph:09691011157

 Create a tree-structured report


 Format hierarchical data
 Exclude branches from the tree structure

19.2 Natural Tree Structure

19.3 Walking the Tree


Top down Column1=Parent Key

Column2=Child key

Bottom up Column1= Child key

Column2= Parent Key

19.4 Walking the Tree: From the Bottom Up

SELECT employee_id, last_name, job_id, manager_id


FROM employees
START WITH employee_id = 101
CONNECT BY PRIOR manager_id = employee_id ;

19.5 Walking the Tree: From the Top Down

SELECT last_name||' reports to '|| PRIOR last_name "Walk Top Down"


FROM employees

Thawzh818@gmail.com Page 176


Treasure Island Training Service Ph:09691011157

START WITH last_name = 'King'


CONNECT BY PRIOR employee_id = manager_id ;

19.6 Ranking Rows with the LEVEL Pseudocolumn

19.7 Formatting Hierarchical Reports Using Level and LPAD

Create a report displaying company management levels, beginning with the highest level and
indenting each of the following levels.

COLUMN org_chart FORMAT A12 SELECT LPAD(last_name, LENGTH(last_name)+(LEVEL*2)-


2,'_') AS org_chart
FROM employees
START WITH first_name='Steven' AND last_name='King'
CONNECT BY PRIOR employee_id=manager_id

19.8 Pruning Branches

Thawzh818@gmail.com Page 177


Treasure Island Training Service Ph:09691011157

20.1 Writing Advanced Scripts

After completing this appendix, you should be able to:

 Describe the type of problems that are solved by using SQL to generate SQL
 Create a basic SQL script
 Capture the output in a file
 Dump the contents of a table to a file
 Generate a dynamic predicate

20.2 Using SQL to Generate SQL

 SQL can be used to generate scripts in SQL.


 The data dictionary is:
– A collection of tables and views that contain database information
– Created and maintained by the Oracle server

Thawzh818@gmail.com Page 178


Treasure Island Training Service Ph:09691011157

20.3 Creating a Basic Script

SELECT 'CREATE TABLE ' || table_name || '_test ' || 'AS SELECT * FROM ' || table name || '
WHERE 1=2 ' AS "Create Table Script" FROM user_tables;

20.4 Controlling the Environment

Thawzh818@gmail.com Page 179


Treasure Island Training Service Ph:09691011157

20.5 Dumping the Contents of a Table to a File

INSERT INTO departments_test VALUES (10, 'Administration', 1700);

INSERT INTO departments_test VALUES (20, 'Marketing', 1800);

INSERT INTO departments_test VALUES (50, 'Shipping', 1500);

Thawzh818@gmail.com Page 180


Treasure Island Training Service Ph:09691011157

INSERT INTO departments_test VALUES (60, 'IT', 1400);

20.6 Generating a Dynamic Predicate

COLUMN my_col NEW_VALUE dyn_where_clause SELECT DECODE('&&deptno', null, DECODE


('&&hiredate', null, ' ', 'WHERE hire_date=TO_DATE('''||'&&hiredate'',''DD-MON-YYYY'')'),
DECODE ('&&hiredate', null, 'WHERE department_id = ' || '&&deptno', 'WHERE department_id
= ' || '&&deptno' || ' AND hire_date = TO_DATE('''||'&&hiredate'',''DD-MON-YYYY'')')) AS
my_col FROM dual;

SELECT last_name FROM employees &dyn_where_clause;

21.1 What Are Regular Expressions?

 You use regular expressions to search for (and manipulate) simple and complex patterns
in string data by using standard syntax conventions.
 You use a set of SQL functions and conditions to search for and manipulate strings in
SQL and PL/SQL.
 You specify a regular expression by using:
– Metacharacters, which are operators that specify the search algorithms
– Literals which are the characters for which ou are searching

21.2 Benefits of Using Regular Expressions

Regular expressions enable you to implement complex match logic in the database with the
following benefits:

 By centralizing match logic in Oracle Database, you avoid intensive strin rocessin of SQL
result sets b middle-tier applications.
 Using server-side regular expressions to enforce constraints, you eliminate the need to
code data validation logic on the client.

Thawzh818@gmail.com Page 181


Treasure Island Training Service Ph:09691011157

 The build-in SQL and PL/SQL regular expression functions and conditions make string
manipulations more powerful and easier than in previous releases of Oracle Database.

21.3 Using the Regular Expressions Functions and Condtions in SQL and PL/SQL

21.4 What are Metacharacters?

 Metacharacters are special characters that have a special meaning such as a wildcard, a
repeating character, a nonmatching character, or a range of characters.
 You can use several redefined metacharacter symbols in the pattern matching.
 For example, the ^ (f|ht) tps? : $ regular expression searches for the following from the
beginning of the string:
– The literals f or ht
– The t literal
– The p literal, optionally followed by the s literal
– The colon “:” literal at the end of the string

21.5 Using Metacharacters with Regular Expressions

Thawzh818@gmail.com Page 182


Treasure Island Training Service Ph:09691011157

21.6 Using Metacharacters with Regular Expressions

Syntax Description
^ Matches the beginning of a string
$ Matches the end of a string
\ Treats the subsequent metacharacter in the expression as a literal
\n Matches the nth (1–9) preceding subexpression of whatever is grouped within
parentheses. The parentheses cause an expression to be remembered; a
backreference refers to it.
\d A digit character
[:class:] Matches any character belonging to the specified POSIX character class
[^:class:] Matches any single character not in the list within the brackets

21.7 Regular Exprssions Functions and Conditions: Syntax

Thawzh818@gmail.com Page 183


Treasure Island Training Service Ph:09691011157

 source_char: A character expression that serves as the search value

 pattern: a regular expression , a text literal

 occurrence: A positive integer indicating which occurrence of pattern in source_char Oracle


Server should search for. The default is 1.

 position: A positive integer indicating the character of source_char where Oracle Server
should begin the search. The default is 1.

 return_option: -0: Returns the position of the first character of the occurrence (default)

- 1: Returns the position of the character following the occurrence 


replacestr: Character string replacing pattern

 match_parameter:

- “ c”: Use case-sensitive matching (default)

- “ i”: Use non-case-sensitive matching

- “n ”: Allows match-any character operator

Thawzh818@gmail.com Page 184


Treasure Island Training Service Ph:09691011157

- “m ”: Treats source string as multiple lines

 subexpr: Fragment of pattern enclosed in parentheses. You learn more about subexpressions
later in this appendix.

21.8 Performing a Basic Search by Using the REGEXP_LIKE Condition

SELECT first_name, last_name


FROM employees
WHERE REGEXP_LIKE (first_name, '^Ste(v|ph)en$');

SELECT last_name,phone_number, regexp_replace(phone_number,'\.','-') AS phone


FROM employees;

21.9 Finding Patterns by Using the REGEXP_INSTR Function

SELECT street_address, REGEXP_INSTR(street_address,'[[:alpha:]]') AS First_Alpha_Position


FROM locations;

21.10 Finding Patterns by Using the REGEXP_SUBSTR Function

SELECT street_address, REGEXP_SUBSTR(street_address, ' [^ ]+ ') AS Road


FROM locations;

21.11 Subexpressions

Thawzh818@gmail.com Page 185


Treasure Island Training Service Ph:09691011157

Select regexp_instr(„0123456789‟,
„(123)(4(56)(78))‟,
1,
1,
0,
„I‟,
1) “position”
From dual;

21.12 Why Access the nth Subexpression?

 A more realistic use: DNA sequencing


 You may need to find a specific subpattern that identifies a protein needed for immunity
in mouse DNA

SELECT REGEXP_INSTR(' ccacctttccctccactcctcacgttctcacctgtaaagcgtccctc


cctcatccccatgcccccttaccctgcagggtagagtaggctagaaaccagagagctccaagc
tccatctgtggagaggtgccatccttgggctgcagagagaggagaatttgccccaaagctgcc
tgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttcttgagttttca
ccctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagag
gctcttgggtctgatggccacatcctggaattgttttcaagttgatggtcacagccctgaggc
atgtaggggcgtggggatgcgctctgctctgctctcctctcctgaacccctgaaccctctggc taccccagagcacttagagccag ',
'(gtc(tcac)(aaag))',
1,
1,

Thawzh818@gmail.com Page 186


Treasure Island Training Service Ph:09691011157

0,
'i',
1) "Position"
FROM dual;

21.13 Using the REGEXP_COUNT Function

SELECT REGEXP_COUNT(
'ccacctttccctccactcctcacgttctcacctgtaaagcgtccctccctcatccccatgcccccttaccctgcagggta
gagtaggctagaaaccagagagctccaagctccatctgtggagaggtgccatccttgggctgcagagagaggag
aatttgccccaaagctgcctgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttcttgagtt
ttcaccctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagaggctcttgggtc
tgatggccacatcctggaattgttttcaagttgatggtcacagccctgaggcatgtaggggcgtggggatgcgctctg
ctctgctctcctctcctgaacccctgaaccctctggctaccccagagcacttagagccag', 'gtc') AS Count
FROM dual;

21.14 Regular Expressions and check constraints: Examples

ALTER TABLE emp8 ADD CONSTRAINT email_addr CHECK ( REGEXP_LIKE ( email,'@' ) )


NOVALIDATE;

INSERT INTO emp8


VALUES (500,'Christian','Patel','ChrisP2creme.com', 1234567890, '12-Jan-
2004','HR_REP',2000,null,102,40);

Quiz
With the use of regular expressions in SQL and PL/SQL, you can:
a. Avoid intensive string processing of SQL result sets by middle-tier applications
b. Avoid data validation logic on the client
c. Enforce constraints on the server
Answer: a, b, c

Thawzh818@gmail.com Page 187


Treasure Island Training Service Ph:09691011157

22. Oracle Database Architectural Components

After completing this appendix, you should be able to:


• List the major database architectural components
• Describe the background processes
• Explain the memory structures
• Correlate the logical and physical storage structures

22.1 Oracle Database Architecture: Overview

The Oracle Relational Database Management System (RDBMS) is a database management


system that provides an open, comprehensive, integrated approach to information
management.

Database ဆိုတာ data ေတြကို စုထားတ့ဲ့ အစုအေှး တစ္ခု a collection of data တစ္ခုပျဲ ဖစ္ပါတယ္။

သူ ့ရည္ရြယ္ခ်က္က related information ေတြကို store and retrieve လုပ္ဖို ့ပဲျဖစ္တယ္။

Oracle database က multiuser ေတြကို တခိ်န္ထဲမွာ same data and a large amount of data ေတြကို
ယံုၾကည္စိတ္ခ်စြာ access လုပ္ခင
ြ ့္ေပးနိုင္တယ္။ ျပီး high performance (လ်င္ျမန္မွန္ကန္) လည္းေပး

နိုင္တယ္။ ျပီးေတာ့ တခ်ိန္တည္း မွာ unauthorized access ကိုလည္းကာကြယ္နိုင္တယ္။

Failure ျဖစ္သြားတဲ့ file ေတြကိုလည္း တခ်ိန္တည္း တျပိဳင္တည္း efficient solution ေတြထုတ္ေပးနိုင္တယ္။

Thawzh818@gmail.com Page 188


Treasure Island Training Service Ph:09691011157

22.2 Oracle Database Server Structures

Oracle Database မွာ components နွစ္ခုရွိတယ္။ instance and database ပဲျဖစ္ပါတယ္။ Instance က
memory လုိ ့သိထားျပီး database ကေတာ့ storage လုိ ့သိထားေပးပါ။ အဲဒီ instance တခုလံုးရဲ ့ memory
structure က operating system ကို install လုပ္ထားတဲ့ computer ရဲ ့ main memory ေပၚမွာပဲရွိပါတယ္။

ဒါေၾကာင့္ instance ကို database server install လုပ္ထားတဲ့ OS ရဲ ့ Memory လို ့လည္း သိထားေပးပါ။

Instance

Instance မွာ System Global Area (SGA) and Background Process ဆိုျပီး နွစခ
္ ု ရွိတယ္။ အခိ်န္တိုင္း
instance စလိုက္တာနဲ ့ SGA က အလုပ္တာှန္ေတြကို စီမံ ခန့္ခဲြတယ္။ အဲဒီ အခ်ိန္မွာ background process
က စ အလုပ္လုပ္တယ္။

Thawzh818@gmail.com Page 189


Treasure Island Training Service Ph:09691011157

Database

Database မွာ က physical structure and logical structure ဆိုျပီး ရွိတယ္။ physical structure and
logical structure က ကြျဲ ပားပါတယ္။ သို ့ေပမယ့္ physical stroge ကို logical structure structure ကို
access လုပ္တာကို လံုးှ effect မျဖစ္ေစဘဲ managed လုပ္နိုင္ပါတယ္။ physical stroge structure မွာ file
သံုးခု ရွိတယ္။
ဿ. Control files သည္ database ရဲ ့ physical stroage structure ကို record လုပ္ထားတဲ့ binary file
ပဲျဖစ္တယ္။
၀. Data files သည္ data ကို store လုပ္ထားတဲ့ ေနရာပဲျဖစ္တယ္။
၁. Redo log files သည္ database recovery လုပ္ဖို ့အတြက္ information ေတြသိမ္းထားတဲ့
ေနရာပဲျဖစ္တယ္။ ပိုျပီး အေသးစိတ္ေတြ သိခ်င္ရင္ oracle ရဲ ့ official page မွာ ရွာဖတ္ၾကည့္ပါေနာ္။

22.3 Connecting to the Database

 Connection: Communication pathway between a user process and a database instance


 Session: A specific connection of a user to a database instance through a user process

Database မွာ ရွိတဲ့ information ေတြရယူဖို ့ဆိုရင္ user က database နဲ ့connection ရွဖ
ိ ို့လိုတယ္။
SQL*Plus ကေတာ့ oracle server ေတြအတြက္ connection ယူဖို ့တစ္ခုတည္းေသာ Tool ပါ။ username

နဲ ့password ကိုသံုးျပိး connection ယူပါတယ္။ အဲလို connection ယူျပီးလို ့login ျဖစ္သြားတဲ့အေျခအေနကို

session လို ့ေခၚပါတယ္။ log out မျဖစ္မခ်င္း session ရွိေနတယ္လို ့ေျပာျပီး log out ျဖစ္သြားရင္ေတာ့
session မရွိေတာ့ဘူးလို ့ေျပာပါတယ္။

Thawzh818@gmail.com Page 190


Treasure Island Training Service Ph:09691011157

22.4 Interaction with an Oracle Database

ေအာက္ပါတို ့က connection ဘယ္လိုလုပ္တယ္။ user တစ္ေယာက္ ရဲ ့basic လုပ္ငန္းေတြပဲျဖစ္ပါတယ္။


user တစ္ေယာက္ login လုပ္ျပီး ေတာ့ sql statement ေတြလုပ္တဲ့အခ်ိန္မွာ ျဖစ္သြားတဲ့ Process
ေတြပဲျဖစ္ပါတယ္။
1. instance တစ္ခု က ဘယ္မွ စတင္ အလုပ္လုပ္လည္း ဆိုေတာ့ database installed လုပ္ထားတဲ့
host or database server ေပၚမွာ စတင္ပါတယ္။
2. user တစ္ေယာက္က login လုပ္တယ္။ အဲဒါကို connection လုပ္တယ္လို ့ေခၚတယ္။ connection
က local connection, client server connection or a three-tier connection from a middile tier
ပဲျဖစ္တယ္။
3. Oracle server က Oracle Net services handler ရွိတဲ့ listener တစ္ခုကို run တယ္။ အဲဒိ မွာ
server က ှင္လာတဲ့ connection ကို detect လုပ္တယ္။ ျပီးေတာ့ dedicated server process အျဖစ္
create လုပ္ျပစ္တယ္။
4. DML statement ေတြကို user က run တယ္ ျပီးေတာ့့ အဲဒီ transaction ကို commit လုပ္ျပစ္တယ္။
5. အဲဒီအခ်ိန္မွာ server process က ပထမဆံုး DML statement ကို လက္ခံရရွိတယ္။ ျပီးေတာ့ shared
pool ကို စစ္တယ္။ shared pool area က အဲဒီ statement ကို စစ္တယ္။ ျပီးေတာ့ user‟s access privileges
ရွိလားမရွိလားဆိုတာကို requested data ေတြအတြက္ စစ္တယ္။ အဲဒီ share pool ထဲမွာ အလားတူ sql
statement ေတြရွိတယ္ဆိုရင္ အလုပ္လုပ္ေပးတယ္။ မရွိဘူးဆိုရင္ new shared SQL area တစ္ခု create

Thawzh818@gmail.com Page 191


Treasure Island Training Service Ph:09691011157

လုပ္ေပးျပီး အလုပ္လုပ္ေပးတယ္။ sql developer tool မွာ ဆိုရင္ history ထဲမွာ ျမင္ရတယ္။ ကိုယ္ေရးခဲ့တဲ့
statement ေတြအကုန္ကို ျမင္ရတယ္။
6. Server process က လိုခ်င္တဲ့ result ကို table ထဲက ထုတ္ေပးသလို System Globle Area (SGA)
ထဲက cached ထဲက ပါ ထုတ္ေပးပါတယ္။
7. SGA ထဲ data ကို server process က modifies လုပ္ေပးတယ္။ Transaction ကို commit
command သံုးျပီး လုပ္လိုက္တာေျကာင့္ Log Writer Process (LGWR) က redo log file ထဲမွာ
transaction ကို ခ်က္ျခင္း record လုပ္လို္က္တယ္။ old data ကို redo log files ထဲမွာ သိမ္းတယ္။ new
data ကို hard disk ေပၚတြင္သိမ္းတယ္။
8. transaction အဆင္ေျပရင္ successful message ကို return ျပန္တယ္။ ဥပမာ insert statement
လုပ္ရင္ 1 row insered ဆိုျပီး return ျပန္တယ္။ တကယ္ လို ့ success မျဖစ္ရင္ လည္း မျဖစ္တာကို return
ျပန္တယ္။ အဲဒီလို return ျပန္တဲ့ code ကို ယူျပီး application ေတြမွာ ျပန္ျပတယ္။
9. အဲဒိ အေပၚက process ေတြလုပ္ေနတဲ့ အခ်ိန္မွာပဲ တျခား background process ေတြ
အလုပ္လုပ္ေနတယ္။

22.5 Oracle Memory Architecture

Thawzh818@gmail.com Page 192


Treasure Island Training Service Ph:09691011157

Oracle Database က memory structure ကို အမ်ိိုးမ်ိဳး create လုပ္ျပီး အသံုးခ်တယ္။


ဥပမာ။ ။ User ေတြ အမ်ားၾကီးရွိတယ္။ အဲဒီ အခ်ိန္မွာ memory က running လုပ္ေနတဲ့ program code
ေတြကို store လုပ္တယ္။ ျပီးေတာ့ connection ရွိေနတဲ့ user တစ္ေယာက္ခ်င္းစီကို private data area
ထုတ္ေပးတယ္။ အဓိက memory structure နွစ္ခုရွိတယ္။ System Global Area (SGA) and Program
Global Area (PGA) ပဲျဖစ္ပါတယ္။
 Shared memory structure တစ္ခုလံုးကို System Global area လို ့ေခၚပါတယ္။ အဲဒီထဲမွာ oracle
database instance အတြက္ data and control information ေတြရွိတယ္။ instance ဆိုတာ
database installed လုပ္ထားတဲ့ host ကိုေျပာတာပါ။ SGA ကို server process and background
process ေတြက shared သံုးတယ္။ ဥပမာ။ SGA ထဲမွာ cached data လည္းရွိေနသလို sql area
လည္းရွိေနတယ္။
 PGA မွာလည္း server and background process အတြက္ data and control information
ေတြပါှင္ပါတယ္။ PGA က shared memory မဟုတ္ဘူး server process and background
process ေတြမွာ ကိုယ္ပိုင္ PGA ရွိတယ္။
Note: SGA က shared memory, PGA က nonshared memory or own memory
SGA က Instance အတြက္ PGA က server and background process အတြက္။

22.6 17.3.1 System Global Area (SGA)

 Database Buffer Cache: Database ထဲက ဆြထ


ဲ ုတ္တဲ့ data ေတြ ရွိတယ္။
 Redo Log Buffer: transaction ျပီးလို ့ commit command မလုပ္ခင္ old data and new data က
redo log buffer ထဲမွာရွိေနတယ္။ commit လုပ္ျပီးရင္ old data က hard disk ေပၚက redo log
file ထဲကိုေရာက္သြားျပီး new data က hard disk ေပၚက Data file ထဲကို ေရာက္သြားတယ္။
 Shared pool: user ေတြ shared သံုးရတဲ ့memory area တစ္ခုပျဲ ဖစ္တယ္။
 Large pool: large pool ကေတာ့ အျမဲတန္းရွိေနတဲ့ memory area တစ္ခု မဟုတ္ဘူး။ သူက Large
processes ေတြအတြက္ large memory allocation တစ္ခုပဲ ျဖစ္တယ္။ Oracle backup and
recovery operations and input/output (I/O) server processes ေတြအတြက္ Large memory
area ပဲျဖစ္တယ္။
 Java pool: java virtual machine (JVM) အတြင္း Session အားလံုး အတြက္ java pool
ကိုသံုးတယ္။
 Streams pool: database backup and recovery operation ေတြမွာ streams pool ကို သံုးတယ္။
ေနာက္ inport or export လုပ္တဲ့ အခ်ိန္မွာ သံုးတယ္။

Thawzh818@gmail.com Page 193


Treasure Island Training Service Ph:09691011157

Note: Enterprise Manager or SQL*Plus ကို သံုးျပီး database server ကို login လုပ္တဲ့အခါမွာ
အသံုးျပဳလိုက္တဲ့ SGA memory amount ကို ျပပါတယ္။
Dynamic SGA infrastructure နဲ ့database buffer cache, shared pool, large pool, java pool and
streams pool ေတြက changes ျဖစ္ပါတယ္။ instance ကို shut down မလုပ္ဘဲ changes
ျဖစ္သြားတာပါ။
Oracle database က parameter ကိုသံုးျပီး memory structure ကို create or configure လုပ္လို ့
ရပါတယ္။ ဥပမာ။ ။ SGA_TARGET ဆိုတဲ့ parameter တစ္ခု create လုပ္တယ္။ ျပီးေတာ့ SGA total
size ကို သတ္မွတ္တယ္။ တကယ္လို ့ 0 လို ့ သတ္မွတ္လိုက္ ရင္ Automatic shared memory
management ကို disabled လုပ္တာနဲ ့တူတူပါပဲ။

22.7 Process Architecture

 User process:
- Is started when a database user or a batch process connects to the Oracle Database

 Database processes:
- Server process: Connects to the Oracle instance and is started when a user establishes a
session
- Background processes: Are started when an Oracle instance is started

Thawzh818@gmail.com Page 194


Treasure Island Training Service Ph:09691011157

User Processes

- User process ဆိုတာ application ေတြက database ကို connect လုပ္တာမ်ိိဳး သို့မဟုတ္
database ကို တိုက္ရိုက္ oracle tool ေတြသံုးျပီး login လုပ္တာမ်ိဳးပါ။
- Oracle database processes ဆိုတာ က server process and background process
နွစ္မ်ိဳးရွိတယ္။
- User တစ္ေယာက္ က application program သို ့မဟုတ္ sql plus ကေန database ကို စ connect
လုပ္တဲ့အခ်ိန္မွာ oracle database က application ေတြ အလုပ္လုပ္ဖို ့user process တစ္ခု
လုပ္ေပးတယ္။
ေနာက္ server process တစ္ခု create လုပ္ေပးျပီး user process က လုပ္လိုက္တဲ့ command
ေတြကို
execute လုပ္ေပးတယ္။ အဲဒီ အခိ်န္မွာ oracle database မွာ background process အစုလိုက္
ရွိေနတယ္။ တစ္ခုနဲ ့တစ္ခု ခ်ိတ္ဆက္အလုပ္လုပ္ေပးတယ္။ အဲဒီ background process က
operating system နဲ ့အတူ oracle ရဲ ့ memory structure နဲ ့ အတူတျြဲ ပီး အလုပ္လုပ္ေပးတယ္။
ျပီးရင္ disk ေပၚကို input output ေတြကို write လုပ္ေပးတယ္။ အျခားလုိအပ္တဲ့ အလုပ္ေတြကို
လည္း လုပ္ေပးတယ္။
- အလုပ္လုပ္ေနတဲ့ Process structure ေတြကေတာ့ oracle database configurations ေတြေပၚ
တူတည္ျပီး ကြျဲ ပားတယ္။ operating system ေပၚလည္း မူတည္တယ္။ ေနာက္တစ္ခု က database
options ေပၚမူတည္တယ္။ ကိုယ္ database installation လုပ္ခ့တ
ဲ ဲ့ options ေတြေပၚမူတည္တယ္လို ့
ေျပာတာပါ။
- Connected လုပ္တဲ့ users ေတြအတြင္ code ကို dedicated server or shared server အျဖစ္
configured လုပ္ထားတယ္။
 With a dedicated server, for each user, the database application is run by a different
process (a user process) than the one that runs the Oracle server code (a dedicated
server process).
 A shared server eliminates the need for a dedicated server process for each
connection. A dispatcher directs multiple incoming network session requests to a
pool of shared server processes. A shared server process serves any client request.
Server Processes
Oracle database က user processes ေတြရဲ ့ request ေတြက instance ကို connect လုပ္ဖို ့ server
process ကို create လုပ္တယ္။ အခ်ိုဳ ့ application ေတြက database server ေပၚမွာပဲ same pc ေပၚမွာပဲ
အလုပ္လုပ္တယ္။ အဲဒီ လို လုပ္ထားရင္ user process and server process ကို single process အျဖစ္

Thawzh818@gmail.com Page 195


Treasure Island Training Service Ph:09691011157

အလုပ္လုပ္ လိုက္ေတာ့ system အလုပ္မ်ားတာေတြကို ေလ်ွာ့ခ်ေပးတယ္။ သို ့ေသာ္ application and oracle
database ေတြ different pc ေပၚ မွာ အလုပ္လုပ္တဲ့အခါ user process and separate server process က
အတူ communicate လုပ္ျပီးအလုပ္လုပ္တယ္။
Server processes က user‟s application တစ္ခုစီ ကိုယ္စား အလုပ္ေတြလုပ္ေပးတယ္။
1. Application က ထုတ္လိုက္တဲ့ sql statement ကို parse and run လုပ္ေပးတယ္။
2. Daisk ေပၚက data file ထဲက လိုအပ္တဲ့ data blocks ေတြကို ဖတ္တယ္။ ျပီးေတာ့ system global
area ထဲ က shared database buffers ထဲကို ပို ့ေပးတယ္။
3. အဲဒီ နည္း နဲ ့ result ေတြကို application ပိုင္းက ရတယ္။

Background Processes
Users အမ်ားၾကီးကို performance ေကာင္းေအာင္ လုပ္ဖို ့အတြက္ဆိုရင္ multiprocess oracle database
system က background process ေတြကို သံုးတယ္။ instance တစ္ခု မွာ background process ေတြ
အမ်ားၾကီးရွိတယ္။ oracle database instance ကို စဖို ့ Startup လုပ္ဖို ့အတြက္ဆိုရင္ ေအာက္ ပါ
background process ေတြ မရွမ
ိ ျဖစ္ လိုအပ္တယ္။
 Database writer (DBWn)
 Log writer (LGWR)
 Checkpoint (CKPT)
 System monitor (SMON)
 Process monitor (PMON)
ေအာက္ပါ background process ေတြက ေတာ့ လိုေတာ့လိုတယ္။ optional ပါ။
 Recover (RECO)
 Job queue
 Archiver (ARCn)
 Queue Monitor (QMNn)
အျခား background process ေတြကေတာ့ advanced configurations ေတြအတြက္ လိုအပ္ပါတယ္။
ဥပမာ။ ။ Real Application Clusters (RAC). လိုမ်ိဳးပါ။ background process ေတြကို ၾကည့္ခ်င္ရင္
select * from V$BGPROCESS ;

အဲဒိ V$BGPROCESS data dictionary view မွာ ၾကည့္ပါ။ operating system အားလံုးမွာ instance ကို
စလိုက္တာနဲ ့ background processes အလုိအေလ်ာက္ ထုတ္ေပးတယ္။

Thawzh818@gmail.com Page 196


Treasure Island Training Service Ph:09691011157

Database Writer Porcess


Writes modified (dirty) buffers in the database buffer cache to disk:
 Asynchronously while performing other processing
 Periodically to advance the checkpoint

DBWn

Database buffer cache Database writer process Data Files

Database Writer process က buffer ထဲမွာ ရွိေနတဲ့ content ေတြကို data file (disk) ေပၚမွာ write
လုပ္ေပးတယ္။
System အမ်ားစု မွာ database writer process (DBW0) တစ္ခု တည္းနဲ ့လံုေလာက္ ေသာ္လည္း data
ေတြအမ်ားၾကီး write လုပ္ဖို ့လိုအပ္လာရင္ performance အတြက္ဆိုရင္ database writer process ကို
configure လုပ္လို ့ရတယ္။ (from DBW1 to DBW9 and DBWa to DBWj ) သို ့ေပမယ္ ့ ထပ္ျပီး create
လုပ္လိုက္တဲ့ Database writer process က uniprocessor system ေတြေပၚမွာ အလုပ္မလုပ္ပါဘူး။
Database Buffer cache ထဲမွာ buffer ကို modified လုပ္တဲ့အခါမွာ သူ ့ကို “dirty” လို ့ marked
လုပ္ထားျပီး LRUW list ထဲကို ထည့္လိုက္ပါတယ္။ system change number (SCN) order နဲ ့သိမ္းပါတယ္။
အဲလို ခ်ိန္းလိုက္တာ နဲ ့Redo order အရ redo log files ထဲမာွ changed buffer ကို written လုပ္တယ္။

Log Writer Process

 Writes the redo log buffer to a redo log file on disk


 LGWR writes:
– When a process commits a transaction
– When the redo log buffer is one-third full
– Before a DBWn process writes modified buffers to disk

Thawzh818@gmail.com Page 197


Treasure Island Training Service Ph:09691011157

Redo log buffer Log writer process Redo log files

Redo log buffer ထဲမွာ ရွိေနတဲ ့ entries ေတြအားလံုးကို redo log file ထဲမွာ ေရးတာကို log writer
process လို ့ေခၚပါတယ္။ redo log buffer ကို circular buffer လို ့လည္းေခၚပါတယ္။ redo log buffer
ထဲက entries ေတြကို redo log file ထဲကို ေရးလိုက္တဲ့အခ်ိန္မွာ buffer ထဲကို အသစ္ ထပ္ေရာက္လာတယ္။
LGWR ကပံုမွန္ဆို write လုပ္တာ အရမ္းျမန္တယ္။ အသစ္ေတြ လက္ခံဖို ့ buffer ထဲမွာ space
အျမဲရွိေနတယ္။
LGWR ဘယ္အခါမွာ အလုပ္စ လုပ္လဲဆုိေတာ့
1. User process ဘက္ transaction ကို commit လုပ္တဲ့အခါ
2. Redo log buffer ထဲမွာ သံုးပံု တစ္ပံု ျပည့္သြားတဲ့အခါ
3. DBWn process က modified data ကို disk ေပၚကို သြားမေရးမီ မွာ လို အပ္ရင္ လုပ္ေပးတယ္ ။

Checkpoint Process

Records checkpoint information in:

 The control file


 Each datafile header

Control file

CKPT

Checkpoint process Data Files

Thawzh818@gmail.com Page 198


Treasure Island Training Service Ph:09691011157

Checkpoint ဆိုတာ database ရဲ ့redo thread ထဲမွာ ရွိတဲ့ system change number ကို define
လုပ္ထားတဲ့ data structure တစ္ခုပျဲ ဖစ္ပါတယ္။ checkpoints ကို control file ထဲမွာ recorded
လုပ္ထားတယ္။ Data file header တစ္ခုစီ နဲ ့ crucial element of recovery နဲ ့ recorded လုပ္ထားတာပါ။
checkpoint တစ္ခု ျဖစ္တဲ့အခ်ိန္မွာ data files အားလံုးရဲ ့ header ကို update လုပ္ေပးရမယ္။ အဲဒါကို CKPT
ကလုပ္ေပးပါတယ္။

System Monitor Process

 Performs recovery at instance startup


 Cleans up unused temporary segments

System monitor process က လိုအပ္ရင္ instance စတဲ့အခ်ိန္မွာ recovery ကိုလုပ္ေဆာင္ေပးတယ္။


အသံုးမျပဳတာ ၾကာတဲ့ temporary segments ေတြကို clean up လုပ္ေပးတယ္။ transaction ကို
terminated လုပ္လိုက္ရင္ instance recovery ကို skip လုပ္ျပစ္တယ္။ ဘာေၾကာင့္လဲဆိုရင္ file read or
offline errors ေၾကာင့္ပါ။ system monitor က tablespace ကို online ျပန္ျဖစ္တဲ့အခ်ိန္မွာ recover
ျပန္လုပ္ေပးတယ္။ SMON က အဲလို recover လုပ္ဖို ့လိုအပ္လားမလိုအပ္လား check ေပးပါတယ္။

Process Monitor Process

 Performs process recovery when a user process fails:


– Cleans up the database buffer cache
– Frees resources used by the user process
 Monitors sessions for idle session timeout

Thawzh818@gmail.com Page 199


Treasure Island Training Service Ph:09691011157

 Dynamically registers database services with listeners

Process monitor (PMON) က user process fail ျဖစ္တဲ့အခ်ိန္မွာ recovery လုပ္ေပးတယ္။ PMON က
Database buffer cache ကို cleaning လုပ္ေပးတယ္။ ျပီးေတာ့ user process အသံုးျပဳတဲ ့resource ေတြကို
free လုပ္ေပးတယ္။ ဥပမာ active transaction table ရဲ ့ status ကို reset လုပ္တယ္။ ျပီးရင္ locks ကို
releases လုပ္တယ္။ ျပီးေတာ့ process ID ကို active prcess list ထဲက ေန remove လုပ္တယ္။ အဲဒိ
အခ်ိန္မွာ PMON က system process နဲ ့dispatcher ရဲ ့ status ကို စစ္တယ္။ ျပီးေတာ့ stopping ျဖစ္သြားတဲ့
process ကို ျပန္ျပီး restart လုပ္ေပးတယ္။ oracle database ကို terminated လုပ္တာမ်ိဳးေတာ့ မဟုတ္ဘူး ။
PMON က network listner နဲ ့ instance and dispatcher process ေတြရဲ ့ information ေတြကို register
လုပ္တယ္။

22.8 Oracle Database Storage Architecture

Thawzh818@gmail.com Page 200


Treasure Island Training Service Ph:09691011157

Oracle Database ရဲ ့storage structure မွာဆိုရင္ အဓိက file သံုးခုရွိတယ္။1. Control file, 2. Data files,
3. Online redo log files. ပဲျဖစ္တယ္။
 Control files: က database မွာ အေရးအၾကီးဆံုး file ပါ။ သူက physical database structure
information ေတြပါှင္ပါတယ္။ control file မရွိဘဲ data file ကို open လုပ္လို ့မရဘူး ။ database
ထဲက data ေတြကို access လုပ္လို ့မရဘူး ။
 Data files: က user information ေတြ ပါှင္တယ္။ application က လာတဲ့ data ေတြရွိတယ္။
ေနာက္ meta data ေတြရွိတယ္။ meta data ဆိုတာ build in လုပ္ထားတဲ့ function ေတြပါ။ ေနာက္
data dictionary ေတြပါှင္ပါတယ္။ data dictionary ဆိုတာ database server ရဲ ့ build in ပါတဲ့
table ေတြကိုေျပာတာပါ။
 Online redo log files: database recovery လုပ္ဖို ့အတြက္ online redo log file ကိုသံုးတယ္။
တကယ္လို ့database server က crashes ျဖစ္ရင္ data file က lose မျဖစ္ဘူးဆိုရင္ instance က
database ကို ျပန္ ျပီး recover လုပ္နိုင္တယ္။ အဲလိုလုပ္ဖို ့online redo log file ထဲက information
ကိုေတာ့သံုးရပါတယ္။
ေနာက္ထပ္ database ကို run ဖို ့အေရးၾကီးတဲ့ file ေတြကေတာ့ 1. Backup files, 2.Archived log files 3.
Parameter file, 4. Passwrod file, 5. Network files, 6.Trace files, 7. Alert log files ပဲျဖစ္ပါတယ္။

 Backup files: database recovery လုပ္ဖို ့အတြက္သံုးတယ္။ backup လုပ္ထားတဲ့ file ကို ျပန္ျပီး
recovery လုပ္လို ့ရပါတယ္။ user က damaged လုပ္မိတဲ့ အခါေတြမွာ backup လုပ္ထားတဲ့ file ကို
recovery ျပန္လုပ္ပါတယ္။
 Archived log files: archived log file ထဲမွာ data changes ေတြ သိမ္းထားတယ္။ archived logs
က restored data files ေတြ recovery ကို လုပ္ေဆာင္ေပးတယ္။
 Parameter file: parameter တစ္ခုစီ ရဲ ့ တန္ဘိုးေတြ initialization parameters list ေတြ ပါှင္တဲ့
File ေတြပဲျဖစ္ပါတယ္။ Server parameter file and initialization parameter file
ေတြပဲျဖစ္ပါတယ္။
 Password file: sysdba / sysoper / sysasm role ရွိတဲ့ users ေတြကို database ကို remotely
connect လုပ္ဖို ့ခြင့္ျပဳပါတယ္။ ေနာက္ administrative tasks ေတြကိုလည္း လုပ္ေဆာင္ေပးပါတယ္။
 Network files: database listener ကို start လုပ္ဖို ့အတြက္ သံုးပါတယ္။ user connections
အတြက္ လိုအပ္တဲ့ information ေတြကိုသိမ္းထားပါတယ္။
 Trace files: server process and background process တစ္ခုစီက သက္ဆိုင္တဲ့ trace file
ေတြမွာ ေရးတယ္။ process တစ္ခု က internal error ကို detect လုပ္မိတဲ့အခါ မွာ process က
information ေတြကို dump ထုတ္တယ္။ backup သေဘာပါပဲ။ trace file ထဲကို ပို ့လိုက္တာပါ။
အဲလို trace file ကို database administrator က ဖတ္ဖို ့ပါ။

Thawzh818@gmail.com Page 201


Treasure Island Training Service Ph:09691011157

 Alert log files: trace entries ေတြ ရွိတယ္။ Database ရဲ ့ alert log ကေတာ့ messages and
errors ေတြပဲျဖစ္ပါတယ္။ instance တစ္ခုစီမွာ alert log file တစ္ခုစီရွိပါတယ္။ oracle က အဲဒီ alert
log file ကို ၾကည့္ဖို ့recommand ေပးထားပါတယ္။

22.9 Logical and Physical Database Structures

Oracle database မွာ logical and physical storage structure ဆိုျပီးရွိပါတယ္။ physical ကေတာ့ oracle
database ကို install လုပ္ထားတဲ့ server ရဲ ့hard disk ပါ။ OS block လို ့ေခၚျပီး data file ကေတာ့ oracle
database install လုပ္တဲ့အခ်ိန္မွာ hard disk ေပၚတြင္ ပဲ data file အေနန ့ဲ သတ္မွတ္ေပးခဲ့ရပါတယ္။

22.9.1 Tablespaces
Database ကို tablespace လုိ ့ေခၚေသာ logical storage units ေတြအျဖစ္ ပိင
ု း္ ျပီး အလုပ္လုပ္တယ္။ user
တစ္ေယာက္ စီ ကို tablespace သတ္မွတ္ေပးသလို unlimited လည္း ထားလို ့ရပါတယ္။ default
tablespace လည္းထားပါတယ္။

Thawzh818@gmail.com Page 202


Treasure Island Training Service Ph:09691011157

22.9.2 Databases, Tablespaces, and Data Files


ပံုတြင္ၾကည့္ပါ။ database တစ္ခုမွာ tablespace အမ်ားၾကီးရွိပါတယ္။ tablespace တစ္ခု မွာ data file
အမ်ားၾကိးရွိပါတယ္။ user တစ္ေယာက္ကို tablespace တစ္ခု သတ္မွတ္ေပးခဲ့ရင္ အဲဒီ tablespace ေပၚမွာ
data file ေတြအမ်ားၾကီးရွိတယ္လို ့ေျပာပါ။ database server တစ္ခု မွာ user ေတြအမ်ားျကိးရွိပါတယ္။
ထို ့အတြက္ user အားလံုး အတြက္ tablespace ေတြအမ်ားၾကီးပါ။
22.9.3 Schemas
Schema name နဲ ့user name က တူပါတယ္။ ဒါေပမယ့္ schema ဆိုတာဘာလည္း ဆိုေတာ့ user ပိုင္တဲ့
database objects ေတြ Collection တစ္ခုပျဲ ဖစ္ပါတယ္။ schema object က database‟s data ကို
တိုက္ရိုက္ကိုယ္စားျပဳတဲ့ logical structure ပဲျဖစ္ပါတယ္။ schmea object ေတြမွာ table, views,
sequences, stored procedures, synonyms indexes, clusters and database link ေတြပါှင္ပါတယ္။
ေနာက္ Schema object ေတြမွာ application က create လုပ္လိုက္တဲ့ အရာအားလံုးက database ထဲက
schema ထဲမွာသိမ္းပါတယ္။
22.9.4 Data Blocks
Oracle database ရဲ ့data ေတြကို data blocks ထဲမွာသိမ္းပါတယ္။ data block က disk ေပၚမွာ ရွိေနတဲ့
physical database space ရဲ ့bytes ေတြန ဲ့သတ္မွတ္ပါတယ္။ data block size ကို tablespace တစ္ခုစီနဲ ့
သတ္မွတ္ပါတယ္။ database တစ္ခုစီက free database space ကို oracle data blocks ထဲမွာပဲသတ္မွတ္ပါ
တယ္။
22.9.5 Extents
Logical database space ေနာက္ တစ္ခုကို an extent လို ့ေခၚတယ္။ continuous data block တစ္ခုပဲ
ျဖစ္ပါတယ္။ information ေတြသိမ္းဖို ့သူ ့ကို အသံုးျပဳတယ္ ။
22.9.6 Segments
Extent လို ့ေခၚတဲ့ logical database space ရဲ ့အေပၚမွာ segment တစ္ခုရွိတယ္။ segment တစ္ခု ကို
extents အမ်ားၾကီး နဲ ့ဖြဲ ့စည္းထားပါတယ္။ segments ထဲမွာဘာေတြပါလဲဆိုေတာ့
 Data segments: clustered လည္း မဟုတ္ indexed လည္း မလုပ္ထားတဲ့ table ေတြမွာ data
segment တစ္ခုရွိပါတယ္။ သို ့ေပမယ့္ external tables, global temporary tables and
partitioned tables ေတြမွာေတာ့ data segment တစ္ခု ထက္ပိုရွိပါတယ္။ table အားလံုးရဲ ့ data
ေတြအားလံုးကို သူတို ့ရဲ ့data segments ေတြရဲ ့extents ထဲမွာသိမ္းပါတယ္။ partitioned table
အတြက္ partition တစ္ခုစီအတြက္ data segment တစ္ခုရွိပါတယ္။ each cluster တစ္ခုစီမွာ data
segment တစ္ခုစီရွိပါတယ္။ cluster ထဲမွာရွိေနတဲ့ table တိုင္းရဲ ့data ေတြကို cluster ရဲ ့ data
segment ထဲမွာသိမ္းထားပါတယ္။
 Index segments: index တစ္ခုစီမွာ index segment တစ္ခုရွိတယ္။ data အားလံုးကို
သိမ္းထားတယ္။ partitioned index တစ္ခုအတြက္ဆိုရင္ partition တစ္ခုစီမွာ index segment
တစ္ခုရွိတယ္။
 Undo segments: undo tablespace တစ္ခုစီကို database instance တစ္ခုစီမွာ create လုပ္ထား

Thawzh818@gmail.com Page 203


Treasure Island Training Service Ph:09691011157

တယ္။ database instance ထဲမွာ undo seements ေတြပါတယ္။ undo segment ထဲမွာရွိတဲ့
information ေတြကို read-consistent database information ေတြထုတ္ဖို ့သံုးတယ္။ database
recovery လုပ္ေနစဥ္္တြင္ users ေတြရဲ ့uncommited transtactions ေတြကို roll back လုပ္ဖို ့
အတြက္သံုးတယ္။
 Temporary segments: oracle database က temporary segments ေတြကို temporary area
လုိတဲ့ အခ်ိန္မွာ create လုပ္တယ္။ statement ေတြ execute လုပ္ျပီးတဲ့အခါမွာ temporary
segment‟s extend ကို returned ျပန္တယ္။ user တိုင္းအတြက္ default temporary space လည္း
သတ္မွတ္လု ့ိရပါတယ။္
Oracle database က space ကို dynamically ေနရာခ်တယ္။ တကယ္လို ့segment တစ္ခုရဲ ့ရွိေနတဲ့
extents ေတြျပည့္သြားရင္ ေနာက္ထပ္ extents ေတြထပ္ထည့္တယ္။ ထပ္ထည့္တဲ့ extents ကို ေနရာခ်ဖို ့
လိုတာေၾကာင့္ segment တစ္ခု ရဲ ့extents ေတြက disk ေပၚမွာ အဆက္မျပတ္ အတူအကြ ရွိမေနဘူး။
22.10 Processing a SQL Statement

 Connect to an instance using:


– The user process
– The server process
 The Oracle server components that are used depend on the type of SQL statement:
– Queries return rows
– Data manipulation language (DML) statements log changes.
– Commit ensures transaction recovery
 Some Oracle server components do not participate in SQL statement processing

SQL statements ကို အလုပ္လုပ္ ဖို ့ oracle instance ရ ဲ့ components အားလံုးကိုေတာ့ အသံုးမျပဳဘူး
။ user process and server process ကို oracle instance ကို connect လုပ္ဖို ့သံုးတယ္။ user process
and server process က oracle instance ရဲ ့အစိတ္အပိုင္းေတြေတာ့ မဟုတ္ဘူး။ သို ့ေသာ္ sql
statement process လုပ္ဖို ့အတြက္လိုအပ္ပါတယ္။

Sql statement အလုပ္လုပ္ဖို ့background process , sga structures and database files
အခ်ိဳ ့ကိုသံုးပါတယ္။ Sql statement အမ်ိဳးအစားေပၚ မူတည္ျပီး အမ်ိဳးမ်ိဳးေသာ components
ကိုသံုးပါတယ္။
Query က user ကို Rows ေတြ return ျပန္တယ္။ DML statement ေတြ က data changes ေတြကို
log ပါမွတ္ေပးတယ္။ commit ကေတာ့ transaction ကို recover ျပန္လုပ္ဖို ့အတြက္ပါ modified data
ေတြပါမွတ္ေပးတယ္။ အခ်ိဳ ့ေသာ background process ေတြက sql statement ေတြ
အလုပ္လုပ္ေနတဲ့အခ်ိန္မွာ တိုက္ရုိက္ participate မလုပ္ဘူး ။သို ့ေပမယ့္ database recovery လုပ္ဖို ့

Thawzh818@gmail.com Page 204


Treasure Island Training Service Ph:09691011157

performance improve လုပ္ဖို ့အတြက္ေတာ့သံုးတယ္။ ဥပမာ Archiver background process , ARCn


ပဲျဖစ္ပါတယ္။ သူ က database ကို recovered လုပ္နိုင္ပါတယ္။

22.11 Processing a Query

 Parse:
– Search for an identical statement.
– Check the syntax, object names, and privileges
– Lock the objects used during parse.
– Create and store the execution plan
 Execute: Identify the rows selected.
 Fetch: Return the rows to the user process.

Query တစ္ခု မွာ အဆင့္ေတြရွိပါတယ္။ ပထမ အဆင့္ က parse ပါ ။ parse အဆင့္မွာ sql script က
ေရးျပီးလို ့run button ကို နွပ
ိ ျ္ ပီးပါျပီ။ user process မွ server process ကို ေရာက္သြားပါတယ္။ အဲဒီ
အခ်ိန္မွာ ေရးထားတဲ့ Script က အရင္ run ဘူးလား ဆိုတာကို စစ္ပါတယ္။ အရင္ run ဘူးတယ္ဆုိရင္
shared pool ထဲမွာ ရွိေနပါတယ္။ syntax ကိုစစ္ မွန္တယ္ဆိုရင္ execute အဆင့္ကို ေရာက္သြားပါတယ္။
အဲဒီ ေနာက္ မွာ user ကို data ေတြ return ျပန္လိုက္ပါတယ္။ အဲဒါကို fetch လုပ္တယ္လို ့ေျပာပါတယ္။

22.12 Shared Pool

 The library cache contains the SQL statement text, parsed code, and execution plan.
 The data dictionary cache contains table, column, and other object definition and
privileges.
 The shared pool is sized by SHARED_POOL_SIZE.

Thawzh818@gmail.com Page 205


Treasure Island Training Service Ph:09691011157

Sql statement run ေနတဲ ့အခိ်န္ parse state မွာ ဆိုရင္ shard pool ေပၚမွာ အလုပ္လုပ္ပါတယ္။ shared
pool မွာ components နွစခ
္ ရ
ု ပ
ိွ ါတယ္။ library cache and Data Dictionary cache ပါ။ library cache ထဲမွာ
အရင္က run ခဲ့ဘူးတဲ ့sql statement ေတြရွိပါတယ္။ Data Dictionary cache မွာ database ထဲ က
မၾကာခန သံုးခဲ့ဘူးတဲ့ database definition ေတြရွိတယ္။ shared pool size ကို SHARED_POOL_SIZE ကို
initialization parameter နဲ ့သတ္မွတ္လို ့ရပါတယ္။

22.13 Database Buffer Cache

 The database buffer cache stores the most recently used blocks.
 The size of a buffer is based on DB_BLOCK_SIZE.
 The number of buffers is defined by DB_BLOCK_BUFFERS.

Query တစ္ခု process လုပ္ေနတဲ့အခိ်န္မွာ အဲဒီ query က အရင္ run ခဲ့ဘူးတဲ့ query ဆိုရင္ data ေတြက
database buffer cache ထဲမွာရွိေနမွာပါ။ တကယ္လို ့buffer ထဲမယ္ရွိမေနဘူးဆိုရင္ ေတာ့ hard disk
ေပၚက data file ထဲက သြားဖတ္ျပီး return ျပန္မွာပါ။ Database buffer cache ကို DB_BLOCL_BUFFERS
parameter နဲ ့set လုပ္ေပးလို ့ရပါတယ္။ buffer cache ထဲမွာ ရွိေနတဲ့ buffer တစ္ခု စီ ရဲ ့size က Oracle
block နဲ တူပါတယ္။ DB_BLOCK_SIZE parameter နဲ ့တူပါတယ္။

22.14 Program Global Area (PGA)

 Is not shared
 Is writable only by the server process
 Contains
– Sort area
– Session information
– Cursor state
– Stack space

Thawzh818@gmail.com Page 206


Treasure Island Training Service Ph:09691011157

PGA မွာ server process အတြက္ data and control information ေတြပါတဲ့ memory area
တစ္ခုပျဲ ဖစ္ပါတယ္။ အဲဒီ memory က oracle က created လုပ္ထားတဲ့ shared memory မဟုတ္ဘူး ။
Dedicated server configuration တစ္ခုမွာ PGA မွာ sort area, session information, cursor state and
stack space ေတြပါှင္ပါတယ္။
Sort area ကို sql statement sorting လုပ္တဲ့အခါမွာသံုးပါတယ္။ session information မွာ user privileges
and performance statistics ေတြပါတယ္။
Cursor state က လက္ရ႕ွိ ရွိေနတဲ ့ user session မွာသံုးေနတဲ့ sql statement ရဲ ့ state ကိုေျပာတာပါ။
Stack space က အျခား session variables ေတြပါပါတယ္။
Process ေတြ CREATED လုပ္တဲ့အခါ ျပန္ျပီး ေနရာ ခ်တဲ့ အခါမွာ နဲ ့ အဲဒီ PROCESS ကို ျပန္ျပီး
TERMINATED လုပ္တဲ့အခါမွာ PGA က စ ျပီး အလုပ္လုပ္ပါတယ္။

22.15 Processing a DML Statement

DML language process လုပ္မယ္ဆိုရင္ State နွစခ


္ ု ရွိပါတယ္။ parse and execute ပါ ။
Parse state ကေတာ့ query လုပ္တဲ့ process နဲ့ တူတူပါပဲ။execute မွာေတာ့ data changes လုပ္ဖို ့
additional processing ေတြလုိပါတယ္။

Thawzh818@gmail.com Page 207


Treasure Island Training Service Ph:09691011157

DML statement Execute လုပ္ဖို ့buffer cache ထဲမွာ data and rollback blocks ေတြက အဆင္သင့္
ရွမ
ိ ေနပါဘူး။ server process က Data files ထဲက data ကို ဖတ္တယ္။ ျပိး ရင္ buffer cache ထဲကို
ပို ့ေပးတယ္။ server process က modified လုပ္လိုက္တဲ့ rows ေတြကို lock လုပ္ထားတယ္။ အဲဒီ မွာ undo
block က rollback အတြက္ old data ကို store လုပ္တယ္။ server process က undo block ထဲက အရင္
Data ကို သိမ္းတယ္။ ေနာက္ new data ကို data file မွာ update လုပ္တယ္။ delete or insert process
ကလည္း ဒီ လုိပဲ လုပ္တယ္။ သို ့ေပမယ့္ delete process မွာ ဆိုရင္ deleted rows ထဲက column values
ေတြကို old data အေနနဲ ့undo block မွာသိမ္းတယ္။ insert အတြက္ row location information ေတြကို
သိမ္းတယ္။

22.16 Redo Log Buffer

 Has its size defined by LOG_BUFFER


 Records changes made through the instance
 Is used sequentially
 Is a circular buffe

Server process ေတြ သည္ redo log buffer ထဲမွာ ရွိေနတဲ့ Data file block ေတြ changes လုပ္တာေတြကို
record လုပ္ေပးတယ္။ redo log buffer သည္ SGA ရဲ ့အစိတ္အပိုင္း တစ္ခုပျဲ ဖစ္ပါတယ္။ redo log buffer
size ကို LOG_BUFFER parameter နဲ့ size ကို defined လုပ္ပါတယ္။ changed လုိက္တဲ့ block ေတြကို
record လုပ္ေပးတယ္။

22.17 Rollback Segment

Change တစ္ခု မလုပ္ခင္ server process က old data ကို rollback segment ထဲမွာ save တယ္။

Thawzh818@gmail.com Page 208


Treasure Island Training Service Ph:09691011157

Transaction ကို rollback ျပန္ေခၚမယ္ဆိုလ်င္ အဲဒီ old data ကို undo ျပန္ေခၚတယ္။ အဲဒီမွာ ေျပာခ်င္တာ
က DML statement ကို commit မလုပ္ခင္ အျခား transaction ေတြက မေတြ ့ရပါဘူး ။ အဲဒါ ကို read
consistence ျဖစ္တယ္လို ့ေခၚပါတယ္။ failure ျဖစ္ေနရင္ေတာ့ consistent state ရေအာင္ database ကို
recover လုပ္ေပးရပါတယ္။
Table and indexes ကဲ့သို ့rollback segments ေတြက data file ထဲမွာရွိပါတယ္။ rollback blocks ကို
လိုအပ္ရင္ database buffer cache ထဲကို ဆြထ
ဲ ည့္ပါတယ္။ rollback segment ကို DBA က create
လုပ္ပါတယ္။ rollback segment ရဲ ့ changes ေတြကို redo log buffer ထဲမွာ သိမ္းပါတယ္။

22.18 COMMIT Processing

Oracle server က instance failure ျဖစ္တဲ့အခ်ိန္မွာ committed changes ေတြကို recover


လုပ္နို္င္ေလာက္ေအာင္ fast commit mechanism ကို သံုးတယ္။

22.18.1 System Change Number


Transaction တစ္ခုကို commit လုပ္လိုက္တဲ့အခါတိုင္း Oracle server က commit SCN တစ္ခုကို assigns
လုပ္တယ္။ SCN က monotonically incremented ျဖစ္တယ္။ ျပီးေတာ့ unique ျဖစ္တယ္။ အဲဒီ SCN ကို

Thawzh818@gmail.com Page 209


Treasure Island Training Service Ph:09691011157

oracle server က internatl time stamp အျဖစ္သံုးတယ္။ အဲဒီ time stamp က data file ကေန data
ေတြကို ဆြထ
ဲ ုတ္တဲ့အခါမွာ read consistency ျဖစ္ေအာင္လုပ္ေပးတယ္။ ေနာက္ data ေတြကို synchronize
ျဖစ္ေအာင္လုပ္ေပးတယ္။ SCN ကို သံုးျခင္းအားျဖင့္ oracle server ကို opearating system ရဲ ့ data and
time ကို မမွခ
ီ ဘ
ုိ ဲ consistency checks ကို လုပ္ေဆာင္ေပးတယ္။

22.18.2 Steps in Processing COMMITS


COMMIT လုပ္လိုက္တဲ့ အခါမွာ ေအာက္ပါ STEP ေတြကို လုပ္ေဆာင္ေပးတယ္။
1. Server process က commit record တစ္ခု ကို လုပ္လိုက္တဲ့အခါ မွာ အဲဒီ record ကို SCN နဲ ့အတူ
redo log buffer ထဲမွာသြားသိမ္းပါတယ္။
2. LGWR က redo log buffer ထဲက ရွိေနတဲ့ entries အားလံုးကို commit record ပါ အပါကို redo
log files ထဲမွာသြားသိမ္းပါတယ္။ အဲဒိ အခ်က္ကို ၾကည့္ျခင္းအားျဖင့္ oracle က မည္သည့္ changes
ကို မဆို guarantee ေပးနိုင္ပါတယ္။ ဘယ္ေတာ့မွ lost မျဖစ္ပါဘူး။ instance failure ျဖစ္ရင္ေတာင္
မွ မည္သည့္ changes မွ lost မျဖစ္ပါဘူး။
3. Commit လုပ္ျပီးရင္လည္း user ကို inform ေပးပါတယ္။
4. Server process က transaction complete ျဖစ္တာကို ေျပာတဲ့ information ေတြကိုလည္း record
လုပ္တယ္။ resource locks ေတြကို ထုတ္ေပးနုိင္တဲ့ information ေတြကို လည္း record
လုပ္ထားပါတယ္။

22.18.3 Advantages of the Fast COMMIT


Fast commit mechanism က data file အစား redo log file မွာ changes ေတြကို သြားေရးတာက data
recovery လုပ္တဲ့အခါ ပိုေသခ်ာေစပါတယ္။
 Log file မွာ data changes ေတြသြားေရးတာက data file မွာ different blocks ေတြကို
သြားေရးတာထက္ ပိုျမန္ေစပါတယ္။
 Log file မွာ ေရးတာက changes လုပ္လိုက္တဲ့ record ေလးရဲ ့information ကိုပဲသိမ္းတာပါ။ data
file မွာေတာ့ data ေတြရဲ ့ block တစ္ခုလံုးကို ေရးရတာပါ။ အဲဒါေၾကာင့္ပိုၾကာတာပါ။
 Multiple transaction ေတြကို တခ်ိန္တည္း မွာ commit လုပ္လိုက္တဲ့အခါ instance piggybacks
redo log က တၾကိမ္တည္းပဲ မွတ္ေပးတယ္။
 Redo log buffer မျပည့္ေသးဘူးဆိုရင္ transaction တစ္ခု ကို synchronous write
တစ္ခုပလ
ဲ ိုတယ္။ တကယ္လို ့ piggybacking ျဖစ္ျပီဆိုရင္ေတာ့ transaction တစ္ခုအတြက္
synchronous write တစ္ခုထက္ပိုျပီးေလ်ာ့က်သြားပါတယ္။
 Commit မလုပ္ခင္ redo log buffer ျပည့္သြားနိုင္တာေၾကာင့္ transaction ရဲ ့ size က commit
operation အတြက္ လိုအပ္တဲ့ အခ်ိန္ကိုေတာ့ affect မျဖစ္ပါဘူ။

Thawzh818@gmail.com Page 210


Treasure Island Training Service Ph:09691011157

22.19 Summary of the Oracle Database Architecture

Oracle database က instance and its associated database နဲ ့ဖြဲ ့စည္းထားတယ္။


 instance က SGA and background processes ေတြ နဲ ့ဖြဲ ့စည္းထားတယ္။
- SGA: Database buffer cache, redo log buffer, shared pool and so on
- Background processes: SMON, PMON, DBWn, CKPT, LGWR and so on
 Database က storage structures နဲ ့ဖြဲ ့စည္းထားတယ္။
- Logical: Tablespaces, schemas, segments, extents, and Oracle block
- Physical: Data files, control files, redo log files

Thawzh818@gmail.com Page 211

You might also like