Oracle Basic and Advanced SQL
Oracle Basic and Advanced SQL
An application developer, for example, may have the following system privileges:
– CREATE SESSION
– CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE
Thawzh818@gmail.com Page 1
Treasure Island Training Service Ph:09691011157
Create a role:
The DBA creates your user account and initializes your password.
You can change your password by using the ALTER USER statement.
Thawzh818@gmail.com Page 2
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 3
Treasure Island Training Service Ph:09691011157
Allow all users on the system to query data from DEPARTMENTS table:
GRANT select
ON departments
TO PUBLIC;
1.10 Confirming Granted 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 the SELECT and INSERT privileges given to the demo user on the
DEPARTMENTS table.
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.
Thawzh818@gmail.com Page 6
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 7
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 8
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 9
Treasure Island Training Service Ph:09691011157
2.6 Relationships
Thawzh818@gmail.com Page 10
Treasure Island Training Service Ph:09691011157
• A foreign key must reference either a primary key or a unique key column.
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.
Thawzh818@gmail.com Page 12
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 13
Treasure Island Training Service Ph:09691011157
SELECT *
FROM table_name;
Thawzh818@gmail.com Page 14
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 15
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 16
Treasure Island Training Service Ph:09691011157
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
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
A concatenation operator:
• Links columns or character strings to other columns
Thawzh818@gmail.com Page 19
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 20
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 21
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 22
Treasure Island Training Service Ph:09691011157
DESCRIBE employees;
Desc employees;
Thawzh818@gmail.com Page 23
Treasure Island Training Service Ph:09691011157
True/Flase
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
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
Thawzh818@gmail.com Page 26
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 27
Treasure Island Training Service Ph:09691011157
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;
Thawzh818@gmail.com Page 28
Treasure Island Training Service Ph:09691011157
6 SELECT last_name
FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith';
• 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 '\';
Thawzh818@gmail.com Page 30
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 31
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 32
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 33
Treasure Island Training Service Ph:09691011157
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:
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:
Thawzh818@gmail.com Page 34
Treasure Island Training Service Ph:09691011157
The following query uses the row limiting clause with the WITH TIES option:
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.
The following query returns top 5% products with the highest inventory level:
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;
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 ;
UNDEFINE employee_num
1 SET VERIFY ON
SELECT employee_id, last_name, salary
FROM hr.employees
WHERE employee_id = &employee_num;
Thawzh818@gmail.com Page 37
Treasure Island Training Service Ph:09691011157
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
Thawzh818@gmail.com Page 40
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 41
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 42
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 43
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 44
Treasure Island Training Service Ph:09691011157
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';
• 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
Thawzh818@gmail.com Page 46
Treasure Island Training Service Ph:09691011157
SELECT sysdate
FROM dual;
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';
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.
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;
Thawzh818@gmail.com Page 51
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 52
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 53
Treasure Island Training Service Ph:09691011157
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
Thawzh818@gmail.com Page 55
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 56
Treasure Island Training Service Ph:09691011157
FROM employees
WHERE department_id = 80;
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
Thawzh818@gmail.com Page 59
Treasure Island Training Service Ph:09691011157
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;
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;
Thawzh818@gmail.com Page 62
Treasure Island Training Service Ph:09691011157
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
3. The WHERE clause restricts rows before inclusion in a group calculation. True/False
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
Natural join
Equijoin
Nonequijoin
Outer join
Self-join
Cross join
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.5 Equijoins
7.7 Additional Search Conditions Using the AND and WHERE Operators
Thawzh818@gmail.com Page 67
Treasure Island Training Service Ph:09691011157
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:
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.
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:
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:
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
A CROSS JOIN is a JOIN operation that produces the Cartesian product of two
tables.
Example:
Thawzh818@gmail.com Page 70
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 71
Treasure Island Training Service Ph:09691011157
Thawzh818@gmail.com Page 72
Treasure Island Training Service Ph:09691011157
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.
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
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.
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.
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
( 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
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.
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.
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);
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;
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.
Example 1 Find all employees who earn more than the average salary in their
department.
Thawzh818@gmail.com Page 81
Treasure Island Training Service Ph:09691011157
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
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);
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);
Thawzh818@gmail.com Page 83
Treasure Island Training Service Ph:09691011157
Is ANSI-compatible
UNION ALL
SELECT incoming.Source,
outgoing.Destin,incoming.TotalFlightTime+outgoing.Flight_time
FROM Reachable_
From incoming, Flights outgoing
WHERE incoming.Destin = outgoing.Source
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
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
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;
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.
See the following employees and contacts tables in the sample database.
Thawzh818@gmail.com Page 89
Treasure Island Training Service Ph:09691011157
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:
To sort the result set returned by the UNION operator, you add an ORDER BY clause to
the last SELECT statement as shown below:
Thawzh818@gmail.com Page 90
Treasure Island Training Service Ph:09691011157
In this example, we sorted the list by name concatenated from the first and last names.
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;
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
The Oracle INTERSECT operator compares the result of two queries and returns the
distinct rows that are output by both queries.
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.
Suppose we have two queries that return the T1 and T2 result set.
Thawzh818@gmail.com Page 92
Treasure Island Training Service Ph:09691011157
The intersect of T1 and T2 result returns 2 and 3. Because these are distinct values that
are output by both queries.
The illustration showed that the INTERSECT returns the intersection of two circles (or
sets).
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.
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.
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:
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
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:
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
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;
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 NCHAR[(size)]
112 CLOB
112 NCLOB
113 BLOB
114 BFILE
Thawzh818@gmail.com Page 99
Treasure Island Training Service Ph:09691011157
1. NUMBER
2. NUMBER(p,s)
3. NUMBER(p)
4. NUMBER(p,0)
5. NUMBER(5,-2)
VALUES( 1 / 3, 1 / 3, 1/3 );
3 SELECT *
FROM float_demo;
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.
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) );
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);
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) ,
department_id integer);
alter table emp_thaw5 add primary key(id);
commit;
UPDATE employees
SET salary = 17500
WHERE employee_id = 102;
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
COMMIT;
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';
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;
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.
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.
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,
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.
9. Make the data additions permanent. Update and delete data in the MY_EMPLOYEE
table.
11. Change the salary to $1,000 for all employees who have a salary less than $900.
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.
21. Discard the most recent DELETE operation without discarding the earlier INSERT
operation.
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.
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-
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
(&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;
V$ Performance-related data
Start with DICTIONARY. It contains the names and descriptions of the dictionary
tables and views.
DESCRIBE DICTIONARY;
SELECT *
From dictionary
WHERE table_name = 'USER_OBJECTS';
ALL_OBJECTS:
Query ALL_OBJECTS to see all the objects to which you have access.
USER_TABLES:
DESCRIBE user_tables;
SELECT table_name
FROM user_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‟;
DESCRIBE user_cons_columns;
SELECT constraint_name, column_name
FROM user_cons_columns
WHERE table_name = 'EMPLOYEES';
ALL_COL_COMMENTS
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
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
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.
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.
– A rollback occurs
– The system crashes
– A sequence is used in another table
Change the increment value, maximum value, minimum value, cycle option, or cache
option:
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:
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
Is useful for hiding the identity and location of an underlying schema 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
DESCRIBE user_synonyms;
SELECT *
FROM user_synonyms;
12.17 Indexes
An index:
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
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
DESCRIBE user_ind_columns;
Remove an index from the data dictionary by using the DROP INDEX command:
DROP INDEX index ;
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
Create the EMPVU80 view, which contains details of the employees in department 80:
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;
Modify the EMPVU80 view by using a CREATE OR REPLACE VIEW clause. Add an
alias for each column name:
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:
A GROUP BY clause
The DISTINCT keyword
The pseudocolumn ROWNUM keyword
Expressions
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
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 ;
Quiz
You cannot add data through a view if the view includes a GROUP BY clause.
a. True
b. False
Answer: a
14.2 Adding a Constraint Syntax Use the ALTER TABLE statement to:
Add a FOREIGN KEY constraint to the EMP2 table indicating that a manager must
already exist as a valid employee in the EMP2 table.
You can specify the ONLINE keyword to indicate that DML operations on the table are
allowed while dropping the constraint.
Use the ON DELETE CASCADE clause to delete child rows when a parent key is
deleted:
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;
– 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
Use the RENAME TABLE clause of the ALTER TABLE statement to rename tables.
Use the RENAME COLUMN clause of the ALTER TABLE statement to rename
table columns.
Use the RENAME CONSTRAINT clause of the ALTER TABLE statement to rename
any existing constraint for a table.
Apply the CASCADE option to disable the primary key and it will disable all
dependent FOREIGN KEY constraints automatically as well.
INITIALLY DEFERRED Waits until the transaction ends to check the constraint
INITIALLY Checks the constraints at the end of the statement execution
IMMEDIATE
Example 1
insert into emp_new_sal values (90,5);
Example 2.
insert into emp_new_sal values (110,-1);
Example 3.
SET CONSTRAINTS ALL DEFERRED;
Example 4.
SET CONSTRAINT ALL IMMEDIATE;
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.
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.
Create a DIRECTORY object that corresponds to the directory on the file system where
the external data source resides.
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
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
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
Use a correlated subquery to update rows in one table based on rows from another
table.
UPDATE empl6 e
SET department_name =(SELECT department_name
FROM departments d
WHERE e.department_id=d.department_id);
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);
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
UPDATE deptm3
SET manager_id = DEFAULT
WHERE department_id = 10;
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
Unconditional INSERT
Conditional INSERT ALL
CONDITIONAL INSERT FIRST
Pivoting 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;
INSERT ALL
WHEN HIREDATE < '01-JAN-05' THEN
INTO emp_history VALUES(EMPID,HIREDATE,SAL)
WHEN COMM IS NOT NULL THEN
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)
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
You can conditionally insert, update, or delete rows in a table by using the MERGE
statement.
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.
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
SELECT salary
FROM employees3
WHERE last_name = 'Chung';
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';
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;
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
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
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‟;
The TIME_ZONE parameter is set to –5:00 and then SELECT statements for each date
and time are executed to compare differences.
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:
MONTH
INTERVAL DAY TO Days, Hour, Minute, Second with fractional seconds
SECOND
17.14 EXTRACT
Display the MONTH component from the HIRE_DATE for those employees whose
MANAGER_ID is 100.
17.15 TZ_OFFSET
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
17.17 TO_TIMESTAMP
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.
17.19 TO_DSINTERVAL
Display a date that is 100 days and 10 hours after the hire date for all the employees.
Quiz
Answer: b, c, d
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.
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
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.
This query results in the Oracle server computing the following groupings:
(job_id, manager_id)
(department_id, job_id, manager_id)
(department_id)
Grand total
The example in the slide can also be written as:
Column2=Child key
Create a report displaying company management levels, beginning with the highest level and
indenting each of the following levels.
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
SELECT 'CREATE TABLE ' || table_name || '_test ' || 'AS SELECT * FROM ' || table name || '
WHERE 1=2 ' AS "Create Table Script" FROM user_tables;
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
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.
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
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
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
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)
match_parameter:
subexpr: Fragment of pattern enclosed in parentheses. You learn more about subexpressions
later in this appendix.
21.11 Subexpressions
Select regexp_instr(„0123456789‟,
„(123)(4(56)(78))‟,
1,
1,
0,
„I‟,
1) “position”
From dual;
0,
'i',
1) "Position"
FROM dual;
SELECT REGEXP_COUNT(
'ccacctttccctccactcctcacgttctcacctgtaaagcgtccctccctcatccccatgcccccttaccctgcagggta
gagtaggctagaaaccagagagctccaagctccatctgtggagaggtgccatccttgggctgcagagagaggag
aatttgccccaaagctgcctgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttcttgagtt
ttcaccctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagaggctcttgggtc
tgatggccacatcctggaattgttttcaagttgatggtcacagccctgaggcatgtaggggcgtggggatgcgctctg
ctctgctctcctctcctgaacccctgaaccctctggctaccccagagcacttagagccag', 'gtc') AS Count
FROM dual;
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
Database ဆိုတာ data ေတြကို စုထားတ့ဲ့ အစုအေှး တစ္ခု a collection of data တစ္ခုပျဲ ဖစ္ပါတယ္။
Oracle database က multiuser ေတြကို တခိ်န္ထဲမွာ same data and a large amount of data ေတြကို
ယံုၾကည္စိတ္ခ်စြာ access လုပ္ခင
ြ ့္ေပးနိုင္တယ္။ ျပီး high performance (လ်င္ျမန္မွန္ကန္) လည္းေပး
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
က စ အလုပ္လုပ္တယ္။
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 မွာ ရွာဖတ္ၾကည့္ပါေနာ္။
Database မွာ ရွိတဲ့ information ေတြရယူဖို ့ဆိုရင္ user က database နဲ ့connection ရွဖ
ိ ို့လိုတယ္။
SQL*Plus ကေတာ့ oracle server ေတြအတြက္ connection ယူဖို ့တစ္ခုတည္းေသာ Tool ပါ။ username
session လို ့ေခၚပါတယ္။ log out မျဖစ္မခ်င္း session ရွိေနတယ္လို ့ေျပာျပီး log out ျဖစ္သြားရင္ေတာ့
session မရွိေတာ့ဘူးလို ့ေျပာပါတယ္။
လုပ္ေပးျပီး အလုပ္လုပ္ေပးတယ္။ 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 ေတြ
အလုပ္လုပ္ေနတယ္။
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 လုပ္တာနဲ ့တူတူပါပဲ။
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
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 အျဖစ္
အလုပ္လုပ္ လိုက္ေတာ့ 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 အလုိအေလ်ာက္ ထုတ္ေပးတယ္။
DBWn
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 လုပ္တယ္။
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
Control file
CKPT
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
ကလုပ္ေပးပါတယ္။
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
လုပ္တယ္။
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 က ဖတ္ဖို ့ပါ။
Alert log files: trace entries ေတြ ရွိတယ္။ Database ရဲ ့ alert log ကေတာ့ messages and
errors ေတြပဲျဖစ္ပါတယ္။ instance တစ္ခုစီမွာ alert log file တစ္ခုစီရွိပါတယ္။ oracle က အဲဒီ alert
log file ကို ၾကည့္ဖို ့recommand ေပးထားပါတယ္။
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 လည္းထားပါတယ္။
တယ္။ 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
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 လုပ္ဖို ့
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 လုပ္တယ္လို ့ေျပာပါတယ္။
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.
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 နဲ ့သတ္မွတ္လို ့ရပါတယ္။
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 နဲ ့တူပါတယ္။
Is not shared
Is writable only by the server process
Contains
– Sort area
– Session information
– Cursor state
– Stack space
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 က စ ျပီး အလုပ္လုပ္ပါတယ္။
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 ေတြကို
သိမ္းတယ္။
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 လုပ္ေပးတယ္။
Change တစ္ခု မလုပ္ခင္ server process က old data ကို rollback segment ထဲမွာ save တယ္။
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 ထဲမွာ သိမ္းပါတယ္။
oracle server က internatl time stamp အျဖစ္သံုးတယ္။ အဲဒီ time stamp က data file ကေန data
ေတြကို ဆြထ
ဲ ုတ္တဲ့အခါမွာ read consistency ျဖစ္ေအာင္လုပ္ေပးတယ္။ ေနာက္ data ေတြကို synchronize
ျဖစ္ေအာင္လုပ္ေပးတယ္။ SCN ကို သံုးျခင္းအားျဖင့္ oracle server ကို opearating system ရဲ ့ data and
time ကို မမွခ
ီ ဘ
ုိ ဲ consistency checks ကို လုပ္ေဆာင္ေပးတယ္။