oracle notes

268
Capabilities of SELECT statement The 3 main tasks of a SELECT command is: 1. Selection: restricting the no of rows to be displayed in the result. 2. Projection: restricting the no of columns to be shown in the result. 3. Joins: combining the columns of multiple tables and showing them as a single result. Syntax of the SELECT command: SELECT <column list> | * FROM <tablename>; Rules and regulations to be followed to enter an SQL command: 1. SQL is not case-sensitive. 2. As per the standards, the keywords must be typed in uppercase and other information in lowercase. 3. Each clause must be entered on separate lines. An SQL statement is made up of many clauses. A clause is a keyword followed by the required information. SELECT employeeid FROM employees; 1. Proper alignment should be maintained for better readability. Outer query = ( Inner Query ) 1. Each SQL statement must end with a ; Arithmetic Operator is used perform mathematical calculations Add + Subtract - Divide /

Upload: peter-lwanda

Post on 06-Dec-2015

16 views

Category:

Documents


0 download

DESCRIPTION

Notes i collected during training

TRANSCRIPT

Page 1: Oracle Notes

Capabilities of SELECT statement

The 3 main tasks of a SELECT command is:1. Selection: restricting the no of rows to be displayed in the result.2. Projection: restricting the no of columns to be shown in the result.3. Joins: combining the columns of multiple tables and showing them as a single result.

Syntax of the SELECT command:SELECT <column list> | *FROM <tablename>;Rules and regulations to be followed to enter an SQL command:

1. SQL is not case-sensitive.2. As per the standards, the keywords must be typed in uppercase and other information in

lowercase.3. Each clause must be entered on separate lines.

An SQL statement is made up of many clauses.A clause is a keyword followed by the required information.SELECT employeeid FROM employees;

4. Proper alignment should be maintained for better readability.Outer query = (Inner Query)

5. Each SQL statement must end with a ;

Arithmetic Operator

is used perform mathematical calculationsAdd +Subtract -Divide /Multiply *

You can use an arithmetic expression in the SELECT clause.Write a query to show employee id, last name, salary and a revisedsalary of 100$ raise for all employees.SELECT employee_id,last_name,salary,salary+100FROM employees;

To rename the column heading, use an AliasAn Alias is a short name given to a column or to a table.

Page 2: Oracle Notes

SQL> SELECT employee_id AS "Employee Code", last_name AS "Employee Name", 2 salary AS "Basic Salary", salary+100 AS "Revised Salary" 3 FROM employees;

An alias name should be enclosed within double quotes if:1. it holds a space2. you want to use the same case how it was typed in the script

NOTE: in an arithmetic expression having all the 4 operations, the division and multiplication have more precedence than addition and subtraction. To override the order of precedence, enclose the expression within parentheses ().

Example:Write a query to display employee id, last name, salary, revised salary of 100$ raise and the annual revised salary of all employees.

SELECT employee_id, last_name, salary, salary+100 AS Revised,(salary+100)*12 AS AnnualSalaryFROM employees;

Working with NULL values:NULL is means no value. It cannot be compared with zero or empty string.

Note: In an arithmetic expression having null value, the result of the expression will also be null.

10+20*null = nullOracle has a default table called as dual

For Example:

NOTE: oracle commands can be abbreviated.Example: conn for connect, desc for describe comamnd

Write a query to display employee id, last name, salary, commission, and net salary of employeesSELECT employee_id, last_name, salary, salary+100 AS Revised,(salary+100)*12 AS AnnualSalaryFROM employees;

Page 3: Oracle Notes

SQL> SELECT employee_id, last_name, salary, commission_pct, salary+(salary*commission_pct) AS netsalary 2 FROM employees;

CONCATENATION OPERATOR:Combining the result of two or more columns and displaying them as a single column. This operator is introduced by ||

NOTE: A character and date value should be enclosed within single quote.SQL> SELECT first_name || ' ' || last_name AS "Full Name" 2 FROM employees;

SQL> SELECT 'The Employee ' || first_name || ' ' || last_name || ' who works in ' || department_id || ' was hired on ' || hire_date AS message FROM employees;

Quote Operator (Q Operator) is used to override the special meaning of single quotes.Syntax:q'[john's]''John's salary is'SQL> SELECT last_name || q'['s salary is]' || salary AS message 2 FROM employees;

To remove duplicate value from a column:

SQL> SELECT DISTINCT job_id 2 FROM employees;DISTINCT keyword is used to remove duplicate values and show only unique ones.

Comparison / Relational OperatorThey are used in comparisons and the result of the comparison will be either TRUE or FALSE.< Less than> Greater than<= Less than or equal to>= Greater than or equal to= Equal to<> or! = or ^=

SELECT <column list> | *FROM <table>[WHERE <condition>]

Page 4: Oracle Notes

The WHERE is an optional clause that is used to limit the no of rows to be shown.

Example:1. Write a query to show employees whose salary is greater than 14000$

SQL> SELECT employee_id, last_name, salary 2 FROM employees 3 WHERE salary>14000;

2. Write a query to show employees who are not IT Programmers.SQL> SELECT employee_id, last_name, job_id, salary 2 FROM employees 3 WHERE job_id ^= 'IT_PROG';

NOTE: The Character value is case-sensitiveSQL> SELECT last_name, salary, first_name 2 FROM employees 3 WHERE first_name = 'john'; no rows selected SQL> SELECT last_name, salary, first_name 2 FROM employees 3 WHERE first_name = 'John'; LAST_NAME SALARY FIRST_NAME ------------------------- ---------- -------------------- Chen 8200 John Seo 2700 John Russell 14000 John

Note: The date value is Format SensitiveThe Oracle default date format is DD-MON-YYSQL> SELECT employee_id, last_name, salary 2 FROM employees 3 WHERE hire_date='17-MAR-07'; EMPLOYEE_ID LAST_NAME SALARY ----------- ------------------------- ---------- 195 Jones 2800 SQL> SELECT employee_id, last_name, salary 2 FROM employees 3 WHERE hire_date='2007/03/17'; WHERE hire_date='2007/03/17' * ERROR at line 3:

Page 5: Oracle Notes

ORA-01861: literal does not match format string

LOGICAL OperatorsThey are used to join two conditions together:Types:

1. AND2. OR3. NOT

For Examples:Write a query to show employees whose salary is greater than 8000 and who were hired before 2007.

SQL> SELECT employee_id, last_name, hire_date, salary 2 FROM employees 3 WHERE hire_date<'1-JAN-07' AND salary > 8000;

Write a query to display employees belonging to department 10, 20, and 50.SQL> SELECT employee_id, last_name, department_id, salary 2 FROM employees 3 WHERE department_id=10 OR department_id=20 OR department_id=50;

Display employees whose salary is between 1500 and 3000SQL> SELECT employee_id, last_name, department_id, salary 2 FROM employees 3 WHERE salary >= 1500 AND salary <= 3000;NOT: used to negate the expression

Other comparison operators:IN: to provide alternate values. It is an alternate to Logical ORSQL> SELECT employee_id, last_name, department_id, salary FROM employees WHERE department_id IN(10,20,50);

SQL> SELECT employee_id, last_name, department_id, salary FROM employees WHERE department_id NOT IN(10,20,50);

BETWEEN: is used to provide a range. It can be a replacement of Logical AND.SQL> SELECT employee_id, last_name, department_id, salary

Page 6: Oracle Notes

FROM employees WHERE salary BETWEEN 1500 AND 3000;

SQL> SELECT employee_id, last_name, department_id, salary FROM employees WHERE salary NOT BETWEEN 1500 AND 3000;

LIKE: used to provide a pattern matching. Oracle provides 2 wildcard characters for pattern matching% is used to ignore any no of characters_ is used to ignore 1 character.

For ExamplesDisplay employees whose first start begin with 'A'

SQL> SELECT employee_id, last_name, department_id, salary FROM employees WHERE salary BETWEEN 1500 AND 3000; EMPLOYEE_ID LAST_NAME DEPARTMENT_ID SALARY ----------- ------------------------- ------------- ----------

198 OConnell 50 2600 199 Grant 50 2600 116 Baida 30 2900 117 Tobias 30 2800 118 Himuro 30 2600 119 Colmenares 30 2500 126 Mikkilineni 50 2700 127 Landry 50 2400 128 Markle 50 2200 130 Atkinson 50 2800 131 Marlow 50 2500

EMPLOYEE_ID LAST_NAME DEPARTMENT_ID SALARY ----------- ------------------------- ------------- ----------

132 Olson 50 2100 134 Rogers 50 2900 135 Gee 50 2400 136 Philtanker 50 2200 139 Seo 50 2700 140 Patel 50 2500 143 Matos 50 2600 144 Vargas 50 2500

Page 7: Oracle Notes

182 Sullivan 50 2500 183 Geoni 50 2800 187 Cabrio 50 3000

EMPLOYEE_ID LAST_NAME DEPARTMENT_ID SALARY ----------- ------------------------- ------------- ---------- 190 Gates 50 2900 191 Perkins 50 2500 195 Jones 50 2800 197 Feeney 50 3000 26 rows selected. SQL> SQL> SQL> SELECT employee_id, first_name, salary 2 FROM employees 3 WHERE first_name LIKE 'A%'; SQL> SELECT employee_id, first_name, salary 2 FROM employees 3 WHERE first_name NOT LIKE 'A%';

EMPLOYEE_ID FIRST_NAME SALARY ----------- -------------------- ---------- 103 Alexander 9000 115 Alexander 3100 121 Adam 8200 147 Alberto 12000 158 Allan 9000 167 Amit 6200 175 Alyssa 8800 185 Alexis 4100 187 Anthony 3000 196 Alana 3100 10 rows selected. SQL> SELECT employee_id, first_name, salary 2 FROM employees 3 WHERE first_name LIKE '%a'; EMPLOYEE_ID FIRST_NAME SALARY ----------- -------------------- ---------- 101 Neena 17000 107 Diana 4200 123 Shanta 6500 125 Julia 3200

Page 8: Oracle Notes

129 Laura 3300 140 Joshua 2500 141 Trenna 3500 162 Clara 10500 164 Mattea 7200 168 Lisa 11500 173 Sundita 6100 EMPLOYEE_ID FIRST_NAME SALARY ----------- -------------------- ---------- 175 Alyssa 8800 182 Martha 2500 184 Nandita 4200 186 Julia 3400 196 Alana 3100 16 rows selected. SQL> SELECT employee_id, first_name, salary 2 FROM employees 3 WHERE first_name LIKE 'A%a'; EMPLOYEE_ID FIRST_NAME SALARY ----------- -------------------- ---------- 175 Alyssa 8800 196 Alana 3100 SQL> SELECT employee_id, first_name, salary 2 FROM employees 3 WHERE first_name LIKE '__a%'; EMPLOYEE_ID FIRST_NAME SALARY ----------- -------------------- ---------- 107 Diana 4200 121 Adam 8200 123 Shanta 6500 162 Clara 10500 179 Charles 6200 181 Jean 3100 196 Alana 3100 7 rows selected. SQL> SELECT employee_id, first_name, salary 2 FROM employees 3 WHERE first_name = 'A%'; no rows selected

4. IS: used for NULL comparison only.

Page 9: Oracle Notes

Display employees who are not given any commission:SQL> SELECT employee_id, last_name, salary, commission_pct 2 FROM employees 3 WHERE commission_pct IS NULL;

SQL> SELECT employee_id, last_name, salary, commission_pct 2 FROM employees 3 WHERE commission_pct IS NOT NULL;

ORDER BY clause

SELECT <column list> | *FROM <table>WHERE <condition>ORDER BY <colname>;

Order By clause is used to sort the resultset in ascending/descending order based on the given column.

Example 1:Write a query to display employee id, last name and salary in theascending order of their last name.

SELECT employee_id, last_name, salaryFROM employeesORDER BY last_name;

Example 2:Modify the above query to show only those employees whose salary is in between3000 and 5000

SELECT employee_id, last_name, salaryFROM employeesWHERE salary BETWEEN 3000 AND 5000ORDER BY last_name;

Note: You can sort the result using multiple columns

Page 10: Oracle Notes

Example 3:Modify the above query to add department id and sort the information first in theascending order of departments and then in the descending order of theysalary.

SELECT employee_id, department_id, last_name, salaryFROM employeesORDER BY department_id ASC, salary DESC;

Note: the default ordering of ORDER BY clause is Ascending.

Substitution Variable: is used to hold a value temporarily so that you can retreiveit later for some calculations. This variable name must begin with & sign.

Example 4:SQL> SELECT last_name, salary  2  FROM employees  3  WHERE salary > &basic;

If a substitution variable begin with & sign then its life is only as long as the query isrunning. If a substitution variable begin with && sign then its life is as long as the sessionis active. The moment the session is expired the memory for this variable will bereleased.

Example 5:SQL> SELECT last_name, salary  2  FROM employees  3  WHERE salary > &&basic;

using DEFINE command:

This command is used to declare a variable. This also a session-specific variable.

Syntax:DEFINE <variablename>=value

Example 6:SQL> DEFINE sal=5000

SQL> SELECT employee_id, salary

Page 11: Oracle Notes

  2  FROM employees  3  WHERE salary = &sal;

SQL> UNDEFINE sal

The UNDEFINE command will release the memory of the variable declared using theDEFINE command.

FUNCTIONS-----------------Oracle have mainly 2 categories of functions:

1. Single Row FunctionApplies on each rows independantly and gives one result per row.2. Multiple Row Function (Group Function)Applies on each group of rows and gives one result per group

Single Row Functions:Types:1. Character Function2. Number Function3. Date Function4. Conversion Function5. General Function

Character Function-----------------------------A character function passes a character value as a parameter but can return bothcharacter or numeric values.

Types:1. CASE-MANIPULATION  a) UPPER() : convert the character value into upper case  b) LOWER() : convert the character value into lower case  c) INITCAP() : capitalizes the first letter of each word

Example 7:SQL> SELECT upper(last_name), lower(last_name), initcap(last_name)  2  FROM employees;

Example 8:

Page 12: Oracle Notes

SQL> SELECT employee_id, last_name, first_name  2  FROM employees  3  WHERE upper(first_name)='JOHN';

EMPLOYEE_ID LAST_NAME              FIRST_NAME----------- ------------------------- --------------------    110 Chen              John    139 Seo               John    145 Russell              John

2. CHARACTER-MANIPULATION

  a) CONCAT()used to join two character values together.

Example 9:SQL> SELECT concat('John','Smith') FROM dual;

CONCAT('J---------JohnSmith

Example 10:SQL> SELECT concat('John',concat(' ','Smith')) FROM dual;

CONCAT('JO----------John Smith

Example 11:SQL> SELECT concat(first_name, concat('  ',last_name)) AS FullName  2  FROM employees;

Nester function is a function within another function.

  b) SUBSTR()Extracts a string of determined length.

Example 12:SQL> SELECT substr(first_name,1,3) AS code 

Page 13: Oracle Notes

  2  FROM employees;

The first parameter indicate the column namethe second parameter indicate the start positionthe third parameter indicate the total no of characters to be extracted from the givenstart position.

Example 13:SQL> SELECT upper(substr(first_name, 1, 3))  2  FROM employees;

  c) LENGTH()return the length the given string.Example 14:SQL> SELECT first_name, length(first_name) AS total_char  2  FROM employees;

  d) LPAD() and RPAD()LPAD() returns an expresion  left-padded to the length of n characters with a characterexpression.RPAD() returns an expresion  right-padded to the length of n characters with a characterexpression.

Example 15:SQL> SELECT rpad(salary,10,'@')  2  FROM employees;

  e) REPLACE()Replaces a part of the text with the given text.

Example 16:SQL> SELECT replace('Jack and Jue','J','Bl') FROM dual;

REPLACE('JACKA--------------Black and Blue

  f) TRIM()To remove the leading and trailing spaces

Page 14: Oracle Notes

Example 17:SQL> SELECT trim('              Welcome to Oracle               ') AS message  2  FROM dual;

MESSAGE-----------------Welcome to Oracle

2) Number Functions: These functions passes numeric values as parameters and return numberic value

a) ROUND()Rounds the decimal places to the nearest numberb) TRUNC()Truncates the decimal numbers to the given decimal placec) MOD()Returns the remainder of a division

Example 18:SQL> SELECT round(93.563,2)  2  FROM dual;

ROUND(93.563,2)---------------      93.56

Example 19:SQL> SELECT round(93.563,1) FROM dual;

ROUND(93.563,1)---------------       93.6

Example 20:SQL> SELECT trunc(93.563,1) FROM dual;

TRUNC(93.563,1)---------------       93.5

Page 15: Oracle Notes

Example 20:SQL> SELECT mod(1600,200) FROM dual;

MOD(1600,200)-------------        0

Example 21:SQL> SELECT mod(4,2) FROM dual;

  MOD(4,2)----------     0

Example 22:SQL> SELECT mod(3,2) FROM dual;

  MOD(3,2)----------     1

Pseudocolumn

SYSDATE is used to return the system date

3) Date() These functions passes a date value as a parameter and returnthe date or numeric value

Example 23:SQL> SELECT sysdate FROM dual;

SYSDATE---------08-SEP-15

Example 24:SQL> SELECT systimestamp FROM dual;

SYSTIMESTAMP---------------------------------------------------------------------------08-SEP-15 01.09.43.851349 PM +03:00

Page 16: Oracle Notes

SQL>

Note: You can perform arithmetic calculation with date values.

Example 25:SQL> SELECT employee_id, last_name, hire_date, sysdate-hire_date AS total_days  2  FROM employees;

Example 26:SQL> SELECT employee_id, last_name, hire_date, round(sysdate-hire_date) AS total_days  2  FROM employees;

Example 27:SQL> SELECT employee_id, last_name, hire_date, round(sysdate-hire_date) AS total_days,  2  ROUND((sysdate-hire_date)/7) AS Total_Weeks  3  FROM employees;

MONTHS_BETWEEN() used to return total no of months between the given datesSQL> SELECT employee_id, last_name, hire_date, round(sysdate-hire_date) AS total_days,  2  ROUND((sysdate-hire_date)/7) AS Total_Weeks, months_between(sysdate, hire_date) AS  3  Total_Months  4  FROM employees;

NEXT_DAY() : this function will return the date of the first given weekday

Example 28:SQL> SELECT employee_id, last_name, hire_date, next_day(hire_date,'Sunday')  2  FROM employees;

LAST_DAY() : returns the last date of the current month

Example 29:SQL> SELECT last_day(sysdate)  2  FROM dual;

LAST_DAY(---------30-SEP-15

Page 17: Oracle Notes

4) Conversion Function: is used to convert the value from one type to another.The conversion is performed by oracle in two methods:a) Implicit ConversionHere oracle will convert the value from one type to another automatically.

Example 30:SQL> SELECT '10' + '20'  2  FROM dual;

 '10'+'20'----------    30

Example 31:SQL> SELECT employee_id, last_name  2  FROM employees  3  WHERE hire_date='01-JUL-06';

EMPLOYEE_ID LAST_NAME----------- -------------------------    194 McCain

b) Explicit ConversionHere you must use a function to do the conversion.

i) TO_CHAR()It converts the given value to a character type. It is used to format the output.

Example 32:SQL> SELECT employee_id, last_name, to_char(hire_date,'YYYY / MM / DD HH:MI:SS AM') AS hiredate  2  FROM employees;

Example 33:SQL> SELECT to_char(sysdate,'Month DD YYYY Day HH24:MI:SS') AS today  2  FROM dual;

TODAY

Page 18: Oracle Notes

------------------------------------September 08 2015 Tuesday   13:30:24

Example 34:SQL> SELECT to_char(sysdate,'Mon DD YYYY Dy HH:MI:SS AM') AS Today  2  FROM dual;

TODAY---------------------------Sep 08 2015 Tue 01:31:24 PM

Example 35:SQL> SELECT to_char(sysdate,'fmDdspth "of" Month YYYY HH:MI:SS AM') FROM dual;

TO_CHAR(SYSDATE,'FMDDSPTH"OF"MONTHYYYYHH:MI:--------------------------------------------Eighth of September 2015 1:32:51 PM

Example: To_char with Numeric type

SQL> SELECT employee_id, last_name, department_id, to_char(salary,'$99,999.00') AS salary  2  FROM employees;

ii) TO_DATE() : used to convert the character value holding date of any format to a validdate value.

Implicit Conversion

SQL> SELECT employee_id, last_name, department_id, hire_date  2  FROM employees  3  WHERE hire_date > '31-DEC-2007';

The below query will give error as the format of date is not correct:SQL> SELECT employee_id, last_name, department_id, hire_date  2  FROM employees  3  WHERE hire_date > '12/31/2007';

Modify the above query by using TO_DATE()SQL> SELECT employee_id, last_name, department_id, hire_date  2  FROM employees  3  WHERE hire_date > TO_DATE('12/31/2007','MM/DD/YYYY');

Page 19: Oracle Notes

iii) TO_NUMBER(): used to convert the character to a date value.

SQL> SELECT '10' * '2' FROM dual;

  '10'*'2'----------    20

SQL> SELECT to_number('10') * to_number('2') FROM dual;

TO_NUMBER('10')*TO_NUMBER('2')------------------------------                20

5. GENERAL Function:They can be applied on any type of columns:

Types:a) NVL() it works with null. It is used to convert the null value to a given value beforeperforming the calculation.

Example:Write a query to display employee id,last name, department id, salary, commission and net salary of an emlployee.

SELECT employee_id, last_name, department_id, salary, commission_pct, salary+(salary*NVL(commission_pct,0)) AS NetFROM employees;

b) NVL2()This function also works with null values. It is an extended version of NVL()

Example:Write a query to display employee id, last name, salary, commission and income of an employee.The income should show "Salary Only" if the employee do not earn any commission. Else it shouldshow "Salary and Commission" as income.

SQL> SELECT employee_id, last_name, salary, commission_pct,

Page 20: Oracle Notes

NVL2(commission_pct,'Salary and Commission','Salary Only') AS Income  2  FROM employees;

c) NULLIF() : works with null values.If compares both the parameters passed and returns NULL if both them matches else it will returnthe first parameter.

SQL> SELECT nullif('Oracle','oracle') from dual;

NULLIF------Oracle

SQL> SELECT nullif('Oracle','Oracle') from dual;

NULLIF------

d) COALESCE() it operates on null valuesYou can pass any no of parameters to this function.

SELECT coalesce(null,null,null,null,null,22,34,45,5,null) from dual;

e) IF THEN ELSE construct

  i) CASE EXPRESSION  ii DECODE()

Syntax of CASE expression:

CASE <expr>  WHEN <condition> THEN <value>  WHEN <condition> THEN <value>  WHEN <condition> THEN <value>  ELSE <value>END

Example:Write a query to display employee id, last_name, jobid,  salary, and bonus of the employee.

Page 21: Oracle Notes

The Criteria to calculate the bonus is:If job_id = IT_PROG, Bonus=45% of SalaryIf job_id='FI_ACCOUNT', Bonus=40% SalaryIf job_id='SA_REP', Bonus=35% of SalaryFor all other employees bonus=20% of salary

SELECT employee_id, last_name, job_id, salary, CASE job_id      WHEN 'IT_PROG' THEN salary*0.45      WHEN 'FI_ACCOUNT' THEN salary*0.4      WHEN 'SA_REP' THEN salary*0.35      ELSE salary*0.2END AS BonusFROM employees;

Write a query to display employee id, last_name, jobid,  salary, and bonus of the employee.The Criteria to calculate the bonus is:If salary < 1500, Bonus=0If salary is between 1500 and 3000, Bonus=25% of salaryif salary is between 3000 and 5000, Bonus=45% of salaryelse bonus=50% of salary

SELECT employee_id, last_name, job_id, salary, CASE     WHEN salary<1500 THEN 0    WHEN salary BETWEEN 1500 AND 3000 THEN salary*0.25    WHEN salary BETWEEN 3000 AND 5000 THEN salary*0.45    ELSE salary*0.5END AS BonusFROM employees;

decode() is an alternate to CASE expression

Write a query to display employee id, last_name, jobid,  salary, and bonus of the employee.The Criteria to calculate the bonus is:If job_id = IT_PROG, Bonus=45% of SalaryIf job_id='FI_ACCOUNT', Bonus=40% SalaryIf job_id='SA_REP', Bonus=35% of SalaryFor all other employees bonus=20% of salary

Page 22: Oracle Notes

SELECT employee_id, last_name, job_id, salary, decode(job_id,'IT_PROG',salary*0.45,'FI_ACCOUNT',salary*0.4,'SA_REP',salary*0.35,salary*0.2) AS BonusFROM employees;

Group Function: Operates on each group and gives one result per group:

Types:1. SUM() : get the sum of range of values2. COUNT() : get the total count of values in the range3. MIN() : get the lowest value from range4. MAX() :  get the highest value from the range5. AVG() : get the average value from the range of values.

By default the entire table will be considered as one group.

Group Function ignores null values:SQL> SELECT sum(salary) AS Tot_Sal, min(salary) AS Min_Sal, max(salary) AS max_sal, avg(salary) AS avg_sal,  2  count(salary) AS tot_sal  3  FROM employees;

   TOT_SAL    MIN_SAL     MAX_SAL    AVG_SAL    TOT_SAL---------- ---------- ---------- ---------- ----------    691516     2100       24100 6462.76636       107

SQL> SELECT count(commission_pct)  2  FROM employees;

COUNT(COMMISSION_PCT)---------------------           35

GROUP BY clause used to form groups based on a column while using group function.

Write a query to display department-wise total salary givenSQL> SELECT department_id, sum(salary)  2  FROM employees  3  GROUP BY department_id;

Page 23: Oracle Notes

Using ORDER BYSQL> SELECT department_id, sum(salary)  2  FROM employees  3  GROUP BY department_id  4  ORDER BY sum(salary) DESC;

Modify the above query to remove the department 100, 101 and null

SQL> SELECT department_id, sum(salary)  2  FROM employees  3  WHERE department_id NOT IN(100,101) AND department_id IS NOT NULL  4  GROUP BY department_id  5  ORDER BY sum(salary) DESC;

Modify the above question to show only those departments whose total salary isgreater than 15000

SQL> SELECT department_id, sum(salary)  2  FROM employees  3  WHERE department_id NOT IN(100,101) AND department_id IS NOT NULL  4  GROUP BY department_id      HAVING sum(salary) >15000  5  ORDER BY sum(salary) DESC;

Note: You can also group the result based on multiple columns:

Display department-wise total no of employees for each jobs.

SQL> SELECT department_id, job_id, count(employee_id)  2  FROM employees  3  GROUP BY department_id, job_id  4  ORDER BY department_id, job_id;

Sub Queries and Joins---------------------------------

Sub query is used to get result of one table based on the value of some other table.

Syntax:

Page 24: Oracle Notes

Outer Query = (    Inner Query (Sub Query))

For Example: Display employees of Shipping department

SELECT employee_id, last_name, salary, department_idFROM employeesWHERE department_id = (      SELECT department_id      FROM departments      WHERE department_name='Shipping')

Example:Write a query to display employees belonging the city Seattle

SELECT employee_id, last_name, salary, department_idFROM employeesWHERE department_id IN(      SELECT department_id          FROM departments      WHERE location_id=      (        SELECT location_id        FROM locations        WHERE city='Seattle'      ))

Types:A subquery is of two types:1. Single row subqueryHere the inner query returns only one row value to its parent queryHere you can use = operator2. multiple row subqueryHere the inner query returns more than one row value to its parent query

Page 25: Oracle Notes

Here you cannot use = operator

Joins: helps you to combne columns of two or many tables and display them as a single resultset.

Types:1. NATURAL JOINYou can perform joins between two tables only if they have common columns.In Natural Join, oracle will take the common column to be used for joining.

Syntax:

SELECT <columns of two tables>FROM <table1> NATURAL JOIN <table2>;

For ExampleWrite a query to show employee id, last name, department id and department name for all employees

SQL> SELECT employee_id, last_name, department_id, department_name  2  FROM employees NATURAL JOIN departments;

Restriction: You can perform natural join between two tables only of the common columnsof both table matches in terms of their data type as well as their name.

2. Joining with USING keywordUSed to instruct oracle, what common column to be used for joining.

Syntax:

SELECT a.employee_id, a.first_name, b.department_name, department_idFROM employees a JOIN departments b USING(department_id)

3. Joining with ON keyword

Also used to instruct oracle what common column to be used for joining

SELECT emp.employee_id, emp.last_name, dep.department_name, loc.cityFROM employees emp JOIN departments dep ON emp.department_id=dep.department_id JOIN locations loc ON loc.location_id=dep.location_id;

Page 26: Oracle Notes

4. SELF JOINJoining a table to itslef is called as self join.

Write a query to show the employee name and his manager name.SQL> SELECT emp.first_name AS employee, mgr.first_name AS manager  2  FROM employees emp JOIN employees mgr  3  ON emp.manager_id=mgr.employee_id  4  ORDER BY emp.first_name;

5. OUTER JOINThis type of join can show unmatched records alsoTypes:    a) Left Outer Join    b) Right Outer Join    c) Full Outer Join

SELECT emp.employee_id, emp.last_name, dep.department_nameFROM employees emp LEFT OUTER JOIN departments dep ON emp.department_id=dep.department_id;

SELECT emp.employee_id, emp.last_name, dep.department_nameFROM employees emp RIGHT OUTER JOIN departments dep ON emp.department_id=dep.department_id;

SELECT emp.employee_id, emp.last_name, dep.department_nameFROM employees emp FULL OUTER JOIN departments dep ON emp.department_id=dep.department_id;

6. CROSS JOIN

is also called as Cartesian product of two tables

Table A = 5 rowsTable B = 10 rows

Table A CROSS JOIN Table B = 5 * 10 = 50 rowsSQL> SELECT employee_id, last_name, department_name  2  FROM employees CROSS JOIN departments;

Page 27: Oracle Notes

Sub Query------------------IN or ANY can be used if the inner query returns more than one row of value.

There are 3 types of ANY1. <ANY means less than the maximum2. >ANY means more than the minimum3. =ANY is same as IN operator

Example: Write a query to show employee id, last name, job id, and salary of allemployees whose salary is less than the salary of all employees with a job id of IT_PROG.

SQL> SELECT employee_id, last_name, job_id, salary  2  FROM employees  3  WHERE salary <ANY  4  (  5  SELECT salary  6  FROM employees  7  WHERE job_id='IT_PROG'  8  );

Equi Join and Non-Equi Join----------------------------------------SELECT emp.employee_id, emp.last_name, dep.department_nameFROM employees emp JOIN departments depON emp.department_id = dep.department_id;

Non-Equi join: here the common columns of two tables are joined using non-equalitycomparison operator such as <, >, BETWEEN, etc.

Display employee id, last name and grade of an employees for only those employeeswhose salary is within the min and max salary of their grade.

SQL> SELECT emp.employee_id, emp.last_name, emp.salary,grd.gradeid      2  FROM employees emp JOIN grades grd  3  ON emp.salary BETWEEN grd.minsal AND grd.maxsal;

SET OPERATORS

Page 28: Oracle Notes

used to combine the result of two or more tables and display as a singleresultset.

SELECT col4, col2, col3 FROM table1<SET OPERATOR TYPE>SELECT col4, col2, col3FROM table2

Guidelines to be followed to use SET operators1. The no of columns of both joined tables should match.2. The order of columns in the first query should match with the second query3. The names of the supplied columns can differ

Types:

1. UNION : returns rows from both the queries after eliminating the duplications.SQL> select * from testa;

     X Y---------- ----------------------------------------     1 A     2 B     3 C

SQL> select * from testb;

     A B         C---------- --------- ----------------------------------------     1 09-SEP-15 A     2 09-SEP-15 B     5 09-SEP-15 F     6 09-SEP-15 H

SQL> SELECT x,y FROM testa  2  UNION  3  SELECT a,c FROM testb;

     X Y---------- ----------------------------------------     1 A     2 B

Page 29: Oracle Notes

     3 C     5 F     6 H

SQL> ^C

SQL> SELECT x,y FROM testa  2  UNION ALL  3  SELECT a,c FROM testb;

     X Y---------- ----------------------------------------     1 A     2 B     3 C     1 A     2 B     5 F     6 H

7 rows selected.

b) INTERSECT  shows only common rows of two tables removing the distinct rowsSQL> SQL> SELECT x,y FROM testa  2  INTERSECT  3  SELECT a,c FROM testb;

     X Y---------- ----------------------------------------     1 A     2 B

c) MINUS: it displays all the rows of first query that are not available in the second query.

SQL> select * from testa;

     X Y---------- ----------------------------------------

Page 30: Oracle Notes

     1 A     2 B     3 C

SQL> select * from testb;

     A B         C---------- --------- ----------------------------------------     1 09-SEP-15 A     2 09-SEP-15 B     5 09-SEP-15 F     6 09-SEP-15 H

SQL> SELECT a,c FROM testb  2  MINUS  3  SELECT x,y FROM testa;

     A C---------- ----------------------------------------     5 F     6 H

Database Objects------------------------1. Table2. View3. Sequence4. Synonym5. Index

Table: is used to store data permanently in rows and column format. Syntax:

CREATE TABLE <tablename>(        <colname> <datatype>(size),    <colname> datatype>(size));Rules to follow while naming a database object:1. Must begin with a letter

Page 31: Oracle Notes

2. Be 1 to 30 characters long3. Can contain A-Z, a-z, 0-9, _, $ and #4. The object name cannot be duplicated5. It cannot be a reserved word

CREATE TABLE employee(    empCode CHAR(5),    empName VARCHAR(40),    joinDate  DATE,    salary NUMBER(8,2));

To insert a new row:

INSERT INTO employee VALUES('EMP001','PETER',sysdate,4500);

OR

INSERT INTO employee (salary,empName, empCode, joinDate)VALUES(3000,'Peter','EMP02',sysdate);

To ignore the columns

INSERT INTO employee (empCode, empName) VALUES ('EMP03','John');When a column is ignored,oracle will place a NULL to the ignored column.

You can also ignore a column by explicitly providing the null keyword.

INSERT INTO employee VALUES(null,null,null,null);

Data Manipulation LanguageINSERT DELETEUPDATE

DELETE command: used to remove one or more rows from a table.

Syntax:DELETE FROM <tablename>

Page 32: Oracle Notes

[WHERE <condition>];

DELETE FROM employeeWHERE empCode='EMP01';

UPDATE command: used to modify one or more column value.

UPDATE <tablename>SET <colname>=<new val>[WHERE <cond>];

UPDATE employeeSET salary=salary+100WHERE empCode='EMP01';

Constraint:is a rule applied on a column to restrint users from entering invalid data.

Types:1. NOT NULL2. CHECK3. UNIQUE4. DEFAULT property5. PRIMARY KEY6. FOREIGN KEY

NOT NULL: used to make a column require and cannot be ignored.

CREATE TABLE employee1(empCode CHAR(10) NOT NULL,empName VARCHAR(50) NOT NULL,joinDate DATE,salary number(8,2));

SQL> desc employee1 Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPCODE                   NOT NULL CHAR(10)

Page 33: Oracle Notes

 EMPNAME                   NOT NULL VARCHAR2(50) JOINDATE                        DATE SALARY                         NUMBER(8,2)

SQL> insert into employee1 (empCode, joindate, salary)  2  values('EMP001',sysdate,3000);insert into employee1 (empCode, joindate, salary)*ERROR at line 1:ORA-01400: cannot insert NULL into ("HR"."EMPLOYEE1"."EMPNAME")

Note: Any no of columns in a table can have NOT NULL constraint.

2. CHECKis used to allow users to enter only specific values as per the given condition.

CREATE TABLE employee2(empCode CHAR(10) NOT NULL,empName VARCHAR(40) NOT NULL,gender CHAR(1) NOT NULL  CHECK(gender IN('M','F')),joinDate DATE,salary NUMBER(8,2));

3. UNIQUE: restrict the user from entering duplicate values in a column,

CREATE TABLE employee3(empCode CHAR(10) NOT NULL UNIQUE,empName VARCHAR(40) NOT NULL,gender CHAR(1) CHECK(gender IN('M','F')),salary NUMBER (8,2) CHECK (salary BETWEEN 500 and 25000),joindate DATE,Email VARCHAR(25) UNIQUE);

SQL> INSERT INTO employee3 VALUES('&empcode','&empName','&gender',&basic,'&hiredate','&email');

Page 34: Oracle Notes

4. DEFAULT propertyBy default when a column is ignored, oracle will place a null value to that column.The default property is used to insert some other value other than null when it isignored. It can be applied only to nullable columns.

SQL> CREATE TABLE employee4   2  (  3  empCode CHAR(10) NOT NULL UNIQUE,  4  empName VARCHAR(40) NOT NULL,  5  joindate DATE DEFAULT sysdate,  6  gender CHAR(1) DEFAULT 'M' CHECK (gender IN('M','F'))  7  );

SQL> insert into employee4 (empCode, empName) VALUES ('EMP002','Peter');

1 row created.

SQL> select * from employee4;

EMPCODE    EMPNAME                    JOINDATE  G---------- ---------------------------------------- --------- -EMP001       Mike                     10-JAN-15 MEMP002       Peter                    09-SEP-15 M

4. PRIMARY KEYA table can have only 1 primary key column. it is used to uniquely identofy tworows in a table. When a column  is set as PRIMARY KEY, it also gets NOT NULL and UNIQUE constraints.

CREATE TABLE employee5( empCode CHAR(10) PRIMARY KEY,empName VARCHAR(40) NOT NULL,gender CHAR(1) default 'M' CHECK(gender IN('M','F')));

5. FOREIGN KEYis the primary key column of some other table.

Page 35: Oracle Notes

Dept------DeptId     DeptName1        Admin2        Marketing

Emp-------EmpId DeptCode EmpName Salary1001   1                Peter          50001002   1                Mary          45001003   1                George          23001004   1                Peter          3400

SQL> CREATE TABLE tasafdept  2  (  3  deptcode NUMBER PRIMARY KEY,  4  deptname VARCHAR(40) NOT NULL UNIQUE  5  );

Table created.

SQL> CREATE TABLE tasafemp  2  (  3  empcode CHAR(15) PRIMARY KEY,  4  deptid NUMBER REFERENCES tasafdept(deptcode),  5  empname VARCHAR(50)  6  );

Table created.

SQL> insert into tasafdept values(&dcode,'&dname')  2  ;Enter value for dcode: 10  Enter value for dname: Adminold   1: insert into tasafdept values(&dcode,'&dname')new   1: insert into tasafdept values(10,'Admin')

1 row created.

SQL> /

Page 36: Oracle Notes

Enter value for dcode: 20Enter value for dname: Marketingold   1: insert into tasafdept values(&dcode,'&dname')new   1: insert into tasafdept values(20,'Marketing')

1 row created.

SQL> insert into tasafemp VALUES('&ecode',&dcode,'&ename');Enter value for ecode: EMP001Enter value for dcode: 10Enter value for ename: Mikeold   1: insert into tasafemp VALUES('&ecode',&dcode,'&ename')new   1: insert into tasafemp VALUES('EMP001',10,'Mike')

1 row created.

SQL> /Enter value for ecode: EMP002Enter value for dcode: 10Enter value for ename: Peterold   1: insert into tasafemp VALUES('&ecode',&dcode,'&ename')new   1: insert into tasafemp VALUES('EMP002',10,'Peter')

1 row created.

SQL> /Enter value for ecode: EMP003Enter value for dcode: 20Enter value for ename: Allyold   1: insert into tasafemp VALUES('&ecode',&dcode,'&ename')new   1: insert into tasafemp VALUES('EMP003',20,'Ally')

1 row created.

SQL> SELECT * FROM tasafdept;

  DEPTCODE DEPTNAME---------- ----------------------------------------    10 Admin    20 Marketing

Page 37: Oracle Notes

SQL> select * from tasafemp;

EMPCODE         DEPTID EMPNAME--------------- ---------- --------------------------------------------------EMP001            10 MikeEMP002            10 PeterEMP003            20 Ally

SQL> insert into tasafemp values('EMP004',40,'John');insert into tasafemp values('EMP004',40,'John')*ERROR at line 1:ORA-02291: integrity constraint (HR.SYS_C0011137) violated - parent key notfound

After the table creation----------------------------------------You need to use ALTER command to modify the table sructureUsing the ALTER command you can:1. Add a new columnSyntax:

ALTER TABLE <tablename> ADD (<colname> <datatype>); SQL> ALTER TABLE employee  2  ADD(gender CHAR(1));

ORacle will insert NULL to the existing rows of the new column.Note: You cannot add a new column with NOT NULL constraint if the table has any row.

2. delete an existing columnALTER TABLE <tablename>DROP COLUMN <colname>;

SQL> ALTER TABLE employee  2  DROP COLUMN gender;

3. add a new constraint

Page 38: Oracle Notes

ALTER TABLE <tablename>ADD CONSTRAINT <consname> <constype> (<conscol>);

To make a col unique------------------------------SQL> ALTER TABLE employee   2  ADD CONSTRAINT UNQ_EMPLOYEE_EMAIL UNIQUE(email);Note: ensure that the column do not have any duplicate values before adding a UNIQUE constraint.

CHECKSQL> ALTER TABLE employee  2  ADD CONSTRAINT CHK_EMPLOYEE_SALARY CHECK(salary BETWEEN 500 and 25000);

Note: Ensure that the values in the column satisfied the criteria defined in the CHECK constraint

PRIMARY KEYSQL> ALTER TABLE employee  2  ADD CONSTRAINT PK_EMPLOYEE_EMPCODE PRIMARY KEY(empcode);

Note: ensure that the column to be made primary do not have any duplicate/null values.

FOREIGN KEYSQL> ALTER TABLE employee  2  ADD CONSTRAINT FK_EMPLOYEE_DEPT FOREIGN KEY(DEPT) REFERENCES tasafdept(deptcode);

Note: Ensure that the column to be made foreign donot have any invalid value.

A foreign key column can be ignored.

4. delete an existing constraint

ALTER TABLE <tablename>DROP CONSTRAINT <consname>;

SQL> ALTER TABLE employee  2  DROP CONSTRAINT CHK_EMPLOYEE_SALARY;

Page 39: Oracle Notes

Table altered.

To enable/disable constraints:

SQL> ALTER TABLE employee  2  ENABLE CONSTRAINT FK_EMPLOYEE_DEPT;

SQL> ALTER TABLE employee  2  ENABLE CONSTRAINT FK_EMPLOYEE_DEPT;

SQL> SELECT constraint_name, constraint_type, status  2  FROM user_constraints  3  WHERE table_name='EMPLOYEE';

CONSTRAINT_NAME            C STATUS------------------------------ - --------UNQ_EMPLOYEE_EMAIL           U ENABLEDPK_EMPLOYEE_EMPCODE           P ENABLEDFK_EMPLOYEE_DEPT           R ENABLED

SQL> ALTER TABLE employee DISABLE CONSTRAINT UNQ_EMPLOYEE_EMAIL;

Table altered.

SQL> SELECT constraint_name, constraint_type, status  2  FROM user_constraints  3  WHERE table_name='EMPLOYEE';

CONSTRAINT_NAME            C STATUS------------------------------ - --------UNQ_EMPLOYEE_EMAIL           U DISABLEDPK_EMPLOYEE_EMPCODE           P ENABLEDFK_EMPLOYEE_DEPT           R ENABLED

SET UNUSED commandALTER TABLE <table_name>SET UNUSED(<column_name>);

is used to mark the column for deletion.

Page 40: Oracle Notes

SQL> ALTER TABLE employee  2  SET UNUSED (email);

To drop all unused columns from the given table:SQL> ALTER TABLE employee  2  DROP UNUSED COLUMNS;

ALTER TABLE <table_name>DROP UNUSED COLUMNS;

ON DELETE CASCADE------------------------------Will delete all the referencing rows from the child tables when you attempt to deletethe parent table rows.

ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fkFOREIGN KEY (Department_id)REFERENCES departments ON DELETE CASCADE);

Deferring ConstraintsConstraints can have the following attributes:• DEFERRABLE or NOT DEFERRABLE• INITIALLY DEFERRED or INITIALLY IMMEDIATE

ALTER TABLE dept2ADD CONSTRAINT dept2_id_pkPRIMARY KEY (department_id)DEFERRABLE INITIALLY DEFERRED

SQL> ALTER TABLE testemp1  2  ADD CONSTRAINT PK_TESTEMP1_ECODE PRIMARY KEY(ecode) DEFERRABLE INITIALLY DEFERRED;

To change the behaviour of a deferrable constraint:

SET CONSTRAINT <consname> IMMEDIATE|DEFERRED;

SQL> SET CONSTRAINT PK_TESTEMP1_ECODE IMMEDIATE;

Page 41: Oracle Notes

Cascading Constraints• The CASCADE CONSTRAINTS clause is used alongwith the DROP COLUMN clause.• The CASCADE CONSTRAINTS clause drops allreferential integrity constraints that refer to theprimary and unique keys defined on the droppedcolumns.• The CASCADE CONSTRAINTS clause also drops allmulticolumn constraints defined on the droppedcolumns.

ALTER TABLE emp2DROP COLUMN employee_id CASCADE CONSTRAINTS;

The above command will drop the primary key column and also all the foreign keyconstraints referencing this column.

Table altered.ALTER TABLE test1DROP (pk, fk, col1) CASCADE CONSTRAINTS;

5. modify an existing column, type, size, or constraintALTER TABLE <tablename>MODIFY (<colname> <newdatatype>(<newsize>);

SQL> ALTER TABLE tasafemp  2  MODIFY(empname VARCHAR(55));

To Drop a table:DROP TABLE <tablename>;

VIEWS----------helps to restrict users from viewing sensitive information of a table. A view do not havedata of its own.

Syntax:

Page 42: Oracle Notes

CREATE VIEW <viewname>AS <select statement>;

Types:1. Simple ViewIs one where only 1 table is used as the base table.

SQL> CREATE VIEW myv1   2  AS SELECT employee_id, department_id, last_name, salary  3  FROM employees;

You can perform all DML operation on the table though the view if it is a simple view.

2. Complex View

is one that uses joins, sub query, group functionsSQL> CREATE VIEW myv3  2  AS SELECT emploeye_id, last_name, salary, department_id  3  FROM employees  4  WHERE department_id IN  5  (  6  SELECT department_id  7  FROM departments  8  WHERE location_id=  9  ( 10  SELECT location_id 11  FROM locations 12  WHERE city='Seattle' 13  ));

SQL> CREATE VIEW myv4  2  AS SELECT department_id, count(employee_id) AS total_emp  3  FROM employees  4  GROUP BY department_id  5  ORDER BY department_id;

To Drop a view DROP VIEW <viewname>;

Page 43: Oracle Notes

3. SEQUENCEused to generate numbers.

Syntax:CREATE SEQUENCE <seqname>;

SQL> CREATE SEQUENCE myseq1;

SQL> SELECT myseq1.NEXTVAL from dual;

SQL> SELECT myseq1.CURRVAL FROM dual;

SQL> CREATE SEQUENCE myseq2  2  START WITH 1000;

SQL> CREATE SEQUENCE myseq3  2  START WITH 1000  3  INCREMENT BY 2;

SQL> CREATE SEQUENCE myseq5  2  MAXVALUE 20  3  CYCLE NOCACHE;

SYNONYM-----------------they are used another name to a database object.SQL> CREATE SYNONYM mike FOR employees;

INDEX--------are used to retreive data faster.

To create an index :

CREATE INDEX <indname> ON <tablename>(colname);

Apply index on a column only if:1. If the table is very large/2. if the column holds large no of unique values.

Page 44: Oracle Notes

Function based index:

SQL> CREATE INDEX indempname1  2  ON tasafemp(upper(empname));

To DROP an indexDROP INDEX <indname>;

What happend when a table is dropped.

FLASHBACK TABLE testemp1 TO BEFORE DROP;

To drop table permanently:SQL> DROP TABLE testemp1 PURGE;

External TablesCreating a Directory for the External TableCreate a DIRECTORY object that corresponds to thedirectory on the file system where the external datasource resides.CREATE OR REPLACE DIRECTORY emp_dirAS '/.../emp_dir';

GRANT READ ON DIRECTORY emp_dir TO hr;

CREATE TABLE oldemp (fname char(25), lname CHAR(25))ORGANIZATION EXTERNAL(TYPE ORACLE_LOADERDEFAULT DIRECTORY emp_dirACCESS PARAMETERS(RECORDS DELIMITED BY NEWLINENOBADFILENOLOGFILEFIELDS TERMINATED BY ','

Page 45: Oracle Notes

(fname POSITION ( 1:20) CHAR,lname POSITION (22:41) CHAR))LOCATION ('emp.dat'))PARALLEL 5REJECT LIMIT 200;

Command to drop the table from the recyclebinSQL> PURGE TABLE "BIN$H1KFWZPqSUngUKjAQQIc4Q==$0";

TRUNCATE: this command deletes all the rows from a table and cannot be rolled back.

SQL> TRUNCATE TABLE testb;

CREATING A TABLE BY using another tabe:

SQL> INSERT INTO mydept (employee_id, last_name, department_id, salary)  2  SELECT employee_id, last_name, department_id, salary  3  FROM employees  4  WHERE salary BETWEEN 5000 AND 7000;

14 rows created.

SQL> CREATE TABLE mydept2  2  AS SELECT * FROM employees;

Table created.

SQL> TRUNCATE TABLE mydept2;

Table truncated.

SQL> INSERT INTO mydept2  2  SELECT * FROM employees;

108 rows created.

Page 46: Oracle Notes

Types of Multitable INSERT StatementsThe different types of multitable INSERT statementsare:• Unconditional INSERT• Conditional ALL INSERT• Conditional FIRST INSERT• Pivoting INSERT

Unconditional INSERT ALL•Select the EMPLOYEE_ID, HIRE_DATE, SALARY, andMANAGER_ID values from the EMPLOYEES table forthose employees whose EMPLOYEE_ID is greaterthan 200.• Insert these values into the SAL_HISTORY andMGR_HISTORY tables using a multitable INSERT.

INSERT ALLINTO sal_history VALUES(EMPID,HIREDATE,SAL)INTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID, hire_date HIREDATE,salary SAL, manager_id MGRFROM employeesWHERE employee_id > 200;

Conditional INSERT ALL• Select the EMPLOYEE_ID, HIRE_DATE, SALARY, andMANAGER_ID values from the EMPLOYEES table forthose employees whose EMPLOYEE_ID is greaterthan 200.• If the SALARY is greater than $10,000, insert thesevalues into the SAL_HISTORY table using aconditional multitable INSERT statement.• If the MANAGER_ID is greater than 200, insert thesevalues into the MGR_HISTORY table using aconditional multitable INSERT statement.

Conditional INSERT ALL

Page 47: Oracle Notes

INSERT ALLWHEN SAL > 10000 THENINTO sal_history VALUES(EMPID,HIREDATE,SAL)WHEN MGR > 200THENINTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID,hire_date HIREDATE,salary SAL, manager_id MGRFROMemployeesWHERE employee_id > 200;

Conditional INSERT FIRST•Select the DEPARTMENT_ID, SUM(SALARY), andMAX(HIRE_DATE) from the EMPLOYEES table.•If the SUM(SALARY) is greater than $25,000, theninsert these values into the SPECIAL_SAL, using aconditional FIRST multitable INSERT.•If the first WHEN clause evaluates to true, then thesubsequent WHEN clauses for this row should beskipped.•For the rows that do not satisfy the first WHENcondition, insert into the HIREDATE_HISTORY_00,HIREDATE_HISTORY_99, or HIREDATE_HISTORYtables, based on the value in the HIRE_DATEcolumn using a conditional multitable INSERT.

Conditional INSERT FIRSTINSERT FIRSTWHEN SAL > 25000THENINTO special_sal VALUES(DEPTID, SAL)WHEN HIREDATE like ('%00%') THENINTO hiredate_history_00 VALUES(DEPTID,HIREDATE)WHEN HIREDATE like ('%99%') THENINTO hiredate_history_99 VALUES(DEPTID, HIREDATE)ELSEINTO hiredate_history VALUES(DEPTID, HIREDATE)

Page 48: Oracle Notes

SELECT department_id DEPTID, SUM(salary) SAL,MAX(hire_date) HIREDATEFROMemployeesGROUP BY department_id;

Pivoting INSERT• Suppose you receive a set of sales records from a   nonrelational database table,  SALES_SOURCE_DATA, in the following format: EMPLOYEE_ID, WEEK_ID, SALES_MON, SALES_TUE,SALES_WED, SALES_THUR, SALES_FRI• You want to store these records in the   SALES_INFO table in a more typical relational  format: EMPLOYEE_ID, WEEK, SALESUsing a pivoting INSERT, convert the set of salesrecords from the nonrelational database table torelational format.

Pivoting INSERTINSERT ALLINTO sales_info VALUES (employee_id,week_id,sales_MON)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_FRIFROM sales_source_data;

The MERGE Statement•Provides the ability to conditionally update orinsert data into a database table•Performs an UPDATE if the row exists, and anINSERT if it is a new row:

Page 49: Oracle Notes

– Avoids separate updates– Increases performance and ease of use– Is useful in data warehousing applications

Merging RowsInsert or update rows in the EMPL3 table to match theEMPLOYEES table.MERGE INTO empl3 cUSING employees eON (c.employee_id = e.employee_id)WHEN MATCHED THENUPDATE SETc.first_name= e.first_name,c.last_name= e.last_name,...c.department_id = e.department_idWHEN NOT MATCHED THENINSERT 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);

Merging RowsTRUNCATE TABLE empl3;SELECT *FROM empl3;no rows selectedMERGE INTO empl3 cUSING employees eON (c.employee_id = e.employee_id)WHEN MATCHED THENUPDATE SET...WHEN NOT MATCHED THEN

Page 50: Oracle Notes

INSERT VALUES...;SELECT *FROM empl3;

Column comparisons in a multiple-column subquerycan be:• Pairwise comparisons• Nonpairwise comparisons

Pairwise Comparison SubqueryDisplay the details of the employees who are managedby the same manager and work in the samedepartment as the employees with EMPLOYEE_ID 199or 174.SELECT employee_id, manager_id, department_idFROMemployeesWHERE (manager_id, department_id) IN(SELECT manager_id, department_idFROMemployeesWHERE employee_id IN (199,174))ANDemployee_id NOT IN (199,174);

Nonpairwise Comparison SubqueryDisplay the details of the employees who are managedby the same manager as the employees withEMPLOYEE_ID 174 or 199 and work in the samedepartment as the employees with EMPLOYEE_ID 174or 199.SELECT employee_id, manager_id, department_idFROM employeesWHERE manager_id INAND (SELECT manager_id FROM employees WHERE employee_id IN (174,199))AND department_id IN(SELECT department_id FROM employees WHERE employee_id IN (174,199))employee_id NOT IN(174,199);

Page 51: Oracle Notes

Scalar Subquery Expressions•A scalar subquery expression is a subquery thatreturns exactly one column value from one row.•Scalar subqueries can be used in:– Condition and expression part of DECODE and CASE– All clauses of SELECT except GROUP BY

Scalar Subqueries: Examples•Scalar subqueries in CASE expressionsSELECT employee_id, last_name,(CASE20WHEN department_id =(SELECT department_idFROM departmentsWHERE location_id = 1800)THEN 'Canada' ELSE 'USA' END) locationFROMemployees;•Scalar subqueries in ORDER BY clauseSELECTemployee_id, last_nameFROMemployees eORDER BY (SELECT department_nameFROM departments dWHERE e.department_id = d.department_id);

Correlated SubqueriesCorrelated subqueries are used for row-by-rowprocessing. Each subquery is executed once for everyrow of the outer query.

Correlated SubqueriesThe subquery references a column from a table in theparent query.SELECT column1, column2, ...outer

Page 52: Oracle Notes

FROMtable1WHERE column1 operator(SELECTFROMWHEREcolumn1, column2table2expr1 =outer.expr2);

Using Correlated SubqueriesFind all employees who earn more than the averagesalary in their department.SELECT last_name, salary, department_idFROMemployees outerWHERE salary >(SELECT AVG(salary)FROMemployeesWHERE department_id =outer.department_id);

Using Correlated SubqueriesDisplay details of those employees who have changedjobs at least twice.SELECT e.employee_id, last_name,e.job_idFROMemployees eWHERE 2 <= (SELECT COUNT(*)FROMjob_historyWHERE employee_id = e.employee_id);

Using the EXISTS Operator•The EXISTS operator tests for existence of rows inthe results set of the subquery.

Page 53: Oracle Notes

•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

Find Employees Who Have at Least OnePerson Reporting to ThemSELECT employee_id, last_name, job_id, department_idFROMemployees outerWHERE EXISTS ( SELECT 'X'FROMemployeesWHERE manager_id =outer.employee_id);

Find All Departments That Do Not HaveAny EmployeesSELECT department_id, department_nameFROM departments dWHERE NOT EXISTS (SELECT 'X'FROMemployeesWHERE department_id = d.department_id);

Correlated UPDATEUse a correlated subquery to update rows in one tablebased on rows from another table.

ALTER TABLE empl6ADD(department_name VARCHAR2(25));UPDATE empl6 eSETdepartment_name =

Page 54: Oracle Notes

(SELECT department_nameFROMdepartments dWHERE e.department_id = d.department_id);

Correlated DELETEUse a correlated subquery to delete rows in one tablebased on rows from another table.DELETE FROM table1 alias1WHERE column operator(SELECT expressionFROMtable2 alias2WHERE alias1.column = alias2.column);

Use a correlated subquery to delete only those rowsfrom the EMPL6 table that also exist in theEMP_HISTORY table.DELETE FROM empl6 EWHERE employee_id =(SELECT employee_idFROMemp_historyWHERE employee_id = E.employee_id);

The WITH Clause•Using the WITH clause, you can use the samequery block in a SELECT statement when it occursmore than once within a complex query.•The WITH clause retrieves the results of a queryblock and stores it in the user’s temporarytablespace.•The WITH clause improves performance.

Using the WITH clause, write a query to display thedepartment name and total salaries for thosedepartments whose total salary is greater than the

Page 55: Oracle Notes

average salary across departments.

WITHdept_costs AS (SELECT d.department_name, SUM(e.salary) AS dept_totalFROMemployees e JOIN departments dONe.department_id = d.department_idGROUP BY d.department_name),avg_costAS (SELECT SUM(dept_total)/COUNT(*) AS dept_avgFROMdept_costs)SELECT *FROMdept_costsWHERE dept_total >(SELECT dept_avgFROM avg_cost)ORDER BY department_name;

USER MANAGEMENT-----------------------------Database: is a collection of logical storge units called as Tablespaces.

USERS (default)EXAMPLE

SYSTEMSYSAUXTEMP (default)UNDO

A Tablespace is of 3 types:1. PERMANENT: stores data permanently

Page 56: Oracle Notes

2. TEMPORARY: stored data temporarily3. UNDO: stores uncommitted data

To create a new user:

CREATE USER <username> IDENTIFIED BY <password>;

SQL> CREATE USER peter  2  IDENTIFIED BY oracle;

PRivilege: is a right given to a user to perform various database activities on objectsbelonging to him or other users.

Types:1. SYSTEM PRIVILEGEmeans giving a privilege to a user to perform database operation his objects.

2. OBJECT PRIVILEGEallowing one user to access and manipulate the objects belonging to anotheruser.

To give a privilege to a user:GRANT <privname> TO <username>;

SQL> CREATE USER peter  2  IDENTIFIED BY oracle;

User created.

SQL> conn peter/oracleERROR:ORA-01045: user PETER lacks CREATE SESSION privilege; logon denied

Warning: You are no longer connected to ORACLE.SQL> conn sys/manager as sysdbaConnected.

Page 57: Oracle Notes

SQL> GRANT create session TO peter;

Grant succeeded.

SQL> conn peter/oracleConnected.SQL> create table emp  2  (  3  empcode number  4  );create table emp*ERROR at line 1:ORA-01031: insufficient privileges

SQL> conn sys/manager as sysdbaConnected.SQL> GRANT create table, create view, create sequence, create synonym TO peter;

Grant succeeded.

SQL> conn peter/oracleConnected.SQL> create table emp  2  (  3  empcode number  4  );

Table created.

SQL> insert into emp values(1000);insert into emp values(1000)            *ERROR at line 1:ORA-01950: no privileges on tablespace 'USERS'

SQL> conn sys/manager as sysdbaConnected.SQL> ALTER USER peter

Page 58: Oracle Notes

  2  QUOTA UNLIMITED ON users;

User altered.

SQL> ALTER USER peter  2  QUOTA 2M ON users;

User altered.

SQL> conn sys/manager as sysdbaConnected.SQL> ALTER USER peter  2  QUOTA 100K ON users;     

To remove a privilege from the userSQL> REVOKE create table FROM peter;

ROLES : a role is a group of privileges that can be granted to/revoked from the user.

To create a role:CREATE ROLE <rolename>;

To drop a role:

DROP ROLE <rolename>;

Object Privileges-------------------------

Syntax:

GRANT <privname> ON <objname>TO <username>;

SQL> GRANT SELECT, INSERT  2  ON HR.jobs  3  TO peter;

Page 59: Oracle Notes

SQL> INSERT INTO hr.jobs VALUES('DBA','Database Administrator',6000,12000);

To revoke an object privilege:SQL> REVOKE select  2  ON hr.jobs  3  FROM peter;

SQL> CREATE USER jerry  2  IDENTIFIED BY oracle  3  DEFAULT TABLESPACE example  4  QUOTA UNLIMITED ON example;

User created.

To create a new tablespace:SQL> CREATE TABLESPACE PurchaseTbs   2  DATAFILE '/u01/app/oracle/oradata/orcl/purchasetbs01.dbf'  3  SIZE 100M;

Tablespace created.

SQL> ALTER TABLESPACE PurchaseTbs  2  ADD DATAFILE '/u01/app/oracle/oradata/orcl/purchase02.dbf'  3  SIZE 10M;

Tablespace altered.

SQL> create user ally  2  identified by oracle   3  default tablespace purchasetbs  4  quota 40M ON purchasetbs;create user ally            *ERROR at line 1:ORA-01920: user name 'ALLY' conflicts with another user or role name

SQL> l1  1* create user ally

Page 60: Oracle Notes

SQL> c /ally/mohd/  1* create user mohdSQL> /

To delete only the logical structrue from the database:SQL> DROP TABLESPACE purchasetbs INCLUDING CONTENTS;

To delete the logical as well as the physical structure:SQL> drop tablespace admin including contents and datafiles;

Sub Query------------------IN or ANY can be used if the inner query returns more than one row of value.

There are 3 types of ANY1. <ANY means less than the maximum2. >ANY means more than the minimum3. =ANY is same as IN operator

Example: Write a query to show employee id, last name, job id, and salary of allemployees whose salary is less than the salary of all employees with a job id of IT_PROG.

SQL> SELECT employee_id, last_name, job_id, salary  2  FROM employees  3  WHERE salary <ANY  4  (  5  SELECT salary  6  FROM employees  7  WHERE job_id='IT_PROG'  8  );

Equi Join and Non-Equi Join----------------------------------------SELECT emp.employee_id, emp.last_name, dep.department_nameFROM employees emp JOIN departments depON emp.department_id = dep.department_id;

Non-Equi join: here the common columns of two tables are joined using non-equality

Page 61: Oracle Notes

comparison operator such as <, >, BETWEEN, etc.

Display employee id, last name and grade of an employees for only those employeeswhose salary is within the min and max salary of their grade.

SQL> SELECT emp.employee_id, emp.last_name, emp.salary,grd.gradeid      2  FROM employees emp JOIN grades grd  3  ON emp.salary BETWEEN grd.minsal AND grd.maxsal;

SET OPERATORSused to combine the result of two or more tables and display as a singleresultset.

SELECT col4, col2, col3 FROM table1<SET OPERATOR TYPE>SELECT col4, col2, col3FROM table2

Guidelines to be followed to use SET operators1. The no of columns of both joined tables should match.2. The order of columns in the first query should match with the second query3. The names of the supplied columns can differ

Types:

1. UNION : returns rows from both the queries after eliminating the duplications.SQL> select * from testa;

     X Y---------- ----------------------------------------     1 A     2 B     3 C

SQL> select * from testb;

     A B         C---------- --------- ----------------------------------------     1 09-SEP-15 A     2 09-SEP-15 B     5 09-SEP-15 F

Page 62: Oracle Notes

     6 09-SEP-15 H

SQL> SELECT x,y FROM testa  2  UNION  3  SELECT a,c FROM testb;

     X Y---------- ----------------------------------------     1 A     2 B     3 C     5 F     6 H

SQL> ^C

SQL> SELECT x,y FROM testa  2  UNION ALL  3  SELECT a,c FROM testb;

     X Y---------- ----------------------------------------     1 A     2 B     3 C     1 A     2 B     5 F     6 H

7 rows selected.

b) INTERSECT  shows only common rows of two tables removing the distinct rowsSQL> SQL> SELECT x,y FROM testa  2  INTERSECT  3  SELECT a,c FROM testb;

     X Y---------- ----------------------------------------

Page 63: Oracle Notes

     1 A     2 B

c) MINUS: it displays all the rows of first query that are not available in the second query.

SQL> select * from testa;

     X Y---------- ----------------------------------------     1 A     2 B     3 C

SQL> select * from testb;

     A B         C---------- --------- ----------------------------------------     1 09-SEP-15 A     2 09-SEP-15 B     5 09-SEP-15 F     6 09-SEP-15 H

SQL> SELECT a,c FROM testb  2  MINUS  3  SELECT x,y FROM testa;

     A C---------- ----------------------------------------     5 F     6 H

Database Objects------------------------1. Table2. View3. Sequence4. Synonym5. Index

Page 64: Oracle Notes

Table: is used to store data permanently in rows and column format. Syntax:

CREATE TABLE <tablename>(        <colname> <datatype>(size),    <colname> datatype>(size));Rules to follow while naming a database object:1. Must begin with a letter2. Be 1 to 30 characters long3. Can contain A-Z, a-z, 0-9, _, $ and #4. The object name cannot be duplicated5. It cannot be a reserved word

CREATE TABLE employee(    empCode CHAR(5),    empName VARCHAR(40),    joinDate  DATE,    salary NUMBER(8,2));

To insert a new row:

INSERT INTO employee VALUES('EMP001','PETER',sysdate,4500);

OR

INSERT INTO employee (salary,empName, empCode, joinDate)VALUES(3000,'Peter','EMP02',sysdate);

To ignore the columns

INSERT INTO employee (empCode, empName) VALUES ('EMP03','John');When a column is ignored,oracle will place a NULL to the ignored column.

You can also ignore a column by explicitly providing the null keyword.

INSERT INTO employee VALUES(null,null,null,null);

Page 65: Oracle Notes

Data Manipulation LanguageINSERT DELETEUPDATE

DELETE command: used to remove one or more rows from a table.

Syntax:DELETE FROM <tablename>[WHERE <condition>];

DELETE FROM employeeWHERE empCode='EMP01';

UPDATE command: used to modify one or more column value.

UPDATE <tablename>SET <colname>=<new val>[WHERE <cond>];

UPDATE employeeSET salary=salary+100WHERE empCode='EMP01';

Constraint:is a rule applied on a column to restrint users from entering invalid data.

Types:1. NOT NULL2. CHECK3. UNIQUE4. DEFAULT property5. PRIMARY KEY6. FOREIGN KEY

NOT NULL: used to make a column require and cannot be ignored.

CREATE TABLE employee1(

Page 66: Oracle Notes

empCode CHAR(10) NOT NULL,empName VARCHAR(50) NOT NULL,joinDate DATE,salary number(8,2));

SQL> desc employee1 Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPCODE                   NOT NULL CHAR(10) EMPNAME                   NOT NULL VARCHAR2(50) JOINDATE                        DATE SALARY                         NUMBER(8,2)

SQL> insert into employee1 (empCode, joindate, salary)  2  values('EMP001',sysdate,3000);insert into employee1 (empCode, joindate, salary)*ERROR at line 1:ORA-01400: cannot insert NULL into ("HR"."EMPLOYEE1"."EMPNAME")

Note: Any no of columns in a table can have NOT NULL constraint.

2. CHECKis used to allow users to enter only specific values as per the given condition.

CREATE TABLE employee2(empCode CHAR(10) NOT NULL,empName VARCHAR(40) NOT NULL,gender CHAR(1) NOT NULL  CHECK(gender IN('M','F')),joinDate DATE,salary NUMBER(8,2));

3. UNIQUE: restrict the user from entering duplicate values in a column,

CREATE TABLE employee3(empCode CHAR(10) NOT NULL UNIQUE,

Page 67: Oracle Notes

empName VARCHAR(40) NOT NULL,gender CHAR(1) CHECK(gender IN('M','F')),salary NUMBER (8,2) CHECK (salary BETWEEN 500 and 25000),joindate DATE,Email VARCHAR(25) UNIQUE);

SQL> INSERT INTO employee3 VALUES('&empcode','&empName','&gender',&basic,'&hiredate','&email');

4. DEFAULT propertyBy default when a column is ignored, oracle will place a null value to that column.The default property is used to insert some other value other than null when it isignored. It can be applied only to nullable columns.

SQL> CREATE TABLE employee4   2  (  3  empCode CHAR(10) NOT NULL UNIQUE,  4  empName VARCHAR(40) NOT NULL,  5  joindate DATE DEFAULT sysdate,  6  gender CHAR(1) DEFAULT 'M' CHECK (gender IN('M','F'))  7  );

SQL> insert into employee4 (empCode, empName) VALUES ('EMP002','Peter');

1 row created.

SQL> select * from employee4;

EMPCODE    EMPNAME                    JOINDATE  G---------- ---------------------------------------- --------- -EMP001       Mike                     10-JAN-15 MEMP002       Peter                    09-SEP-15 M

4. PRIMARY KEYA table can have only 1 primary key column. it is used to uniquely identofy tworows in a table. When a column  is set as PRIMARY KEY, it also gets NOT NULL and UNIQUE constraints.

Page 68: Oracle Notes

CREATE TABLE employee5( empCode CHAR(10) PRIMARY KEY,empName VARCHAR(40) NOT NULL,gender CHAR(1) default 'M' CHECK(gender IN('M','F')));

5. FOREIGN KEYis the primary key column of some other table.

Dept------DeptId     DeptName1        Admin2        Marketing

Emp-------EmpId DeptCode EmpName Salary1001   1                Peter          50001002   1                Mary          45001003   1                George          23001004   1                Peter          3400

SQL> CREATE TABLE tasafdept  2  (  3  deptcode NUMBER PRIMARY KEY,  4  deptname VARCHAR(40) NOT NULL UNIQUE  5  );

Table created.

SQL> CREATE TABLE tasafemp  2  (  3  empcode CHAR(15) PRIMARY KEY,  4  deptid NUMBER REFERENCES tasafdept(deptcode),  5  empname VARCHAR(50)  6  );

Table created.

Page 69: Oracle Notes

SQL> insert into tasafdept values(&dcode,'&dname')  2  ;Enter value for dcode: 10  Enter value for dname: Adminold   1: insert into tasafdept values(&dcode,'&dname')new   1: insert into tasafdept values(10,'Admin')

1 row created.

SQL> /Enter value for dcode: 20Enter value for dname: Marketingold   1: insert into tasafdept values(&dcode,'&dname')new   1: insert into tasafdept values(20,'Marketing')

1 row created.

SQL> insert into tasafemp VALUES('&ecode',&dcode,'&ename');Enter value for ecode: EMP001Enter value for dcode: 10Enter value for ename: Mikeold   1: insert into tasafemp VALUES('&ecode',&dcode,'&ename')new   1: insert into tasafemp VALUES('EMP001',10,'Mike')

1 row created.

SQL> /Enter value for ecode: EMP002Enter value for dcode: 10Enter value for ename: Peterold   1: insert into tasafemp VALUES('&ecode',&dcode,'&ename')new   1: insert into tasafemp VALUES('EMP002',10,'Peter')

1 row created.

SQL> /Enter value for ecode: EMP003Enter value for dcode: 20Enter value for ename: Allyold   1: insert into tasafemp VALUES('&ecode',&dcode,'&ename')new   1: insert into tasafemp VALUES('EMP003',20,'Ally')

Page 70: Oracle Notes

1 row created.

SQL> SELECT * FROM tasafdept;

  DEPTCODE DEPTNAME---------- ----------------------------------------    10 Admin    20 Marketing

SQL> select * from tasafemp;

EMPCODE         DEPTID EMPNAME--------------- ---------- --------------------------------------------------EMP001            10 MikeEMP002            10 PeterEMP003            20 Ally

SQL> insert into tasafemp values('EMP004',40,'John');insert into tasafemp values('EMP004',40,'John')*ERROR at line 1:ORA-02291: integrity constraint (HR.SYS_C0011137) violated - parent key notfound

After the table creation----------------------------------------You need to use ALTER command to modify the table sructureUsing the ALTER command you can:1. Add a new columnSyntax:

ALTER TABLE <tablename> ADD (<colname> <datatype>); SQL> ALTER TABLE employee  2  ADD(gender CHAR(1));

ORacle will insert NULL to the existing rows of the new column.Note: You cannot add a new column with NOT NULL constraint if the table has any row.

Page 71: Oracle Notes

2. delete an existing columnALTER TABLE <tablename>DROP COLUMN <colname>;

SQL> ALTER TABLE employee  2  DROP COLUMN gender;

3. add a new constraint

ALTER TABLE <tablename>ADD CONSTRAINT <consname> <constype> (<conscol>);

To make a col unique------------------------------SQL> ALTER TABLE employee   2  ADD CONSTRAINT UNQ_EMPLOYEE_EMAIL UNIQUE(email);Note: ensure that the column do not have any duplicate values before adding a UNIQUE constraint.

CHECKSQL> ALTER TABLE employee  2  ADD CONSTRAINT CHK_EMPLOYEE_SALARY CHECK(salary BETWEEN 500 and 25000);

Note: Ensure that the values in the column satisfied the criteria defined in the CHECK constraint

PRIMARY KEYSQL> ALTER TABLE employee  2  ADD CONSTRAINT PK_EMPLOYEE_EMPCODE PRIMARY KEY(empcode);

Note: ensure that the column to be made primary do not have any duplicate/null values.

FOREIGN KEYSQL> ALTER TABLE employee  2  ADD CONSTRAINT FK_EMPLOYEE_DEPT FOREIGN KEY(DEPT) REFERENCES tasafdept(deptcode);

Note: Ensure that the column to be made foreign donot have any invalid value.

Page 72: Oracle Notes

A foreign key column can be ignored.

4. delete an existing constraint

ALTER TABLE <tablename>DROP CONSTRAINT <consname>;

SQL> ALTER TABLE employee  2  DROP CONSTRAINT CHK_EMPLOYEE_SALARY;

Table altered.

To enable/disable constraints:

SQL> ALTER TABLE employee  2  ENABLE CONSTRAINT FK_EMPLOYEE_DEPT;

SQL> ALTER TABLE employee  2  ENABLE CONSTRAINT FK_EMPLOYEE_DEPT;

SQL> SELECT constraint_name, constraint_type, status  2  FROM user_constraints  3  WHERE table_name='EMPLOYEE';

CONSTRAINT_NAME            C STATUS------------------------------ - --------UNQ_EMPLOYEE_EMAIL           U ENABLEDPK_EMPLOYEE_EMPCODE           P ENABLEDFK_EMPLOYEE_DEPT           R ENABLED

SQL> ALTER TABLE employee DISABLE CONSTRAINT UNQ_EMPLOYEE_EMAIL;

Table altered.

SQL> SELECT constraint_name, constraint_type, status  2  FROM user_constraints  3  WHERE table_name='EMPLOYEE';

CONSTRAINT_NAME            C STATUS------------------------------ - --------

Page 73: Oracle Notes

UNQ_EMPLOYEE_EMAIL           U DISABLEDPK_EMPLOYEE_EMPCODE           P ENABLEDFK_EMPLOYEE_DEPT           R ENABLED

SET UNUSED commandALTER TABLE <table_name>SET UNUSED(<column_name>);

is used to mark the column for deletion.SQL> ALTER TABLE employee  2  SET UNUSED (email);

To drop all unused columns from the given table:SQL> ALTER TABLE employee  2  DROP UNUSED COLUMNS;

ALTER TABLE <table_name>DROP UNUSED COLUMNS;

ON DELETE CASCADE------------------------------Will delete all the referencing rows from the child tables when you attempt to deletethe parent table rows.

ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fkFOREIGN KEY (Department_id)REFERENCES departments ON DELETE CASCADE);

Deferring ConstraintsConstraints can have the following attributes:• DEFERRABLE or NOT DEFERRABLE• INITIALLY DEFERRED or INITIALLY IMMEDIATE

ALTER TABLE dept2ADD CONSTRAINT dept2_id_pkPRIMARY KEY (department_id)DEFERRABLE INITIALLY DEFERRED

Page 74: Oracle Notes

SQL> ALTER TABLE testemp1  2  ADD CONSTRAINT PK_TESTEMP1_ECODE PRIMARY KEY(ecode) DEFERRABLE INITIALLY DEFERRED;

To change the behaviour of a deferrable constraint:

SET CONSTRAINT <consname> IMMEDIATE|DEFERRED;

SQL> SET CONSTRAINT PK_TESTEMP1_ECODE IMMEDIATE;

Cascading Constraints• The CASCADE CONSTRAINTS clause is used alongwith the DROP COLUMN clause.• The CASCADE CONSTRAINTS clause drops allreferential integrity constraints that refer to theprimary and unique keys defined on the droppedcolumns.• The CASCADE CONSTRAINTS clause also drops allmulticolumn constraints defined on the droppedcolumns.

ALTER TABLE emp2DROP COLUMN employee_id CASCADE CONSTRAINTS;

The above command will drop the primary key column and also all the foreign keyconstraints referencing this column.

Table altered.ALTER TABLE test1DROP (pk, fk, col1) CASCADE CONSTRAINTS;

5. modify an existing column, type, size, or constraintALTER TABLE <tablename>MODIFY (<colname> <newdatatype>(<newsize>);

SQL> ALTER TABLE tasafemp  2  MODIFY(empname VARCHAR(55));

Page 75: Oracle Notes

To Drop a table:DROP TABLE <tablename>;

VIEWS----------helps to restrict users from viewing sensitive information of a table. A view do not havedata of its own.

Syntax:CREATE VIEW <viewname>AS <select statement>;

Types:1. Simple ViewIs one where only 1 table is used as the base table.

SQL> CREATE VIEW myv1   2  AS SELECT employee_id, department_id, last_name, salary  3  FROM employees;

You can perform all DML operation on the table though the view if it is a simple view.

2. Complex View

is one that uses joins, sub query, group functionsSQL> CREATE VIEW myv3  2  AS SELECT emploeye_id, last_name, salary, department_id  3  FROM employees  4  WHERE department_id IN  5  (  6  SELECT department_id  7  FROM departments  8  WHERE location_id=  9  ( 10  SELECT location_id 11  FROM locations 12  WHERE city='Seattle' 13  ));

SQL> CREATE VIEW myv4

Page 76: Oracle Notes

  2  AS SELECT department_id, count(employee_id) AS total_emp  3  FROM employees  4  GROUP BY department_id  5  ORDER BY department_id;

To Drop a view DROP VIEW <viewname>;

3. SEQUENCEused to generate numbers.

Syntax:CREATE SEQUENCE <seqname>;

SQL> CREATE SEQUENCE myseq1;

SQL> SELECT myseq1.NEXTVAL from dual;

SQL> SELECT myseq1.CURRVAL FROM dual;

SQL> CREATE SEQUENCE myseq2  2  START WITH 1000;

SQL> CREATE SEQUENCE myseq3  2  START WITH 1000  3  INCREMENT BY 2;

SQL> CREATE SEQUENCE myseq5  2  MAXVALUE 20  3  CYCLE NOCACHE;

SYNONYM-----------------they are used another name to a database object.SQL> CREATE SYNONYM mike FOR employees;

INDEX--------

Page 77: Oracle Notes

are used to retreive data faster.

To create an index :

CREATE INDEX <indname> ON <tablename>(colname);

Apply index on a column only if:1. If the table is very large/2. if the column holds large no of unique values.

Function based index:

SQL> CREATE INDEX indempname1  2  ON tasafemp(upper(empname));

To DROP an indexDROP INDEX <indname>;

What happend when a table is dropped.

FLASHBACK TABLE testemp1 TO BEFORE DROP;

To drop table permanently:SQL> DROP TABLE testemp1 PURGE;

External TablesCreating a Directory for the External TableCreate a DIRECTORY object that corresponds to thedirectory on the file system where the external datasource resides.CREATE OR REPLACE DIRECTORY emp_dirAS '/.../emp_dir';

GRANT READ ON DIRECTORY emp_dir TO hr;

Page 78: Oracle Notes

CREATE TABLE oldemp (fname char(25), lname CHAR(25))ORGANIZATION EXTERNAL(TYPE ORACLE_LOADERDEFAULT DIRECTORY emp_dirACCESS PARAMETERS(RECORDS DELIMITED BY NEWLINENOBADFILENOLOGFILEFIELDS TERMINATED BY ','(fname POSITION ( 1:20) CHAR,lname POSITION (22:41) CHAR))LOCATION ('emp.dat'))PARALLEL 5REJECT LIMIT 200;

Command to drop the table from the recyclebinSQL> PURGE TABLE "BIN$H1KFWZPqSUngUKjAQQIc4Q==$0";

TRUNCATE: this command deletes all the rows from a table and cannot be rolled back.

SQL> TRUNCATE TABLE testb;

CREATING A TABLE BY using another tabe:

SQL> INSERT INTO mydept (employee_id, last_name, department_id, salary)  2  SELECT employee_id, last_name, department_id, salary  3  FROM employees  4  WHERE salary BETWEEN 5000 AND 7000;

14 rows created.

SQL> CREATE TABLE mydept2  2  AS SELECT * FROM employees;

Table created.

SQL> TRUNCATE TABLE mydept2;

Page 79: Oracle Notes

Table truncated.

SQL> INSERT INTO mydept2  2  SELECT * FROM employees;

108 rows created.

Multiple INSERT Statement:

Types of Multitable INSERT StatementsThe different types of multitable INSERT statementsare:• Unconditional INSERT• Conditional ALL INSERT• Conditional FIRST INSERT• Pivoting INSERT

Unconditional INSERT ALL•Select the EMPLOYEE_ID, HIRE_DATE, SALARY, andMANAGER_ID values from the EMPLOYEES table forthose employees whose EMPLOYEE_ID is greaterthan 200.• Insert these values into the SAL_HISTORY andMGR_HISTORY tables using a multitable INSERT.

INSERT ALLINTO sal_history VALUES(EMPID,HIREDATE,SAL)INTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID, hire_date HIREDATE,salary SAL, manager_id MGRFROM employeesWHERE employee_id > 200;

Conditional INSERT ALL• Select the EMPLOYEE_ID, HIRE_DATE, SALARY, andMANAGER_ID values from the EMPLOYEES table forthose employees whose EMPLOYEE_ID is greaterthan 200.

Page 80: Oracle Notes

• If the SALARY is greater than $10,000, insert thesevalues into the SAL_HISTORY table using aconditional multitable INSERT statement.• If the MANAGER_ID is greater than 200, insert thesevalues into the MGR_HISTORY table using aconditional multitable INSERT statement.

SQL> CREATE TABLE MGR  2  AS SELECT employee_id, last_name, manager_id, salary  3  FROM employees;

Table created.

SQL> truncate table mgr;

Table truncated.

SQL> CREATE TABLE SAL  2  AS SELECT employee_id, department_id, salary, commission_pct  3  FROM employees;

Table created.

SQL> truncate table sal;

Table truncated.

SQL> desc mgr Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPLOYEE_ID                        NUMBER(6) LAST_NAME                   NOT NULL VARCHAR2(25) MANAGER_ID                        NUMBER(6) SALARY                         NUMBER(8,2)

SQL> desc sal Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPLOYEE_ID                        NUMBER(6) DEPARTMENT_ID                        NUMBER(4) SALARY                         NUMBER(8,2)

Page 81: Oracle Notes

 COMMISSION_PCT                     NUMBER(2,2)

SQL> select from mgr;select from mgr       *ERROR at line 1:ORA-00936: missing expression

SQL> select * from mgr;

no rows selected

SQL> select * from sal;

no rows selected

SQL> SQL> SQL> INSERT ALL  2  INTO mgr VALUES(employee_id, last_name, manager_id, salary)  3  INTO sal VALUES(employee_id, department_id, salary, commission_pct)  4  SELECT employee_id, last_name, manager_id, salary,department_id, commission_pct  5  FROM employees  6  WHERE hire_date>'31-DEC-08';

2 rows created.

SQL> select * from mgr;

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    222 John

SQL> select * from sal;

EMPLOYEE_ID DEPARTMENT_ID     SALARY COMMISSION_PCT----------- ------------- ---------- --------------    222

SQL> CREATE TABLE jobdet

Page 82: Oracle Notes

  2  AS SELECT employee_id, department_id, job_id, hire_date  3  FROM employees;

Table created.

SQL> truncate table jobdet;

Table truncated.

SQL> truncate table sal;

Table truncated.

SQL> truncate table mgr;

Table truncated.

SQL> desc sal Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPLOYEE_ID                        NUMBER(6) DEPARTMENT_ID                        NUMBER(4) SALARY                         NUMBER(8,2) COMMISSION_PCT                     NUMBER(2,2)

SQL> desc mgr Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPLOYEE_ID                        NUMBER(6) LAST_NAME                   NOT NULL VARCHAR2(25) MANAGER_ID                        NUMBER(6) SALARY                         NUMBER(8,2)

SQL> desc jobdet Name                       Null?    Type ----------------------------------------- -------- ---------------------------- EMPLOYEE_ID                        NUMBER(6) DEPARTMENT_ID                        NUMBER(4) JOB_ID                    NOT NULL VARCHAR2(10) HIRE_DATE                   NOT NULL DATE

Page 83: Oracle Notes

SQL> INSERT ALL  2  WHEN salary > 14000 THEN  3  INTO sal VALUES(employee_id, department_id, salary, commission_pct)  4  WHEN manager_id BETWEEN 100 AND 150 THEN  5  INTO mgr VALUES(employee_id, last_name,manager_id, salary)  6  WHEN hire_Date BETWEEN '1-JAN-05' AND '31-DEC-06' THEN  7  INTO jobdet VALUES(employee_id, department_id, job_id, hire_date)  8  SELECT employee_id, department_id, salary, commission_pct, last_name, manager_id,  9  job_id, hire_date 10  FROM employees;

160 rows created.

SQL> INSERT FIRST  2  WHEN salary > 14000 THEN  3  INTO sal VALUES(employee_id, department_id, salary, commission_pct)  4  WHEN manager_id BETWEEN 100 AND 150 THEN  5  INTO mgr VALUES(employee_id, last_name,manager_id, salary)  6  WHEN hire_Date BETWEEN '1-JAN-05' AND '31-DEC-06' THEN  7  INTO jobdet VALUES(employee_id, department_id, job_id, hire_date)  8  SELECT employee_id, department_id, salary, commission_pct, last_name, manager_id,  9  job_id, hire_date 10  FROM employees;

SQL> SELECT * from sal;

EMPLOYEE_ID DEPARTMENT_ID     SALARY COMMISSION_PCT----------- ------------- ---------- --------------    100           90      24100    101           90      17000    102           90      17000

SQL> SELECT * FROM mgr;

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    198 OConnell                 124       2600    199 Grant                 124       2600    200 Whalen                 101       4400    201 Hartstein                 100      13000

Page 84: Oracle Notes

    203 Mavris                 101       6500    204 Baer                 101      10000    205 Higgins                 101      12008    101 Kochhar                 100      17000    102 De Haan                 100      17000    103 Hunold                 102       9000    104 Ernst                 103       6000

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    105 Austin                 103       4800    106 Pataballa                 103       4800    107 Lorentz                 103       4200    108 Greenberg                 101      12008    109 Faviet                 108       9000    110 Chen                 108       8200    111 Sciarra                 108       7700    112 Urman                 108       7800    113 Popp                 108       6900    114 Raphaely                 100      11000    115 Khoo                 114       3100

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    116 Baida                 114       2900    117 Tobias                 114       2800    118 Himuro                 114       2600    119 Colmenares                 114       2500    120 Weiss                 100       8000    121 Fripp                 100       8200    122 Kaufling                 100       7900    123 Vollman                 100       6500    124 Mourgos                 100       5800    125 Nayer                 120       3200    126 Mikkilineni              120       2700

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    127 Landry                 120       2400    128 Markle                 120       2200    129 Bissot                 121       3300

Page 85: Oracle Notes

    130 Atkinson                 121       2800    131 Marlow                 121       2500    132 Olson                 121       2100    133 Mallin                 122       3300    134 Rogers                 122       2900    135 Gee                  122       2400    136 Philtanker                 122       2200    137 Ladwig                 123       3600

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    138 Stiles                 123       3200    139 Seo                  123       2700    140 Patel                 123       2500    141 Rajs                 124       3500    142 Davies                 124       3100    143 Matos                 124       2600    144 Vargas                 124       2500    145 Russell                 100      14000    146 Partners                 100      13500    147 Errazuriz                 100      12000    148 Cambrault                 100      11000

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    149 Zlotkey                 100      10500    150 Tucker                 145      10000    151 Bernstein                 145       9500    152 Hall                 145       9000    153 Olsen                 145       8000    154 Cambrault                 145       7500    155 Tuvault                 145       7000    156 King                 146      10000    157 Sully                 146       9500    158 McEwen                 146       9000    159 Smith                 146       8000

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    160 Doran                 146       7500    161 Sewall                 146       7000

Page 86: Oracle Notes

    162 Vishney                 147      10500    163 Greene                 147       9500    164 Marvins                 147       7200    165 Lee                  147       6800    166 Ande                 147       6400    167 Banda                 147       6200    168 Ozer                 148      11500    169 Bloom                 148      10000    170 Fox                  148       9600

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    171 Smith                 148       7400    172 Bates                 148       7300    173 Kumar                 148       6100    174 Abel                 149      11000    175 Hutton                 149       8800    176 Taylor                 149       8600    177 Livingston                 149       8400    178 Grant                 149       7000    179 Johnson                 149       6200    180 Taylor                 120       3200    181 Fleaur                 120       3100

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    182 Sullivan                 120       2500    183 Geoni                 120       2800    184 Sarchand                 121       4200    185 Bull                 121       4100    186 Dellinger                 121       3400    187 Cabrio                 121       3000    188 Chung                 122       3800    189 Dilly                 122       3600    190 Gates                 122       2900    191 Perkins                 122       2500    192 Bell                 123       4000

EMPLOYEE_ID LAST_NAME              MANAGER_ID     SALARY----------- ------------------------- ---------- ----------    193 Everett                 123       3900

Page 87: Oracle Notes

    194 McCain                 123       3200    195 Jones                 123       2800    196 Walsh                 124       3100    197 Feeney                 124       3000

104 rows selected.

SQL> select * from jobdet;

EMPLOYEE_ID DEPARTMENT_ID JOB_ID     HIRE_DATE----------- ------------- ---------- ---------    202           20 MK_REP     17-AUG-05    101           90 AD_VP      21-SEP-05    103           60 IT_PROG    03-JAN-06    105           60 IT_PROG    25-JUN-05    106           60 IT_PROG    05-FEB-06    110          100 FI_ACCOUNT 28-SEP-05    111          100 FI_ACCOUNT 30-SEP-05    112          100 FI_ACCOUNT 07-MAR-06    116           30 PU_CLERK   24-DEC-05    117           30 PU_CLERK   24-JUL-05    118           30 PU_CLERK   15-NOV-06

EMPLOYEE_ID DEPARTMENT_ID JOB_ID     HIRE_DATE----------- ------------- ---------- ---------    121           50 ST_MAN     10-APR-05    123           50 ST_MAN     10-OCT-05    125           50 ST_CLERK   16-JUL-05    126           50 ST_CLERK   28-SEP-06    129           50 ST_CLERK   20-AUG-05    130           50 ST_CLERK   30-OCT-05    131           50 ST_CLERK   16-FEB-05    134           50 ST_CLERK   26-AUG-06    138           50 ST_CLERK   26-OCT-05    139           50 ST_CLERK   12-FEB-06    140           50 ST_CLERK   06-APR-06

EMPLOYEE_ID DEPARTMENT_ID JOB_ID     HIRE_DATE----------- ------------- ---------- ---------    142           50 ST_CLERK   29-JAN-05    143           50 ST_CLERK   15-MAR-06

Page 88: Oracle Notes

    144           50 ST_CLERK   09-JUL-06    146           80 SA_MAN     05-JAN-05    147           80 SA_MAN     10-MAR-05    150           80 SA_REP     30-JAN-05    151           80 SA_REP     24-MAR-05    152           80 SA_REP     20-AUG-05    153           80 SA_REP     30-MAR-06    154           80 SA_REP     09-DEC-06    159           80 SA_REP     10-MAR-05

EMPLOYEE_ID DEPARTMENT_ID JOB_ID     HIRE_DATE----------- ------------- ---------- ---------    160           80 SA_REP     15-DEC-05    161           80 SA_REP     03-NOV-06    162           80 SA_REP     11-NOV-05    168           80 SA_REP     11-MAR-05    169           80 SA_REP     23-MAR-06    170           80 SA_REP     24-JAN-06    175           80 SA_REP     19-MAR-05    176           80 SA_REP     24-MAR-06    177           80 SA_REP     23-APR-06    180           50 SH_CLERK   24-JAN-06    181           50 SH_CLERK   23-FEB-06

EMPLOYEE_ID DEPARTMENT_ID JOB_ID     HIRE_DATE----------- ------------- ---------- ---------    185           50 SH_CLERK   20-FEB-05    186           50 SH_CLERK   24-JUN-06    188           50 SH_CLERK   14-JUN-05    189           50 SH_CLERK   13-AUG-05    190           50 SH_CLERK   11-JUL-06    193           50 SH_CLERK   03-MAR-05    194           50 SH_CLERK   01-JUL-06    196           50 SH_CLERK   24-APR-06    197           50 SH_CLERK   23-MAY-06

53 rows selected.

SQL>

Page 89: Oracle Notes

Conditional INSERT ALLINSERT ALLWHEN SAL > 10000 THENINTO sal_history VALUES(EMPID,HIREDATE,SAL)WHEN MGR > 200THENINTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID,hire_date HIREDATE,salary SAL, manager_id MGRFROMemployeesWHERE employee_id > 200;

Conditional INSERT FIRST•Select the DEPARTMENT_ID, SUM(SALARY), andMAX(HIRE_DATE) from the EMPLOYEES table.•If the SUM(SALARY) is greater than $25,000, theninsert these values into the SPECIAL_SAL, using aconditional FIRST multitable INSERT.•If the first WHEN clause evaluates to true, then thesubsequent WHEN clauses for this row should beskipped.•For the rows that do not satisfy the first WHENcondition, insert into the HIREDATE_HISTORY_00,HIREDATE_HISTORY_99, or HIREDATE_HISTORYtables, based on the value in the HIRE_DATEcolumn using a conditional multitable INSERT.

Conditional INSERT FIRSTINSERT FIRSTWHEN SAL > 25000THENINTO special_sal VALUES(DEPTID, SAL)WHEN HIREDATE like ('%00%') THENINTO hiredate_history_00 VALUES(DEPTID,HIREDATE)WHEN HIREDATE like ('%99%') THENINTO hiredate_history_99 VALUES(DEPTID, HIREDATE)ELSE

Page 90: Oracle Notes

INTO hiredate_history VALUES(DEPTID, HIREDATE)SELECT department_id DEPTID, SUM(salary) SAL,MAX(hire_date) HIREDATEFROMemployeesGROUP BY department_id;

Pivoting INSERT• Suppose you receive a set of sales records from a   nonrelational database table,  SALES_SOURCE_DATA, in the following format: EMPLOYEE_ID, WEEK_ID, SALES_MON, SALES_TUE,SALES_WED, SALES_THUR, SALES_FRI• You want to store these records in the   SALES_INFO table in a more typical relational  format: EMPLOYEE_ID, WEEK, SALESUsing a pivoting INSERT, convert the set of salesrecords from the nonrelational database table torelational format.

Pivoting INSERTINSERT ALLINTO sales_info VALUES (employee_id,week_id,sales_MON)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_FRIFROM sales_source_data;

The MERGE Statement•Provides the ability to conditionally update orinsert data into a database table•Performs an UPDATE if the row exists, and an

Page 91: Oracle Notes

INSERT if it is a new row:

– Avoids separate updates– Increases performance and ease of use– Is useful in data warehousing applications

Merging RowsInsert or update rows in the EMPL3 table to match theEMPLOYEES table.

MERGE INTO empl3 cUSING employees eON (c.employee_id = e.employee_id)WHEN MATCHED THENUPDATE SETc.first_name= e.first_name,c.last_name= e.last_name,...c.department_id = e.department_idWHEN NOT MATCHED THENINSERT 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);

SQL> MERGE INTO empdup dup   2  USING employees emp  3  ON (dup.employee_id=emp.employee_id)  4  WHEN MATCHED THEN   5  UPDATE SET  6  dup.first_name=emp.first_name,  7  dup.last_name=emp.last_name,  8  dup.email=emp.email,  9  dup.phone_number=emp.phone_number, 10  dup.hire_date=emp.hire_date,

Page 92: Oracle Notes

 11  dup.job_id=emp.job_id, 12  dup.salary=emp.salary, 13  dup.commission_pct=emp.commission_pct, 14  dup.manager_id=emp.manager_id, 15  dup.department_id=emp.department_id 16  WHEN NOT MATCHED THEN 17  INSERT VALUES(emp.employee_id,emp.first_name, emp.last_name,emp.email,emp.phone_number, 18  emp.hire_date, emp.job_id, emp.salary, emp.commission_pct, emp.manager_id,               19  emp.department_id);

Merging RowsTRUNCATE TABLE empl3;SELECT *FROM empl3;no rows selectedMERGE INTO empl3 cUSING employees eON (c.employee_id = e.employee_id)WHEN MATCHED THENUPDATE SET...WHEN NOT MATCHED THENINSERT VALUES...;SELECT *FROM empl3;

Column comparisons in a multiple-column subquerycan be:• Pairwise comparisons• Nonpairwise comparisons

Pairwise Comparison Subquery

Display the details of the employees who are managedby the same manager and work in the samedepartment as the employees with EMPLOYEE_ID 199.

Page 93: Oracle Notes

SQL> SELECT employee_id, last_name, department_id, manager_id, first_name  2  FROM employees  3  WHERE manager_id IN  4  (  5  SELECT manager_id  6  FROM employees  7  WHERE upper(first_name)='JOHN'  8  )  9  AND department_id IN 10  ( 11  SELECT department_id 12  FROM employees 13  WHERE upper(first_name)='JOHN' 14  );

Example of Pair wise comparison:

SELECT employee_id, manager_id, department_idFROMemployeesWHERE (manager_id, department_id) IN(SELECT manager_id, department_idFROMemployeesWHERE employee_id IN (199,174))ANDemployee_id NOT IN (199,174);

Nonpairwise Comparison SubqueryDisplay the details of the employees who are managedby the same manager as the employees withEMPLOYEE_ID 174 or 199 and work in the samedepartment as the employees with EMPLOYEE_ID 174or 199.SELECT employee_id, manager_id, department_idFROM employeesWHERE manager_id IN

Page 94: Oracle Notes

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

Scalar Subquery Expressions•A scalar subquery expression is a subquery thatreturns exactly one column value from one row.•Scalar subqueries can be used in:– Condition and expression part of DECODE and CASE– All clauses of SELECT except GROUP BY

Scalar Subqueries: Examples•Scalar subqueries in CASE expressionsSELECT employee_id, last_name,(CASE20WHEN department_id =(SELECT department_idFROM departmentsWHERE location_id = 1800)THEN 'Canada' ELSE 'USA' END) locationFROMemployees;•Scalar subqueries in ORDER BY clauseSELECTemployee_id, last_nameFROMemployees eORDER BY (SELECT department_nameFROM departments dWHERE e.department_id = d.department_id);

Correlated SubqueriesCorrelated subqueries are used for row-by-rowprocessing. Each subquery is executed once for everyrow of the outer query.

Page 95: Oracle Notes

Correlated SubqueriesThe subquery references a column from a table in theparent query.SELECT column1, column2, ...outerFROMtable1WHERE column1 operator(SELECTFROMWHEREcolumn1, column2table2expr1 =outer.expr2);

Using Correlated SubqueriesFind all employees who earn more than the averagesalary in their department.SELECT last_name, salary, department_idFROMemployees outerWHERE salary >(SELECT AVG(salary)FROMemployeesWHERE department_id =outer.department_id);

Using Correlated SubqueriesDisplay details of those employees who have changedjobs at least twice.

SELECT e.employee_id, last_name,e.job_idFROMemployees eWHERE 2 <= (SELECT COUNT(*)FROMjob_history

Page 96: Oracle Notes

  WHERE employee_id = e.employee_id);

CO-RELATED UPDATE

SQL> UPDATE myemp outer  2  SET department_name=  3  (  4  SELECT department_name  5  FROM departments  6  WHERE department_id=outer.department_id  7  );

CO-RELATED DELETESQL> DELETE FROM myemp outer  2  WHERE employee_id IN   3  (  4  SELECT employee_id  5  FROM job_history  6  WHERE employee_id=outer.employee_id  7  );

Using the EXISTS Operator•The EXISTS operator tests for existence of rows inthe 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

Find Employees Who Have at Least OnePerson Reporting to ThemSELECT employee_id, last_name, job_id, department_idFROM employees outerWHERE EXISTS ( SELECT  'X'FROM

Page 97: Oracle Notes

employeesWHERE manager_id =outer.employee_id);

Find All Departments That Do Not HaveAny EmployeesSELECT department_id, department_nameFROM departments dWHERE NOT EXISTS (SELECT 'X'FROMemployeesWHERE department_id = d.department_id);

Correlated UPDATEUse a correlated subquery to update rows in one tablebased on rows from another table.

ALTER TABLE empl6ADD(department_name VARCHAR2(25));UPDATE empl6 eSETdepartment_name =(SELECT department_nameFROMdepartments dWHERE e.department_id = d.department_id);

Correlated DELETEUse a correlated subquery to delete rows in one tablebased on rows from another table.DELETE FROM table1 alias1WHERE column operator(SELECT expressionFROMtable2 alias2WHERE alias1.column = alias2.column);

Page 98: Oracle Notes

Use a correlated subquery to delete only those rowsfrom the EMPL6 table that also exist in theEMP_HISTORY table.DELETE FROM empl6 EWHERE employee_id =(SELECT employee_idFROMemp_historyWHERE employee_id = E.employee_id);

The WITH Clause•Using the WITH clause, you can use the samequery block in a SELECT statement when it occursmore than once within a complex query.•The WITH clause retrieves the results of a queryblock and stores it in the user’s temporarytablespace.•The WITH clause improves performance.

Using the WITH clause, write a query to display thedepartment name and total salaries for thosedepartments whose total salary is greater than theaverage salary across departments.

WITHdept_costs AS (SELECT d.department_name, SUM(e.salary) AS dept_totalFROMemployees e JOIN departments dONe.department_id = d.department_idGROUP BY d.department_name),avg_costAS (SELECT SUM(dept_total)/COUNT(*) AS dept_avgFROMdept_costs)

Page 99: Oracle Notes

SELECT *FROMdept_costsWHERE dept_total >(SELECT dept_avgFROM avg_cost)ORDER BY department_name;

USER MANAGEMENT-----------------------------Database: is a collection of logical storge units called as Tablespaces.

USERS (default)EXAMPLE

SYSTEMSYSAUXTEMP (default)UNDO

A Tablespace is of 3 types:1. PERMANENT: stores data permanently2. TEMPORARY: stored data temporarily3. UNDO: stores uncommitted data

To create a new user:

CREATE USER <username> IDENTIFIED BY <password>;

SQL> CREATE USER peter  2  IDENTIFIED BY oracle;

PRivilege: is a right given to a user to perform various database activities on objectsbelonging to him or other users.

Page 100: Oracle Notes

Types:1. SYSTEM PRIVILEGEmeans giving a privilege to a user to perform database operation his objects.

2. OBJECT PRIVILEGEallowing one user to access and manipulate the objects belonging to anotheruser.

To give a privilege to a user:GRANT <privname> TO <username>;

SQL> CREATE USER peter  2  IDENTIFIED BY oracle;

User created.

SQL> conn peter/oracleERROR:ORA-01045: user PETER lacks CREATE SESSION privilege; logon denied

Warning: You are no longer connected to ORACLE.SQL> conn sys/manager as sysdbaConnected.SQL> GRANT create session TO peter;

Grant succeeded.

SQL> conn peter/oracleConnected.SQL> create table emp  2  (  3  empcode number  4  );create table emp*ERROR at line 1:ORA-01031: insufficient privileges

Page 101: Oracle Notes

SQL> conn sys/manager as sysdbaConnected.SQL> GRANT create table, create view, create sequence, create synonym TO peter;

Grant succeeded.

SQL> conn peter/oracleConnected.SQL> create table emp  2  (  3  empcode number  4  );

Table created.

SQL> insert into emp values(1000);insert into emp values(1000)            *ERROR at line 1:ORA-01950: no privileges on tablespace 'USERS'

SQL> conn sys/manager as sysdbaConnected.SQL> ALTER USER peter  2  QUOTA UNLIMITED ON users;

User altered.

SQL> ALTER USER peter  2  QUOTA 2M ON users;

User altered.

SQL> conn sys/manager as sysdbaConnected.SQL> ALTER USER peter  2  QUOTA 100K ON users;     

Page 102: Oracle Notes

To remove a privilege from the userSQL> REVOKE create table FROM peter;

ROLES : a role is a group of privileges that can be granted to/revoked from the user.

To create a role:CREATE ROLE <rolename>;

To drop a role:

DROP ROLE <rolename>;

Object Privileges-------------------------

Syntax:

GRANT <privname> ON <objname>TO <username>;

SQL> GRANT SELECT, INSERT  2  ON HR.jobs  3  TO peter;

SQL> INSERT INTO hr.jobs VALUES('DBA','Database Administrator',6000,12000);

To revoke an object privilege:SQL> REVOKE select  2  ON hr.jobs  3  FROM peter;

SQL> CREATE USER jerry  2  IDENTIFIED BY oracle  3  DEFAULT TABLESPACE example  4  QUOTA UNLIMITED ON example;

User created.

Page 103: Oracle Notes

To create a new tablespace:SQL> CREATE TABLESPACE PurchaseTbs   2  DATAFILE '/u01/app/oracle/oradata/orcl/purchasetbs01.dbf'  3  SIZE 100M;

Tablespace created.

SQL> ALTER TABLESPACE PurchaseTbs  2  ADD DATAFILE '/u01/app/oracle/oradata/orcl/purchase02.dbf'  3  SIZE 10M;

Tablespace altered.

SQL> create user ally  2  identified by oracle   3  default tablespace purchasetbs  4  quota 40M ON purchasetbs;create user ally            *ERROR at line 1:ORA-01920: user name 'ALLY' conflicts with another user or role name

SQL> l1  1* create user allySQL> c /ally/mohd/  1* create user mohdSQL> /

To delete only the logical structrue from the database:SQL> DROP TABLESPACE purchasetbs INCLUDING CONTENTS;

To delete the logical as well as the physical structure:SQL> drop tablespace admin including contents and datafiles;

To start start enterprise manager:

Page 104: Oracle Notes

Oracle Enterprise Manager (OEM): is a web-based application that allows the DBA to carry out various adminactivities.

[oracle@rajiv Desktop]$ export ORACLE_SID=orcl[oracle@rajiv Desktop]$ lsnrctl start

LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 10-SEP-2015 16:01:02

Copyright (c) 1991, 2009, Oracle.  All rights reserved.

TNS-01106: Listener using listener name LISTENER has already been started[oracle@rajiv Desktop]$ emctl start dbconsoleOracle Enterprise Manager 11g Database Control Release 11.2.0.1.0 Copyright (c) 1996, 2009 Oracle Corporation.  All rights reserved.https://rajiv.oracle:1158/em/console/aboutApplicationStarting Oracle Enterprise Manager 11g Database Control ....... started. ------------------------------------------------------------------Logs are generated in directory /u01/app/oracle/product/11.2.0.4/db_1/rajiv.oracle_orcl/sysman/log [oracle@rajiv Desktop]$ sqlplus sys/manager as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on Thu Sep 10 16:02:16 2015

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

Connected to:Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - ProductionWith the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> startup

To shutdown the instance:SQL> shutdown immediateDatabase closed.Database dismounted.ORACLE instance shut down.SQL> exitDisconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - ProductionWith the Partitioning, OLAP, Data Mining and Real Application Testing options

Page 105: Oracle Notes

[oracle@rajiv Desktop]$ emctl stop dbconsoleOracle Enterprise Manager 11g Database Control Release 11.2.0.1.0 Copyright (c) 1996, 2009 Oracle Corporation.  All rights reserved.https://rajiv.oracle:1158/em/console/aboutApplicationStopping Oracle Enterprise Manager 11g Database Control ...  ...  Stopped. [oracle@rajiv Desktop]$ lsnrctl stop

LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 10-SEP-2015 16:04:12

Copyright (c) 1991, 2009, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))The command completed successfully

A database is a collection of several logical storage units called as TablespacesA Tablespace is shared among many usersA tablespace must be associated with atleast one database file (.dbf) file.A tablespace can be of 3 types:1. Permanent2. Temporary3. UndoA tablespace is made of logical units called as segmentsA segment is a database object owned by a user.A segment is a collection of many ExtentsAn Extent is used to store one strip of data of the same type.An extent is a collection of many data blocks.A Data block is the smallest unit of a database.  A single data block can store one piece of data

1. Configuring Oracle network

tnsnames.oralistener.ora

/u01/app/oracle/product/11.2.0.4/db_1/network/admin

Page 106: Oracle Notes

To create a user with limited dba privilege:

Step1:1. create a user with DBA, CONNECT and RESOURCE roles.

SQL> CREATE USER lily  2  IDENTIFIED BY oracle;

User created.

SQL> GRANT dba, resource, connect TO lily;

Grant succeeded.

Step 2: Connect to OEM as sys user--click setup--Click Administrator--Click Create--Type the user name--click reviewPERFORMING BACKUP using OEM----------------------------------------------The recovery files are located at /u01/app/oracle/flash_recovery_area

The recovery file will be saved as .bkp

The backup can be taken in two modes:1. Offline Backup (Cold Backup)Here the backup is taken when the database instance is in the shutdown mode.

2. Online Backup (Hot Backup): Here the database instance is up and running and users arecarrying out their transactions while the backup is being taken.

To Take an online backup, ensure that the database mode is in ARCHIVELOG mode.

Steps to enable archiving:

1. Shutdown the database instance.SQL> shutdown immediate2. Start the database instance in the mount state.SQL> STARTUP MOUNT

Page 107: Oracle Notes

3. Change the database modeSQL> ALTER DATABASE ARCHIVELOG;4. Start the database instanceSQL> ALTER DATABASE OPEN;To check the status of ARCHIVELOG mode:SQL> ARCHIVE LOG LIST

Using OEM:

1. Connection to OEM as sys2. Click on Availability Tab3. Under setting region click Recovery Setting link4. Check/Uncheck the ARCHIVELOG check box to change the status5. Click Apply. Click OK to confirm shutting down the instance.6. Enter the Host and Database Credentials.7. Click OK to continue. Wait for the datbase to shutdown and restart with the change.

To increase the FLASH RECOVERY AREA:ALTER SYSTEM SET db_recovery_file_dest_size = 5G SCOPE=BOTH

An Oracle database server consists of an Oracle database and one or more database instances. Theinstance consists of memory structures and background processes. Every time an instance is started, ashared memory area called the System Global Area (SGA) is allocated and the background processesare started.The database consists of both physical structures and logical structures. Because the physical andlogical structures are separate, the physical storage of data can be managed without affecting accessto logical storage structures.

The Shared Memory Area or SGA is the shared by all the background processes.The PGA or the Program Global Area is shared by a user process.

Mounting the database means associating a database with an instance.

STARTUP  --NOMOUNT  --MOUNT

Page 108: Oracle Notes

  --OPEN

To start the database in the NOMOUNT stateLSQL> STARTUP NOMOUNT;

1. Oracle will look for a parameter file called spfile<SID>.ora (spfileORCL.ora). If this file is not found, it will thenlook for another file called spfile.ora. If this is also not found, then it will look for init<SID>.ora (initORCL.ora)/u01/app/oracle/product/11.2.0.4/db_1/dbs

2. After reading the parameter file, then it will allocate the SGA (Shared Memory Area).

3. Start up the background processes.

4. Open the ALERT LOG file & trace files.

WHY?

1. For certain database creation2. For recreation of control files.3. For certain Backup and recovery operations.

To start the database in the MOUNT state:

If you db is in IDLE state:STARTUP MOUNT

If the db is in NOMOUNT state:SQL> ALTER DATABASE MOUNT;

1. Oracle associate the database with a previously started instance.

2. It will read the control files. After reading the control files, it will check the status of the online redolog files anddatabase files from these controlfiles.

WHY: 1. To rename the database file2. To perform certain backup and recovery operation.

Page 109: Oracle Notes

3. Enabling/disabling Archiving (online redo log files)

To switch to OPEN state:

SQL> ALTER DATABASE OPEN;

1. All the database files and online redo log files are being read one by one.

WHY:1. To enables the database users to connect to the instance.

SHUTDOWN MODES-------------------------------

SHUTDOWN NORMAL

1. No new connections will be allowed to be made.2. Oracle will wait for the users to disconnect the session.3. When all the user processes are terminated, the database and redo buffers will be written to disk.4. The backgroup processes will be termianted and the SGA will be removed from the instance.5. The database instance will then be dismounted after closing all the control files, redo log files and datbasefiles.6. The next startup will not require any instance recovery.

SHUTDOWN TRANACTIONAL

1. No new connections will be allowed to be made.2. The users who are not running any transactions will get immediately disconnected.3. Oracle will wait for the running transactions to complete. Once the transaction finishes, the user will get disconnected.4. No new transaction will be allowed to be made.5. When all the user processes are terminated, oracle will initiate the SHUTDOWN process.6. The next startup will not require any instance recovery

SHUTDOWN IMMEDIATE

Page 110: Oracle Notes

1. No new connections will be allowed to be made.2. The users who are not running any transactions will get immediately disconnected.3. The currently running transactions will be rolled back and session will be disconnected immediately4. When all the user processes are terminated, oracle will initiate the SHUTDOWN process.5. The next startup will not require any instance recovery

SHUTDOWN ABORT

1. The User process will not terminate2. The transactions will not get rolled back3. The database and redo buffers will bot be written to disk.4. ORacle will close the instance without dismounting it.

To take a backup using OEM:1. Login to OEM as sys2. Click on Availability tab

To Perform Recovery

Non-Critical Recovery

If a Temp file is lost or damaged.

Sol:You do not require a recovery file to recover a temp file.

You need to recreate the temp file.

Method 1:shutdown and restart the database instance

Method 2: recreate the temp fileSQL> ALTER TABLESPACE TEMP  2  ADD TEMPFILE '/u01/app/oracle/oradata/orcl/temp02.dbf' SIZE 50M;

Tablespace altered.

SQL> ALTER TABLESPACE TEMP

Page 111: Oracle Notes

  2  DROP TEMPFILE '/u01/app/oracle/oradata/orcl/temp01.dbf';

Tablespace altered.

DATAFILE RECOVERY (object Level Recovery)-------------------------------------------------------------------It requires a VALID backup.

STEPS:

1. Connect to OEM as sys2. Click Availability Tab.3. Under Manage region click Perform Recovery link4. Select Recovery Scope as Datafiles5. Operation time as REcover to current time6. Enter the host credentials. Click the Recover button7. In step1 select the datafile to be recovered.click next8. In step 2 decide if you want the recovered file to be restored on a new location or not the default. click next9. In review step, review the RMAN scripts and click submit.MANAGING SCHEMA AND ITS OBJECTS-------------------------------------------------------

To create a database object:1. Click on the schema tab

Exporting and Importing of data:Step: Create a user with DBA, CONNECT and RESOURCE role.

SQL> conn sys/manager as sysdbaConnected.SQL> CREATE USER prince  2  IDENTIFIED BY oracle;

User created.

SQL> GRANT dba,resource,connect TO prince;

Page 112: Oracle Notes

Grant succeeded.

--Connect to OEM as sys user--Click on setup link--Click Administrators menu--Click Create--Enter the user in the name field--Click Review--Click Finish--Log out and login as the DBA user

To perform export:

1. Click Data Movement Tab2. under     Move Row Data region, click Export to Export files3. Select the export type as Schema4. Enter the host credentials5. Click Continue to start the Data Pump Wizard6. Click the Add button in step 1 and select the HR schema to be exported and click select7. Click Next8. Under Optional File region,  change the dir object to DATA_PUMP_DIR and type the log file name and click next9. In next step, change the directory object to DATA_PUMP_DIR, change the file name to have a proper format and click next.10. In the schedule step, type the job name and description. Click next11. Click Finish to complete the job. Click on the job link to monitor the scheduled job.

To perform import1. Click Data Movement Tab2. under     Move Row Data region, click Import from export files3. Select the directory object as DATA_PUMP_DIR abd enter the DMP file name in the file name field4. Select the import type as schema and enter the host credentials. 5. In step 1, add the schem to be imported. select the schema to be imported and click select and next.6. Under     Re-Map Schemas click Add another row. ensure that the source and destination schema is same. Click next.

Page 113: Oracle Notes

7. In this step,select the directory object as DATA_PUMP_DIR and enter the log file name. Click next8. In this step, type the job name and description.Leave the schedule for the default and click next.9. Click Submit to finish the job.

To perform exporting/importing using command:To export: expdpTo import: impdp

expdp user/password DIRECTORY=dirname

To Export :

[oracle@rajiv dpdump]$ expdp prince/oracle DIRECTORY=myexport DUMPFILE=hremp1.DMP TABLES=hr.employees LOGFILE=empexp11sep15.log

To import:

[oracle@rajiv dpdump]$ impdp testemp/oracle DIRECTORY=myexport DUMPFILE=hremp1.DMP REMAP_SCHEMA=hr:testemp TABLES=hr.employees LOGFILE=empimport1.log

Managing Hanging issues----------------------------------------1. Connect to OEM as sys2.Click on the PErformance Tab3. Scroll down to additional monitoring links and click Blocking sessions.4.Click the Session id link5. Click on Previous SQL hash value.  Go back and kill session if required.

Database Auditing----------------------------

Page 114: Oracle Notes

To enable auditing:1. connec to OEM as sys2. Click server tab3. Under Database Configuration region click Initialization parameters link.4. Click on SPFile tab5. Type the name audit in the name field and click go to view (AUDIT_TRAIL)6. Change the audit_trail parameter from db to xml7. Click Apply8. Restart the database to change the settings.

Steps to set the object for auditing:1. Click on the server tab2. Under Security region click Audit Settings link.3. Click on the Audited objects tab.4. Click Add button.5. Select the tables to be audited by clicking on the lookup icon.6. Move the required statements to be audited from available to selected statements list.7. Click OK to apply.

SQL> create user test15  2  identified by oracle;

User created.

SQL> grant connect to test15;

Grant succeeded.

SQL> grant insert, update, delete  2  on hr.jobs  3  to test15;

Grant succeeded.

SQL> grant select on hr.jobs to test15;

To monitor the audited objects--------------------------------------------1. On the OEM home, click on the server tab.2. Under security, click Audit Settings link

Page 115: Oracle Notes

3. Under Audit Trails region click Audited Objects link.

Note: to disable auditing, change the AUDIT_TRAIL parameter to NONE and restart the database.

MANAGING UNDO DATA--------------------------------------------

Background: You need to create a user account for Jenny Goodman, the new humanresources department manager. There are also two new clerks in the human resourcesdepartment, David Hamby and Rachel Pandya. All three must be able to log in to theorcl database and to select data from, and update records in, the HR.EMPLOYEEStable. The manager also needs to be able to insert and delete new employee records.Ensure that if the new users forget to log out at the end of the day, they are automaticallylogged out after 15 minutes. You also need to create a new user account for the inventoryapplication that you are installing.In this practice, you create the INVENTORY user to own the new Inventory application.You create a profile to limit the idle time of users. If a user is idle or forgets to log outafter 15 minutes, the user session is ended.

Page 116: Oracle Notes

sqlplus / as sysdba << EOFdrop user inventory cascade;create user inventory identified by verysecuredefault tablespace inventory;grant connect, resource to inventory;

Create a profile named HRPROFILE that allows only 15 minutes idle time.a) Invoke Enterprise Manager as the SYS user in the SYSDBA role for your orcldatabase.b) Click the Server tab, and then click Profiles in the Security section.c) Click the Create button.d) Enter HRPROFILE in the Name field.e) Enter 15 in the Idle Time (Minutes) field.f) Leave all the other fields set to DEFAULT.g) Click the Password tab, and review the Password options, which are currently allset to DEFAULT.h) Optionally, click the Show SQL button, review your underlying SQL statement,and then click Return.i) Finally, click OK to create your profile

Set the RESOURCE_LIMIT initialization parameter to TRUE so that your profilelimits are enforced.a) Click the Server tab, and then click Initialization Parameters in the DatabaseConfiguration section.b) Enter resource_limit in the Name field, and then click Go.c) Select TRUE from the Value drop-down list, and then click Apply.

Create the role named HRCLERK with SELECT and UPDATE permissions on theHR.EMPLOYEES table.a) Click the Server tab and then click Roles in the Security section.b) Click the Create button.c) Enter HRCLERK in the Name field. This role is not authenticated.d) Click Object Privileges tab.e) Select Table from the Select Object Type drop-down list, and then click Add.f) Enter HR.EMPLOYEES in the Select Table Objects field.g) Move the SELECT and UPDATE privileges to the Selected Privileges box. ClickOK.h) Click the Show SQL button, and review your underlying SQL statement.

Page 117: Oracle Notes

i) Click Return, and then click OK to create the role.

Create the role named HRMANAGER with INSERT and DELETE permissions on theHR.EMPLOYEES table. Grant the HRCLERK role to the HRMANAGER role.a) Click the Server tab, and then click Roles in the Security section.b) Click Create.c) Enter HRMANAGER in the Name field. This role is not authenticated.d) Click Object Privileges tab.e) Select Table from the Select Object Type drop-down list, and then click Add.f) Enter HR.EMPLOYEES in the Select Table Objects field.g) Move the INSERT and DELETE privileges to the Selected Privileges box. ClickOK.h) Click the Roles tab, and then click Edit List.i) Move the HRCLERK role into the Selected Roles box, and then click OK.j) Click the Show SQL button, and review your underlying SQL statement.k) Click Return, and then click OK to create the role.

MANAGING SCHEMA

MANAGING HANGING SESSIONS

The Help desk just received a call from Susan Mavris, an HRrepresentative, complaining that the database is “frozen.” Upon questioning the user, youfind that she was trying to update John Chen’s personnel record with his new phonenumber, but when she entered the new data, her session froze and she could not doanything else. SQL script files are provided for you in the /home/oracle/labsdirectory.

In this practice, you use two separate SQL*Plus sessions to cause a lock conflict. Using

Page 118: Oracle Notes

Enterprise Manager, you detect the cause of the lock conflict and then resolve theconflict. For your convenience, the SQL code that will cause the lock conflict has beenprovided in scripts that you run during this practice.

1. run the lab_09_01.sql script. This script first creates the users (smavris andngreenberg) that are involved in this practice and the hremployee role that willgive these new users access to the hr.employee table. It then logs in to SQL*Plusas the ngreenberg user and performs an update on the hr.employee table. Thescript does not perform a commit, leaving the update uncommitted in this session.

Leave this session connected in the state that it is currently. Do not exit at thistime.

Make an attempt to update the same row in a separate session by running, in aseparate terminal window, the lab_09_02.sql script. Make sure that you see themessage “Update is being attempted now” before moving on. Do not worry if thesession seems to “hang”—this is the condition that you are trying to create.

Notice that this session appears to be hung. Leave this session as is and move onto the next step.

Using Enterprise Manager, click the Blocking Sessions link on the Performance pageand detect which session is causing the locking conflict.a) In Enterprise Manager, click the Performance page.a) Select the NGREENBERG session, and then click View Session.b) Click the hash value link named “Previous SQL.”c) Note the SQL that was most recently run.a) Click the browser’s Back button.b) Now, on the Session Details: NGREENBERG page, click Kill Session.c) Leave the Options set to Kill Immediate, and then click Show SQL to see thestatement that is going to be executed to kill the session.d) Click Return, and then click Yes to carry out the KILL SESSION command.

Return to the SQL*Plus command window, and note that SMAVRIS’s update hasnow completed successfully. It may take a few seconds for the success message toappear.

Page 119: Oracle Notes

MANAGING UNDO DATAThe business users and management in your organization decide, that theyneed to have a 48-hour retention of undo in the Oracle database to support their flashbackneeds. Your task is to configure the orcl database to support this requirement. In this practice, you first view your system activity regarding undo, and then youconfigure the orcl database to support 48-hour retention for flashback operations.1) In Enterprise Manage  r, as the DBA1 user, view the undo related system activity.a) Click the Server tabbed page and select “Automatic Undo Management” in theDatabase Configuration section.b) Click the System Activity tabbed page.Note: Your information will look different on all analysis screenshots, based on youranalysis period and the system activity during this period.c) Question: Looking at the preceding screenshot, how many errors did this systemencounter?Answer: Noned) Question: Looking at the preceding screenshot, what is the duration of the longestrunning query?Answer: 28 minutes (Your answer may be different.)e) Click the Plus icon to show related graphs.f) Question: How many graphs are displayed?Answer: Three. (Undo Tablespace Usage, Undo Retention Auto-Tuning, andUndo Generation Rate)g) Question: Looking at the preceding Undo Retention Auto-Tuning graph, couldthis system support flashback above and beyond the current longest runningquery?Answer: Yes, (but most likely not enough to support the required 48 hours).

2) Modify the undo retention time and calculate the undo tablespace size to support therequested 48-hour retention.a) Click the General tab to go back to the General Automatic Undo Managementpage.b) Under the Undo Advisor section, select “Specified manually to allow for longerduration queries or flashback.”c) Enter 48 hours as Duration and click the Run Analysis button.d) When the Undo Advisor is finished, take a look at the results.It looks like the undo tablespace is very close to the recommended undo

Page 120: Oracle Notes

tablespace size. This is okay for most workloads, but the recommendation is to setyour undo tablespace size to be three times the minimum size. This means thatyou should change your undo tablespace size to be 846 MB.Note: Your recommended size might be different from what is shown here, soadjust the size accordingly.e) Click the Show SQL button in the upper-right corner of the General AutomaticUndo Management page.f) This command will change the undo retention to support the 48-hour requirement.Review the SQL statement and click Return.g) Click Apply to make the change to undo retention.h) Now adjust the undo tablespace size by clicking the Edit Undo Tablespace button.i) Scroll down to Datafiles and click Edit to make a change to theundotbs01.dgf file size.j) Change the file size to 846 MB and click Continue.k) Verify the SQL commands that will be executed by clicking Show SQL.Click Return.l) Click Apply to change the tablespace size.

3) Go back to the Automatic Undo Management to see the results of the changes youjust made. You see that the undo retention time has increased to support the 48 hoursrequirement. Your undo tablespace size has also increased based on the changes youmade to the size of the datafile for the undo tablespace.a) Question: Which Flashback operations are potentially affected by this change?Answer: Flashback query, Flashback transaction, and Flashback table.b) Question: Do undo data survive the shutdown of a database?Answer: Yes, undo is persistent.

AUDITINGBackground: You have just been informed of suspicious activities in the HR.JOBS tablein your orcl database. The highest salaries seem to fluctuate in a strange way. Youdecide to enable standard database auditing and monitor data manipulation language(DML) activities in this table.

Log in as the DBA1 user (with oracle password, connect as SYSDBA) and perform thenecessary tasks either through Enterprise Manager Database Control or throughSQL*Plus. All scripts for this practice are in the /home/oracle/labs directory.1) Use Enterprise Manager to enable database auditing. Set the AUDIT_TRAILparameter to XML.a) Invoke Enterprise Manager as the DBA1 user in the SYSDBA role for your orcl

Page 121: Oracle Notes

database.b) Click the Server tab, and then click Audit Settings in the Security section.c) Click the value of Audit Trail, the DB link.d) On the Initialization Parameters page, click the SPFile tab.e) Enter audit in the Name field and then click Go.f) For the audit_trail parameter, select the XML value.g) Click Show SQL.h) Review the statement and then click Return.i) On the Initialization Parameters page, click Apply.

2) Because you changed a static parameter, you must restart the database. Do so byrunning the lab_11_02.sh script.a) In a terminal window, enter:b) Continue with the next step when you see that the database is restarted and thescript has exited SQL*Plus.

3) Back in Enterprise Manager, select HR.JOBS as the audited object and DELETE,INSERT, and UPDATE as Selected Statements. Gather audit information by session.Because the database has been restarted, you have to log in to Enterprise Manageragain as the DBA user.a) Click logout in the upper-right corner of the Enterprise Manager window.b) Log in as the DBA1 user in the SYSDBA role for your orcl database.c) Click the Database home page tab to ensure that Enterprise Manager had time toupdate the status of the database and its agent connections.d) Click the Server tab, and then click Audit Settings in the Security section.e) Click the Audited Objects tab at the bottom of the page, and then click the Addbutton.) On the Add Audited Object page, ensure that the Object Type is Table, and enterHR.JOBS in the Table field (or use the flashlight icon to retrieve this table).g) Move DELETE, INSERT, and UPDATE into the Selected Statements area bydouble-clicking each of them.h) Click Show SQL.i) Review the statement, and then click Return.j) Click OK to activate this audit.

4) Provide input for the audit, by executing the lab_11_04.sh script. This scriptcreates the AUDIT_USER user, connects to SQL*Plus as this user, and multiplies thevalues in the MAX_SALARY column by 10. Then the HR user connects and dividesthe column values by 10. Finally, the AUDIT_USER user is dropped again.a) In a terminal window, enter:

Page 122: Oracle Notes

5) In Enterprise Manager, review the audited objects.a) Click the Server tab, and then click Audit Settings in the Security section.b) Click Audited Objects in the Audit Trails area, which is on the right side of thepage.c) On the Audited Objects page, review the collected information.Question: Can you tell which user increased and which user decreased thesalaries?Answer: No, the standard audit records only show which user accessed the table.d) Click Return.

6) Undo your audit settings for HR.JOBS, disable database auditing, and then restart thedatabase by using the lab_11_06.sh script.a) On the Audit Settings page, click the Audited Objects tab at the bottom of thepage.b) Enter HR as Schema, and then click Search.c) Select all three rows, and then click Remove.d) On the Confirmation page, click Show SQL.e) Review the statements, and then click Yes to confirm your removal.f) On the Audit Settings page, click XML in the Configuration region.g) On the Initialization Parameters page, click the SPFile tab.h) On the SPFile page, enter audit in the Name field, and then click Go.i) For the audit_trail parameter, select the DB value.j) Click Show SQL.k) Review the statement, and then click Return.l) On the Initialization Parameters page, click Apply.m) Because you changed a static parameter, you must restart the database. Do so byrunning the lab_11_06.sh script. In a terminal window, enter:

7) Maintain your audit trail: Because you are completely finished with this task, backupand delete all audit files from the /u01/app/oracle/admin/orcl/adumpdirectory.a) In a terminal window, enter:b) Create a backup of the audit trail files, and then remove the filesc) Close the terminal window.

BACKUP and RECOVERYBackground: Your orcl database is ready to move from test or development into

Page 123: Oracle Notes

production.Configure your database to reduce the chances of failure or data loss. To do so, performthe following tasks:• Ensure redundancy of control files and backup the control file to trace• Review the flash recovery area configuration• Ensure that there are at least two redo log members in each group• Place your database in ARCHIVELOG mode• Configure redundant archive log destinations

In this practice, you configure your database to reduce the chances of failure or data loss.Note: Completing this practice is a prerequisite for all following backup and recoverypractices.1) Verify that you have at least two control files to ensure redundancy and backup thecontrol file to trace.a) Invoke Enterprise Manager as the DBA1 user in the SYSDBA role for your orcldatabase.b) Click Server > Control Files (in the Storage section).Question 1: On the Control Files: General page, how many control files do youhave?Answer: Three (in the preceding example).Question 2: How would you add another control file if you needed to?Answer: Adding a control file is a manual operation. To perform this, you must:• Shut down the database• Use the operating system to copy an existing control file to the location whereyou want your new file to be.• Start the database by using Enterprise Manager. Unlike a normal startup, youwould use Advanced Options to select a different startup mode. Select “Startthe instance” to leave the instance in the NOMOUNT state.• Edit the CONTROL_FILES initialization parameter to point to the newcontrol file.• Continue the STARTUP database operation until the database is in an openstate.Note••This answer does not apply to an OMF database because the control files inthat case would have to all be re-created.Alternatively, if you did not want to use Enterprise Manager to perform thesteps, you could perform the steps outlined in the Multiplexing Control Filesslide in the “Backup and Recover Concepts” lesson.c) Click Backup to Trace.

Page 124: Oracle Notes

d) When you receive the success message, note the trace directory location, and thenclick OK.e) Optionally, use a terminal window, logged in as the oracle user to view thetrace file name at the end of the alert log by executing the following command:cd /u01/app/oracle/diag/rdbms/orcl/orcl/tracetail alert_orcl.logThe following output shows only the last few lines:f) Optionally, to view size and usage of the different sections within the control file,click the Record Section tabbed page.Your numbers could look different. For additional information, click Help in theupper-right corner of the page.2) Review the flash recovery area configuration and change the size to 8 GB.a) In Enterprise Manager, select Availability > Recovery Settings in the Setupsection.b) Scroll to the bottom of the page.c) Question: Is the flash recovery area enabled?Answer: Yes, by default.d) Note the location of the flash recovery area.For example: /u01/app/oracle/flash_recovery_areae) Question: Which essential DBA tasks can you perform in this section?Answer: You can change the location, size or retention time for the flash recoveryarea, as well as enable the Flashback Database functionality.f) Question: Does changing the size of the flash recovery area require the databaseto be restarted?Answer: No, a restart is not required for this change.g) Change the size of the Flash Recovery Area to 8 GB, by entering 8 into the“Flash Recovery Area Size” field.h) Optionally, click Show SQL, review the statement and click Return.i) Click Apply.

3) Check how many members each redo log group has. Ensure that there are at least tworedo log members in each group. One set of members should be stored in the flashrecovery area.a) Click Server > Redo Log Groups, and note how many members are in the “# ofMembers” column.Answer: There is only one member in each group.b) To add a member to each group, perform the following steps for each group:i) Select the group (for example, 1) and click the Edit button.ii) On the Edit Redo Log Group page, note the File Name, for example“redo01.log” and click the Add button.iii) On the Edit Redo Log Group: Add Redo Log Member page, enter a file name

Page 125: Oracle Notes

by adding the letter “b” to the end of the name (before the dot). For example,enter redo01b.log as File Name and enter your flash recovery area, forexample, /u01/app/oracle/flash_recovery_area/ as FileDirectory.iv) Click Continue.v) On the Edit Redo Log Group page, review the current members.Note: If you forget to add the last slash to the directory name, the system doesit for you.vi) Optionally, click Show SQL to review the command, and then Return.vii) Click Apply.viii) You should receive a success message. Return to the Redo Log Groups pageand repeat the preceding sequence of steps (under 3 b) for each of theremaining redo log groups.c) You are finished with this task, when the # of members displays 2 for each group.Note: In a production database, you want to ensure that the two members are ondifferent hard drives, preferably with different disk controllers, to minimize therisk of any single hardware failure destroying an entire log group.

4) You notice that, for each log group, the Archived column has a value of No. Thismeans that your database is not retaining copies of redo logs to use for databaserecovery, and in the event of a failure, you will lose all data since your last backup.Place your database in ARCHIVELOG mode, so that redo logs are archived.Note: You must continue with step 5, so that your changes are applied.a) In Enterprise Manager, select Availability > Recovery Settings in the Setupsection.b) In the Media Recovery region, select the ARCHIVELOG Mode check box.c) Verify that Log Archive Filename Format contains %t, %s, and %r.d) Notice the current configuration of redundant archive log destinations—one to theflash recovery area and the other to/u01/app/oracle/product/11.1.0/db_1/dbs/arch. The databaseis preconfigured to save archived logs to the flash recovery area (Archive LogDestination 10), as well as to a redundant location (Archive Log Destination 1).Note: If you add archive log destinations, you must create the directory, if it doesnot already exist.e) Click Apply.f) When prompted whether you want to restart the database now, click Yes.g) Enter the credentials to restart the database (oracle as the Host Credentials, andsys/oracle as SYSDBA as Database Credentials), and then click OK.h) When asked to confirm, click Yes again.i) Should you receive an error during the shutdown and startup activity, click OK toacknowledge the error, and then click Refresh again. (You might have been

Page 126: Oracle Notes

simply faster than the database.)

5) Optionally, use SQL*Plus to check whether your database is in ARCHIVELOG mode.In a terminal window, log in to SQL*Plus as SYSDBA and run the archive loglist command.Now that your database is in ARCHIVELOG mode, it will continually archive a copyof each online redo log file before reusing it for additional redo data.Note: Remember that this consumes space on the disk and that you must regularlyback up older archive logs to some other storage.

Your database is ready to move from development and testing intoproduction. Ensure that your database is configured so that recovery is possible withoutloss of data. Establish the backup policy to automatically back up the SPFILE andcontrol file. Perform an immediate backup to disk and schedule nightly backup jobs thatrepeat indefinitely.In this practice, you perform an immediate backup to disk and schedule a nightly backupjob.1) What is the difference between a backup set and an image copy?Answer: A backup set contains data and archive log files packed in an Oracleproprietary format. Files must be extracted before use. Image copies are theequivalent of operating system file copies and can be used for restore operationsimmediately.2) What is the destination of any disk backups that are done?a) Log in to Enterprise Manager as the DBA1 user in the SYSDBA role and selectAvailability > Backup Settings.b) Note the message under the Disk Backup Location that says the flash recoveryarea is the current disk backup location.3) Establish the backup policy to automatically back up the SPFILE and control file.a) Click the Policy tab under the Backup Settings pages.b) Click Automatically backup the control file and server parameter file(SPFILE) with every backup and database structural change.c) Scroll to the bottom and enter oracle and oracle for Host CredentialsUsername and Password for your server, and click “Save as PreferredCredential.”4) Test making a backup to disk, as a backup set, with oracle for Host Credentials.a) Click the Device tab under the Backup Settings pages.b) Select Backup Set as your Disk Backup Type.c) Scroll to the bottom and ensure the Host Credentials are set to oracle.

Page 127: Oracle Notes

d) Scroll to the top of the page and click Test Disk Backup.e) A processing message appears. When the test finishes, and you see the ‘DiskBackup Test Successful!’ message, click OK.5) Back up your entire database, with archive logs, while the database is open for useractivity. This backup should be the base for an incremental backup strategy.a) Question: What prerequisite must be met to create a valid backup of a databasewithout shutting it down?Answer: The database must be in ARCHIVELOG mode. Backups made with thedatabase open, but not in ARCHIVELOG mode, cannot be used for recovery.b) Select Availability > Schedule Backup (in the Manage section).If you find that the Oracle-Suggested Backup strategy fits your needs exactly, youwould chose this option. For practice purposes, you will schedule a customizedbackupc) Select Whole Database as the object to be backed up.d) Confirm or enter oracle and oracle for Host Credentials Username andPassword for your server.e) Click Schedule Customized Backup.f) On the Schedule Customized Backup: Options page, select Full Backup for yourBackup Type, and select the Use as the base of an incremental backup strategycheck box.g) Select Online Backup as Backup Mode.h) In the Advanced section, select “Also back up all archived logs on disk” and“Delete all archived logs from disk after they are successfully backed up”,and then click Next to continue.i) On the Schedule Customized Backup: Settings page, select Disk for your backuplocation. (Notice that your Disk Backup Location is retained and that you couldoverride the current settings for a one-off backup. But do not click it this time.)j) Click Next.k) Accept all the defaults on the Schedule Customized Backup: Schedule page andthen click Next to continue.Note: Schedule Type should be One Time (Immediately).l) On the Schedule Customized Backup: Review page, review the RMAN script,and then click Submit Job.m) Click View Job to monitor the status of the backup job. The time for this backupdepends on your hardware and system resources.n) Click your browser’s Refresh or Requery button until the job is completed.6) Schedule nightly disk-based incremental online backups for your whole database,without archived logs. Schedule it for execution at 11:00 PM. The schedule should bein effect indefinitely.a) In Enterprise Manager, select Availability > Schedule Backup (in the Managesection).

Page 128: Oracle Notes

b) Select Whole Database as the object to be backed up.c) Confirm or enter oracle and oracle for Host Credentials Username andPassword for your server, and then click Schedule Customized Backup.d) On the Schedule Customized Backup: Options page, select Incremental Backupas your Backup Type.e) Select Online Backup as Backup Mode.f) In the Advanced region, select “Also backup all archived logs on disk” and“Delete all archived logs from disk after they are successfully backed up”,and then click Next to continue.g) On the Schedule Customized Backup: Settings page, select Disk as your backuplocation, and then click Next to continue.h) On the Schedule Customized Backup: Schedule page, change Job Name toNightly_Backup and accept the default value for Job Description.i) Select Repeating in the Schedule region. Notice how additional context sensitivedetails are displayed.j) Select By Days from the Frequency Type drop-down list, enter 1 in the RepeatEvery field, confirm that Indefinite is selected as the Repeat Until value, and enter11:00 PM as Time.k) Click Next to continue.l) On the Schedule Customized Backup: Review page, review your Settings andRMAN script.m) Click Submit Job, and then click OK.n) Click Jobs on the Availability page in the Related Links section to see thescheduled job in the Job Activity list.

Many failures of the Oracle database can be traced to some sort of mediafailure, such as disk or controller failure. In this practice, you encounter a number ofproblems from which you need to recover the database.• Recover from the loss of a control file• Recover from the loss of a data file• Recover from the loss of a redo log member• Recover from the loss of a file in the SYSTEM tablespaceSQL script files are provided for you in the /home/oracle/labs directory. Ifneeded, use the appendixes for Linux and for SQL syntax. After you set up a failure witha SQL script, you must complete the recovery before continuing with any other practice.Note: Your system may have different OS file names than shown here. Your output

Page 129: Oracle Notes

might look different. (To conserve space, blank lines have been removed.)

Before beginning one of the recovery scenarios, you need to run a script that will preparethe environment for the remaining recovery practices.1) Before setting up an individual problem, you need to navigate to your labs directoryand (in SQL*Plus) execute the lab_16_01.sql script as the SYS user. This scriptprepares some procedures to be called by the rest of this practice.In this practice, your system experiences the loss of a control file. You then go throughthe steps to recover from this loss.1) Continue in your SQL*Plus session as the SYS user. Execute the lab_16_02.sqlscript. This script deletes one of your control files.2) The Help desk begins receiving calls saying that the database appears to be down.Troubleshoot and recover as necessary. Use Enterprise Manager to try to start up thedatabase, and use SQL*Plus if needed.a) In Enterprise Manager, navigate to the Database home page. It reports that thedatabase is down and offers you the chance to start it up again.Note: you may see a message stating ‘Internal Error has occurred.’ If so, keeptrying to connect to using the Enterprise Manager URL. Eventually it will displaythe database home page.b) Click Startup. If you see a Connection Refused message, ignore it; the connectionwill eventually be established.c) Enter oracle as Username and Password for Host Credentials and click OK.d) Click Yes to confirm your attempted startup.e) The startup of the instance fails with Enterprise Manager. Click View Details formore information.f) Note the following, and then click OK:ORA-00205: error in identifying control file, check alertlog for more infog) Alternatively, in a new SQL*Plus session, check the current status of the instanceas the SYS user and attempt to mount it with the following commands:select status from v$instance;alter database mount;3) The instance cannot move to the mount stage because it cannot find one of the controlfiles. To find the locations of the alert log and of diagnostic information, enter thefollowing SELECT statement:SELECT NAME, VALUE FROM V$DIAG_INFO;4) Look at the last 25 lines in the log.xml file to see if you can find out what theproblem is. Still inside your SQL*Plus session, enter the following command (on oneline):host tail -25/u01/app/oracle/diag/rdbms/orcl/orcl/alert/log.xml

Page 130: Oracle Notes

5) Note that in the preceding example, the control02.ctl file is missing. Thismight be different in your environment. Restore the control file that is missing foryour database by copying an existing control file. Enter the following command withyour correct file names (on one line):host cp /u01/app/oracle/oradata/orcl/control01.ctl/u01/app/oracle/oradata/orcl/control02.ctl6) (Optional) To view the content of the directory, enter:host ls /u01/app/oracle/oradata/orcl7) Now mount and open the database with the following commands:connect / as sysdbaalter database mount;alter database open;a) Why did you have to use two commands to move the instance state fromNOMOUNT to OPEN?Answer: Because the ALTER DATABASE command enables you to change onlyone state level for each commandb) Why did you use operating system commands to restore the control file instead ofusing Oracle Recovery Manager?Answer: Because all control files are identical. As long as any one control file isintact, it can be used to restore the others.8) Exit all sessions and close all windows

Recovering from the Loss of a Data File

1) In a SQL*Plus session, as the SYS user, execute the lab_16_03.sql script fromyour labs directory. This script deletes one of your application data files.2) The Help desk has received a call from a user who is unable to access theCOUNTRIES table in the HR application schema. Count the rows in the table todetermine whether there is a problem.3) Troubleshoot and recover as necessary. The error message suggests that theexample01.dbf data file is corrupt or missing.a) In Enterprise Manager, click Availability > Perform Recovery.b) Click Advise and Recover.c) On the View and Manage Failures page, click the plus (+) icon under the failuredescription. You should see a failure like the following:Note: If you do not see the nonsystem datafile failure, keep refreshing the pageuntil it shows up.d) With the failures selected, click Advise.e) Because the file was not just renamed or moved, but deleted, you continue by

Page 131: Oracle Notes

clicking “Continue with Advise.”f) On the Recovery Advise page, you see the RMAN script. Click Continue.g) On the Review page, you see the failure and the suggested solution. Click“Submit Recovery Job.”h) A Processing window appears, followed by the Job Activity page. You should seea message that the job was successfully created. (Your link name is probablydifferent.)i) Click the job name link.j) On the Job Run page, check the Status in the Summary section. If it is Running,use you browser’s Refresh or Requery button until the job is completed.k) In your SQL*Plus session, verify that the HR.COUNTRIES table is nowaccessible.

In this practice, your system experiences the loss of a redo log member. You then gothrough the steps to recover from this loss.1) Make sure that you are in your labs directory. Using SQL*Plus, execute thelab_16_04.sql script as the SYS user. The lab_16_04.sql script deletes oneof your redo log files. See the error in the alert log and recover from it.2) The database continues to function normally, and no users are complaining. Log in toEnterprise Manager with the DBA1 username as SYSDBA. On the Database homepage, view alerts similar to the following ones:If you do not see similar alerts, you may need to wait a few minutes and refresh thepage. One of the failures listed may be left over from the data file recovery youperformed in the previous practice.3) Click Availability > Perform Recovery (in the Manage section).4) On the Perform Recovery page, you see the Failure Description and could directlybegin correcting the failure. But for practice purposes, you follow the steps in theData Recovery Advisor. Scroll down and ensure that your host credentials are set(oracle for both username and password). Then click the “Advise and Recover”button (which is one of the ways to invoke the Data Recovery Advisor).5) On the View and Manage Failures page, ensure that the failure is selected, and clickAdvise.6) The Manual Actions page suggests to manually restore it. In the preceding example,redo03.log is deleted. Do not click any button at this point in time.7) In a new terminal window, as the oracle user, copy an existing redo log from thesame redo log group to the missing file.Note: The actual redo log member that was lost on your machine may be differentthan the one shown here. Make sure that you are replacing the file names as

Page 132: Oracle Notes

appropriate for your failure.cd /u01/app/oracle/oradata/orcllscp /u01/app/oracle/flash_recovery_area/redo02b.log redo02.loglsexit8) Now return to your Manual Actions page in Enterprise Manager and click the Re-assess Failures button.a) Note that there are now no failures found.b) Question: Why did the database not crash?Answer: Because a single missing member is noncritical and does not affect theoperation of the database. As long as there is at least one good member for eachlog group, the database operation continues.In this practice, your system experiences the loss of a file in the SYSTEM tablespace. Youthen go through the steps to recover from this loss.1) Why is recovery from the loss of a system data file or a data file belonging to an undotablespace different from recovering an application data file?Answer: Because recovery of system or undo data files must be done with thedatabase closed, whereas recovery of an application data file can be done with thedatabase open and available to users2) As the SYS user, execute the lab_16_05.sql script in your labs directory. Thisscript deletes the system data file.3) In Enterprise Manager, review the Database home page. If you see a message thatsays the connection was refused, dismiss it and reenter the EM home page URL in thebrowser. You may need to try several times before you see the Database home page.4) The database is shut down. Attempt to start your database.a) Click Startup to try to open it.b) On the ‘”Startup/Shutdown:Specify Host and Target Database Credentials” page,enter oracle and oracle as Host Credentials. Click OK.c) On the Startup/Shutdown:Confirmation page, click Yes.d) A progress page appears, followed by an error message.5) Note that the database is in a mounted state. Click Perform Recovery.a) Enter oracle and oracle as Host Credentials, and click Continue.b) On the Database Login page, enter DBA1, oracle, and SYSDBA and clickLogin.6) On the Perform Recovery page, you could select the Oracle Advised Recovery, butfor practice purposes, continue with a User Directed Recovery.a) In the User Directed Recovery section, select Datafiles from the Recovery Scopedrop-down list and “Recover to current time” as Operation Type.b) Scroll down and enter oracle and oracle as Host Credentialsc) Click Recover.

Page 133: Oracle Notes

d) On the Perform Object Level Recovery: Datafiles page, you should see themissing data file. Click Next.e) Because the problem is simply a deleted file rather than a bad hard drive, there isno need to restore to a different location. Select “No. Restore the files to thedefault location” and then click Next.f) On the Perform Object Level Recovery: Review page, view your current optionsand the data file. Click Edit RMAN Script to review the RMAN commands.g) Review the RMAN commands and click Submit.h) A processing page appears, followed by the Perform Recovery: Result page. Theduration of this operation depends on your system resources. The recoveryoperation should be successful.i) On the Perform Recovery: Result page, click Open Database.j) After you see the success message, click OK.k) Verify that the database is open and operating normally by logging in to EM asyour DBA1 user as SYSDBA, and reviewing the Database home page.

EXPORTING/IMPORTINGn the recent past, you received a number of questions about the HRschema. To analyze them without interfering in daily activities, you decide to use theData Pump Wizard to export the HR schema to file. When you perform the export, youare not sure into which database you will be importing this schema.In the end, you learn that the only database for which management approves an import isthe orcl database. So you perform the import with the Data Pump Wizard, remappingthe HR schema to DBA1 schema.Then you receive two data load requests for which you decide to use SQL*Loader.In this practice, you first grant the DBA1 user the privileges necessary to provide accessto the DATA_PUMP_DIR directory. You then export the HR schema so that you can thenimport the tables you want into the DBA1 schema. In the practice, you import only theEMPLOYEES table at this time.1) First, you need to grant the DBA1 user the appropriate privileges on theDATA_PUMP_DIR directory and create the users and roles required for this practice.A script exists that performs all the steps required to configure your environment forthis practice.a) Review the lab_17_01.sql script, which grants the DBA1 user privileges onthe DATA_PUMP_DIR directory and performs other configurations to yourenvironment, by executing the following in your labs directory:$ cat lab_17_01.sqlb) The lab_17_01.sh script calls the lab_17_01.sql script. Execute the

Page 134: Oracle Notes

lab_17_01.sh script now:2) Log in to Enterprise Manager as the DBA1 user in the Normal role and export theHR schema.a) Invoke Enterprise Manager as the DBA1 user as the Normal role for your orcldatabase. The Connect As setting should be Normal.b) Select Data Movement > Move Row Data > Export to Export Files.c) Select Schemas, enter oracle as Username and Password, select Save asPreferred Credential, and then click Continue.d) On the Export: Schemas page, click Add, select the HR schema, and then click theSelect button.e) You see that HR is now in the list of schemas. Click Next.f) On the “Export: Options” page, select DATA_PUMP_DIR from the DirectoryObjects drop-down list, and enter hrexp.log as Log File.g) Review Advanced Options (but do not change), and then click Next.h) On the “Export: Files” page, select DATA_PUMP_DIR from the DirectoryObject drop-down list, enter HREXP%U.DMP as File Name, and then click Next.i) On the “Export: Schedule” page, enter hrexp as Job Name and Export HRschema as Description, accept the immediate job start time, and then clickNext.j) On the “Export: Review” page, click Show PL/SQL and review the PL/SQL thatthe Export Wizard helped you to create.k) Click Submit Job to submit the job.l) Click the link to the HREXP job to monitor the progress. When the job shows assuccessfully completed, move on to the next step.3) Now, import the EMPLOYEES table from the exported HR schema into the DBA1schema. To get a feeling for the command-line interface, you can use the impdputility from the command line to import the EMPLOYEES table into the DBA1 userschema.a) Enter the following entire command string. Do not press [Enter] before reachingthe end of the command:impdp dba1/oracle DIRECTORY=data_pump_dir DUMPFILE=HREXP01.DMP REMAP_SCHEMA=hr:dba1 TABLES=employees LOGFILE=empimport.logNote: You may see errors on constraints and triggers not being created because onlythe EMPLOYEES table is imported and not the other objects in the schema. Theseerrors are expected.b) You can also verify that the import succeeded by viewing the log file.$ cat /u01/app/oracle/admin/orcl/dpdump/empimport.log4) Confirm that the EMPLOYEES table has been loaded into the DBA1 schema bylogging in to SQL*Plus as the DBA1 user and selecting data from the EMPLOYEEStable.a) Log in to SQL*Plus as the DBA1 user.

Page 135: Oracle Notes

b) Select a count of the rows from the EMPLOYEES table in the DBA1 schema, forverification of the import.

In this practice, you load data into the PRODUCT_MASTER table by using SQL*Loadervia Enterprise Manager Database Control. Data and control files are provided.1) As the DBA1 user, use Enterprise Manager to load the lab_17_02_01.dat datafile. This data file contains rows of data for the PRODUCT_MASTER table. Thelab_17_02_01.ctl file is the control file for this load.Optionally, view the lab_17_02_01.dat and lab_17_02_01.ctl files tolearn more about their structure before going further.a) Invoke Enterprise Manager as the DBA1 user as the Normal role for your orcldatabase.b) Select Data Movement > Move Row Data > Load Data from User Files.c) Click Use Existing Control File. If not already entered, enter oracle asUsername and as Password, click Save as Preferred Credential, and then clickContinue.d) On the “Load Data: Control File” page, enter/home/oracle/labs/lab_17_02_01.ctl as the control file name andpath, or use the flashlight icon to select this control file. Click Next.e) On the “Load Data: Data File” page, click Provide the full path and name onthe database server machine and enter/home/oracle/labs/lab_17_02_01.dat as the data file name and path,or use the flashlight icon to select this data file. Click Next.f) On the “Load Data: Load Method” page, select Conventional Path, and thenclick Next.g) On the “Load Data: Options” page, accept all defaults, but enter/home/oracle/labs/lab_17_02_01.log as the log file name and path.Review the advanced options if you want, but do not change any, and then clickNext.h) On the “Load Data: Schedule” page, enter lab_17_02_01 as Job Name andLoad data into the PRODUCT_MASTER table as Description. Let thejob start immediately, and then click Next.i) On the “Load Data: Review” page, review the loading information andparameters, and then click Submit Job.j) Click the link to the LAB_17_02_01 job to monitor the progress. After the jobshows as successfully completed, move on to the next step.k) Confirm your results by viewing your lab_17_02_01.log file in your/home/oracle/labs directory.2) As the INVENTORY user, load data into the PRODUCT_ON_HAND table by usingSQL*Loader command line. The lab_17_02_02.dat data file contains rows of

Page 136: Oracle Notes

data for the PRODUCT_ON_HAND table. The lab_17_02_02.ctl file is thecontrol file for this load.Optionally, view the lab_17_02_02.dat and lab_17_02_02.ctl files tolearn more about their structure before going further.a) Open a terminal window and navigate to the /home/oracle/labs directory.b) Enter the following SQL*Loader command (in continuation, without pressing[Enter] before reaching the end of the command):sqlldr userid=inventory/verysecure control=lab_17_02_02.ctllog=lab_17_02_02.log data=lab_17_02_02.datc) Confirm your results by viewing your lab_17_02_02.log file in your/home/oracle/labs directory.MANAGING SCHEMA AND ITS OBJECTS-------------------------------------------------------

To create a database object:1. Click on the schema tab

Exporting and Importing of data:Step: Create a user with DBA, CONNECT and RESOURCE role.

SQL> conn sys/manager as sysdbaConnected.SQL> CREATE USER prince  2  IDENTIFIED BY oracle;

User created.

SQL> GRANT dba,resource,connect TO prince;

Grant succeeded.

--Connect to OEM as sys user--Click on setup link--Click Administrators menu--Click Create--Enter the user in the name field--Click Review--Click Finish

Page 137: Oracle Notes

--Log out and login as the DBA user

To perform export:

1. Click Data Movement Tab2. under     Move Row Data region, click Export to Export files3. Select the export type as Schema4. Enter the host credentials5. Click Continue to start the Data Pump Wizard6. Click the Add button in step 1 and select the HR schema to be exported and click select7. Click Next8. Under Optional File region,  change the dir object to DATA_PUMP_DIR and type the log file name and click next9. In next step, change the directory object to DATA_PUMP_DIR, change the file name to have a proper format and click next.10. In the schedule step, type the job name and description. Click next11. Click Finish to complete the job. Click on the job link to monitor the scheduled job.

To perform import1. Click Data Movement Tab2. under     Move Row Data region, click Import from export files3. Select the directory object as DATA_PUMP_DIR abd enter the DMP file name in the file name field4. Select the import type as schema and enter the host credentials. 5. In step 1, add the schem to be imported. select the schema to be imported and click select and next.6. Under     Re-Map Schemas click Add another row. ensure that the source and destination schema is same. Click next.7. In this step,select the directory object as DATA_PUMP_DIR and enter the log file name. Click next8. In this step, type the job name and description.Leave the schedule for the default and click next.9. Click Submit to finish the job.

To perform exporting/importing using command:To export: expdpTo import: impdp

Page 138: Oracle Notes

expdp user/password DIRECTORY=dirname

To Export :

[oracle@rajiv dpdump]$ expdp prince/oracle DIRECTORY=myexport DUMPFILE=hremp1.DMP TABLES=hr.employees LOGFILE=empexp11sep15.log

To import:

[oracle@rajiv dpdump]$ impdp testemp/oracle DIRECTORY=myexport DUMPFILE=hremp1.DMP REMAP_SCHEMA=hr:testemp TABLES=hr.employees LOGFILE=empimport1.log

Managing Hanging issues----------------------------------------1. Connect to OEM as sys2.Click on the PErformance Tab3. Scroll down to additional monitoring links and click Blocking sessions.4.Click the Session id link5. Click on Previous SQL hash value.  Go back and kill session if required.

Database Auditing----------------------------

To enable auditing:1. connec to OEM as sys2. Click server tab3. Under Database Configuration region click Initialization parameters link.4. Click on SPFile tab5. Type the name audit in the name field and click go to view (AUDIT_TRAIL)6. Change the audit_trail parameter from db to xml7. Click Apply8. Restart the database to change the settings.

Steps to set the object for auditing:

Page 139: Oracle Notes

1. Click on the server tab2. Under Security region click Audit Settings link.3. Click on the Audited objects tab.4. Click Add button.5. Select the tables to be audited by clicking on the lookup icon.6. Move the required statements to be audited from available to selected statements list.7. Click OK to apply.

SQL> create user test15  2  identified by oracle;

User created.

SQL> grant connect to test15;

Grant succeeded.

SQL> grant insert, update, delete  2  on hr.jobs  3  to test15;

Grant succeeded.

SQL> grant select on hr.jobs to test15;

To monitor the audited objects--------------------------------------------1. On the OEM home, click on the server tab.2. Under security, click Audit Settings link3. Under Audit Trails region click Audited Objects link.

Note: to disable auditing, change the AUDIT_TRAIL parameter to NONE and restart the database.

MANAGING UNDO DATA--------------------------------------------

Page 140: Oracle Notes

Background: You need to create a user account for Jenny Goodman, the new humanresources department manager. There are also two new clerks in the human resourcesdepartment, David Hamby and Rachel Pandya. All three must be able to log in to theorcl database and to select data from, and update records in, the HR.EMPLOYEEStable. The manager also needs to be able to insert and delete new employee records.Ensure that if the new users forget to log out at the end of the day, they are automaticallylogged out after 15 minutes. You also need to create a new user account for the inventoryapplication that you are installing.In this practice, you create the INVENTORY user to own the new Inventory application.You create a profile to limit the idle time of users. If a user is idle or forgets to log outafter 15 minutes, the user session is ended.

sqlplus / as sysdba << EOFdrop user inventory cascade;create user inventory identified by verysecuredefault tablespace inventory;grant connect, resource to inventory;

Create a profile named HRPROFILE that allows only 15 minutes idle time.a) Invoke Enterprise Manager as the SYS user in the SYSDBA role for your orcldatabase.b) Click the Server tab, and then click Profiles in the Security section.

Page 141: Oracle Notes

c) Click the Create button.d) Enter HRPROFILE in the Name field.e) Enter 15 in the Idle Time (Minutes) field.f) Leave all the other fields set to DEFAULT.g) Click the Password tab, and review the Password options, which are currently allset to DEFAULT.h) Optionally, click the Show SQL button, review your underlying SQL statement,and then click Return.i) Finally, click OK to create your profile

Set the RESOURCE_LIMIT initialization parameter to TRUE so that your profilelimits are enforced.a) Click the Server tab, and then click Initialization Parameters in the DatabaseConfiguration section.b) Enter resource_limit in the Name field, and then click Go.c) Select TRUE from the Value drop-down list, and then click Apply.

Create the role named HRCLERK with SELECT and UPDATE permissions on theHR.EMPLOYEES table.a) Click the Server tab and then click Roles in the Security section.b) Click the Create button.c) Enter HRCLERK in the Name field. This role is not authenticated.d) Click Object Privileges tab.e) Select Table from the Select Object Type drop-down list, and then click Add.f) Enter HR.EMPLOYEES in the Select Table Objects field.g) Move the SELECT and UPDATE privileges to the Selected Privileges box. ClickOK.h) Click the Show SQL button, and review your underlying SQL statement.i) Click Return, and then click OK to create the role.

Create the role named HRMANAGER with INSERT and DELETE permissions on theHR.EMPLOYEES table. Grant the HRCLERK role to the HRMANAGER role.a) Click the Server tab, and then click Roles in the Security section.b) Click Create.c) Enter HRMANAGER in the Name field. This role is not authenticated.d) Click Object Privileges tab.e) Select Table from the Select Object Type drop-down list, and then click Add.

Page 142: Oracle Notes

f) Enter HR.EMPLOYEES in the Select Table Objects field.g) Move the INSERT and DELETE privileges to the Selected Privileges box. ClickOK.h) Click the Roles tab, and then click Edit List.i) Move the HRCLERK role into the Selected Roles box, and then click OK.j) Click the Show SQL button, and review your underlying SQL statement.k) Click Return, and then click OK to create the role.

MANAGING SCHEMA

MANAGING HANGING SESSIONS

The Help desk just received a call from Susan Mavris, an HRrepresentative, complaining that the database is “frozen.” Upon questioning the user, youfind that she was trying to update John Chen’s personnel record with his new phonenumber, but when she entered the new data, her session froze and she could not doanything else. SQL script files are provided for you in the /home/oracle/labsdirectory.

In this practice, you use two separate SQL*Plus sessions to cause a lock conflict. UsingEnterprise Manager, you detect the cause of the lock conflict and then resolve theconflict. For your convenience, the SQL code that will cause the lock conflict has beenprovided in scripts that you run during this practice.

1. run the lab_09_01.sql script. This script first creates the users (smavris andngreenberg) that are involved in this practice and the hremployee role that willgive these new users access to the hr.employee table. It then logs in to SQL*Plusas the ngreenberg user and performs an update on the hr.employee table. Thescript does not perform a commit, leaving the update uncommitted in this session.

Page 143: Oracle Notes

Leave this session connected in the state that it is currently. Do not exit at thistime.

Make an attempt to update the same row in a separate session by running, in aseparate terminal window, the lab_09_02.sql script. Make sure that you see themessage “Update is being attempted now” before moving on. Do not worry if thesession seems to “hang”—this is the condition that you are trying to create.

Notice that this session appears to be hung. Leave this session as is and move onto the next step.

Using Enterprise Manager, click the Blocking Sessions link on the Performance pageand detect which session is causing the locking conflict.a) In Enterprise Manager, click the Performance page.a) Select the NGREENBERG session, and then click View Session.b) Click the hash value link named “Previous SQL.”c) Note the SQL that was most recently run.a) Click the browser’s Back button.b) Now, on the Session Details: NGREENBERG page, click Kill Session.c) Leave the Options set to Kill Immediate, and then click Show SQL to see thestatement that is going to be executed to kill the session.d) Click Return, and then click Yes to carry out the KILL SESSION command.

Return to the SQL*Plus command window, and note that SMAVRIS’s update hasnow completed successfully. It may take a few seconds for the success message toappear.

MANAGING UNDO DATAThe business users and management in your organization decide, that theyneed to have a 48-hour retention of undo in the Oracle database to support their flashbackneeds. Your task is to configure the orcl database to support this requirement. In this practice, you first view your system activity regarding undo, and then youconfigure the orcl database to support 48-hour retention for flashback operations.

Page 144: Oracle Notes

1) In Enterprise Manage  r, as the DBA1 user, view the undo related system activity.a) Click the Server tabbed page and select “Automatic Undo Management” in theDatabase Configuration section.b) Click the System Activity tabbed page.Note: Your information will look different on all analysis screenshots, based on youranalysis period and the system activity during this period.c) Question: Looking at the preceding screenshot, how many errors did this systemencounter?Answer: Noned) Question: Looking at the preceding screenshot, what is the duration of the longestrunning query?Answer: 28 minutes (Your answer may be different.)e) Click the Plus icon to show related graphs.f) Question: How many graphs are displayed?Answer: Three. (Undo Tablespace Usage, Undo Retention Auto-Tuning, andUndo Generation Rate)g) Question: Looking at the preceding Undo Retention Auto-Tuning graph, couldthis system support flashback above and beyond the current longest runningquery?Answer: Yes, (but most likely not enough to support the required 48 hours).

2) Modify the undo retention time and calculate the undo tablespace size to support therequested 48-hour retention.a) Click the General tab to go back to the General Automatic Undo Managementpage.b) Under the Undo Advisor section, select “Specified manually to allow for longerduration queries or flashback.”c) Enter 48 hours as Duration and click the Run Analysis button.d) When the Undo Advisor is finished, take a look at the results.It looks like the undo tablespace is very close to the recommended undotablespace size. This is okay for most workloads, but the recommendation is to setyour undo tablespace size to be three times the minimum size. This means thatyou should change your undo tablespace size to be 846 MB.Note: Your recommended size might be different from what is shown here, soadjust the size accordingly.e) Click the Show SQL button in the upper-right corner of the General AutomaticUndo Management page.f) This command will change the undo retention to support the 48-hour requirement.Review the SQL statement and click Return.g) Click Apply to make the change to undo retention.h) Now adjust the undo tablespace size by clicking the Edit Undo Tablespace button.

Page 145: Oracle Notes

i) Scroll down to Datafiles and click Edit to make a change to theundotbs01.dgf file size.j) Change the file size to 846 MB and click Continue.k) Verify the SQL commands that will be executed by clicking Show SQL.Click Return.l) Click Apply to change the tablespace size.

3) Go back to the Automatic Undo Management to see the results of the changes youjust made. You see that the undo retention time has increased to support the 48 hoursrequirement. Your undo tablespace size has also increased based on the changes youmade to the size of the datafile for the undo tablespace.a) Question: Which Flashback operations are potentially affected by this change?Answer: Flashback query, Flashback transaction, and Flashback table.b) Question: Do undo data survive the shutdown of a database?Answer: Yes, undo is persistent.

AUDITINGBackground: You have just been informed of suspicious activities in the HR.JOBS tablein your orcl database. The highest salaries seem to fluctuate in a strange way. Youdecide to enable standard database auditing and monitor data manipulation language(DML) activities in this table.

Log in as the DBA1 user (with oracle password, connect as SYSDBA) and perform thenecessary tasks either through Enterprise Manager Database Control or throughSQL*Plus. All scripts for this practice are in the /home/oracle/labs directory.1) Use Enterprise Manager to enable database auditing. Set the AUDIT_TRAILparameter to XML.a) Invoke Enterprise Manager as the DBA1 user in the SYSDBA role for your orcldatabase.b) Click the Server tab, and then click Audit Settings in the Security section.c) Click the value of Audit Trail, the DB link.d) On the Initialization Parameters page, click the SPFile tab.e) Enter audit in the Name field and then click Go.f) For the audit_trail parameter, select the XML value.g) Click Show SQL.h) Review the statement and then click Return.i) On the Initialization Parameters page, click Apply.

Page 146: Oracle Notes

2) Because you changed a static parameter, you must restart the database. Do so byrunning the lab_11_02.sh script.a) In a terminal window, enter:b) Continue with the next step when you see that the database is restarted and thescript has exited SQL*Plus.

3) Back in Enterprise Manager, select HR.JOBS as the audited object and DELETE,INSERT, and UPDATE as Selected Statements. Gather audit information by session.Because the database has been restarted, you have to log in to Enterprise Manageragain as the DBA user.a) Click logout in the upper-right corner of the Enterprise Manager window.b) Log in as the DBA1 user in the SYSDBA role for your orcl database.c) Click the Database home page tab to ensure that Enterprise Manager had time toupdate the status of the database and its agent connections.d) Click the Server tab, and then click Audit Settings in the Security section.e) Click the Audited Objects tab at the bottom of the page, and then click the Addbutton.) On the Add Audited Object page, ensure that the Object Type is Table, and enterHR.JOBS in the Table field (or use the flashlight icon to retrieve this table).g) Move DELETE, INSERT, and UPDATE into the Selected Statements area bydouble-clicking each of them.h) Click Show SQL.i) Review the statement, and then click Return.j) Click OK to activate this audit.

4) Provide input for the audit, by executing the lab_11_04.sh script. This scriptcreates the AUDIT_USER user, connects to SQL*Plus as this user, and multiplies thevalues in the MAX_SALARY column by 10. Then the HR user connects and dividesthe column values by 10. Finally, the AUDIT_USER user is dropped again.a) In a terminal window, enter:

5) In Enterprise Manager, review the audited objects.a) Click the Server tab, and then click Audit Settings in the Security section.b) Click Audited Objects in the Audit Trails area, which is on the right side of thepage.c) On the Audited Objects page, review the collected information.Question: Can you tell which user increased and which user decreased thesalaries?Answer: No, the standard audit records only show which user accessed the table.d) Click Return.

Page 147: Oracle Notes

6) Undo your audit settings for HR.JOBS, disable database auditing, and then restart thedatabase by using the lab_11_06.sh script.a) On the Audit Settings page, click the Audited Objects tab at the bottom of thepage.b) Enter HR as Schema, and then click Search.c) Select all three rows, and then click Remove.d) On the Confirmation page, click Show SQL.e) Review the statements, and then click Yes to confirm your removal.f) On the Audit Settings page, click XML in the Configuration region.g) On the Initialization Parameters page, click the SPFile tab.h) On the SPFile page, enter audit in the Name field, and then click Go.i) For the audit_trail parameter, select the DB value.j) Click Show SQL.k) Review the statement, and then click Return.l) On the Initialization Parameters page, click Apply.m) Because you changed a static parameter, you must restart the database. Do so byrunning the lab_11_06.sh script. In a terminal window, enter:

7) Maintain your audit trail: Because you are completely finished with this task, backupand delete all audit files from the /u01/app/oracle/admin/orcl/adumpdirectory.a) In a terminal window, enter:b) Create a backup of the audit trail files, and then remove the filesc) Close the terminal window.

BACKUP and RECOVERYBackground: Your orcl database is ready to move from test or development intoproduction.Configure your database to reduce the chances of failure or data loss. To do so, performthe following tasks:• Ensure redundancy of control files and backup the control file to trace• Review the flash recovery area configuration• Ensure that there are at least two redo log members in each group• Place your database in ARCHIVELOG mode• Configure redundant archive log destinations

In this practice, you configure your database to reduce the chances of failure or data loss.Note: Completing this practice is a prerequisite for all following backup and recovery

Page 148: Oracle Notes

practices.1) Verify that you have at least two control files to ensure redundancy and backup thecontrol file to trace.a) Invoke Enterprise Manager as the DBA1 user in the SYSDBA role for your orcldatabase.b) Click Server > Control Files (in the Storage section).Question 1: On the Control Files: General page, how many control files do youhave?Answer: Three (in the preceding example).Question 2: How would you add another control file if you needed to?Answer: Adding a control file is a manual operation. To perform this, you must:• Shut down the database• Use the operating system to copy an existing control file to the location whereyou want your new file to be.• Start the database by using Enterprise Manager. Unlike a normal startup, youwould use Advanced Options to select a different startup mode. Select “Startthe instance” to leave the instance in the NOMOUNT state.• Edit the CONTROL_FILES initialization parameter to point to the newcontrol file.• Continue the STARTUP database operation until the database is in an openstate.Note••This answer does not apply to an OMF database because the control files inthat case would have to all be re-created.Alternatively, if you did not want to use Enterprise Manager to perform thesteps, you could perform the steps outlined in the Multiplexing Control Filesslide in the “Backup and Recover Concepts” lesson.c) Click Backup to Trace.d) When you receive the success message, note the trace directory location, and thenclick OK.e) Optionally, use a terminal window, logged in as the oracle user to view thetrace file name at the end of the alert log by executing the following command:cd /u01/app/oracle/diag/rdbms/orcl/orcl/tracetail alert_orcl.logThe following output shows only the last few lines:f) Optionally, to view size and usage of the different sections within the control file,click the Record Section tabbed page.Your numbers could look different. For additional information, click Help in theupper-right corner of the page.

Page 149: Oracle Notes

2) Review the flash recovery area configuration and change the size to 8 GB.a) In Enterprise Manager, select Availability > Recovery Settings in the Setupsection.b) Scroll to the bottom of the page.c) Question: Is the flash recovery area enabled?Answer: Yes, by default.d) Note the location of the flash recovery area.For example: /u01/app/oracle/flash_recovery_areae) Question: Which essential DBA tasks can you perform in this section?Answer: You can change the location, size or retention time for the flash recoveryarea, as well as enable the Flashback Database functionality.f) Question: Does changing the size of the flash recovery area require the databaseto be restarted?Answer: No, a restart is not required for this change.g) Change the size of the Flash Recovery Area to 8 GB, by entering 8 into the“Flash Recovery Area Size” field.h) Optionally, click Show SQL, review the statement and click Return.i) Click Apply.

3) Check how many members each redo log group has. Ensure that there are at least tworedo log members in each group. One set of members should be stored in the flashrecovery area.a) Click Server > Redo Log Groups, and note how many members are in the “# ofMembers” column.Answer: There is only one member in each group.b) To add a member to each group, perform the following steps for each group:i) Select the group (for example, 1) and click the Edit button.ii) On the Edit Redo Log Group page, note the File Name, for example“redo01.log” and click the Add button.iii) On the Edit Redo Log Group: Add Redo Log Member page, enter a file nameby adding the letter “b” to the end of the name (before the dot). For example,enter redo01b.log as File Name and enter your flash recovery area, forexample, /u01/app/oracle/flash_recovery_area/ as FileDirectory.iv) Click Continue.v) On the Edit Redo Log Group page, review the current members.Note: If you forget to add the last slash to the directory name, the system doesit for you.vi) Optionally, click Show SQL to review the command, and then Return.vii) Click Apply.viii) You should receive a success message. Return to the Redo Log Groups page

Page 150: Oracle Notes

and repeat the preceding sequence of steps (under 3 b) for each of theremaining redo log groups.c) You are finished with this task, when the # of members displays 2 for each group.Note: In a production database, you want to ensure that the two members are ondifferent hard drives, preferably with different disk controllers, to minimize therisk of any single hardware failure destroying an entire log group.

4) You notice that, for each log group, the Archived column has a value of No. Thismeans that your database is not retaining copies of redo logs to use for databaserecovery, and in the event of a failure, you will lose all data since your last backup.Place your database in ARCHIVELOG mode, so that redo logs are archived.Note: You must continue with step 5, so that your changes are applied.a) In Enterprise Manager, select Availability > Recovery Settings in the Setupsection.b) In the Media Recovery region, select the ARCHIVELOG Mode check box.c) Verify that Log Archive Filename Format contains %t, %s, and %r.d) Notice the current configuration of redundant archive log destinations—one to theflash recovery area and the other to/u01/app/oracle/product/11.1.0/db_1/dbs/arch. The databaseis preconfigured to save archived logs to the flash recovery area (Archive LogDestination 10), as well as to a redundant location (Archive Log Destination 1).Note: If you add archive log destinations, you must create the directory, if it doesnot already exist.e) Click Apply.f) When prompted whether you want to restart the database now, click Yes.g) Enter the credentials to restart the database (oracle as the Host Credentials, andsys/oracle as SYSDBA as Database Credentials), and then click OK.h) When asked to confirm, click Yes again.i) Should you receive an error during the shutdown and startup activity, click OK toacknowledge the error, and then click Refresh again. (You might have beensimply faster than the database.)

5) Optionally, use SQL*Plus to check whether your database is in ARCHIVELOG mode.In a terminal window, log in to SQL*Plus as SYSDBA and run the archive loglist command.Now that your database is in ARCHIVELOG mode, it will continually archive a copyof each online redo log file before reusing it for additional redo data.Note: Remember that this consumes space on the disk and that you must regularlyback up older archive logs to some other storage.

Page 151: Oracle Notes

Your database is ready to move from development and testing intoproduction. Ensure that your database is configured so that recovery is possible withoutloss of data. Establish the backup policy to automatically back up the SPFILE andcontrol file. Perform an immediate backup to disk and schedule nightly backup jobs thatrepeat indefinitely.In this practice, you perform an immediate backup to disk and schedule a nightly backupjob.1) What is the difference between a backup set and an image copy?Answer: A backup set contains data and archive log files packed in an Oracleproprietary format. Files must be extracted before use. Image copies are theequivalent of operating system file copies and can be used for restore operationsimmediately.2) What is the destination of any disk backups that are done?a) Log in to Enterprise Manager as the DBA1 user in the SYSDBA role and selectAvailability > Backup Settings.b) Note the message under the Disk Backup Location that says the flash recoveryarea is the current disk backup location.3) Establish the backup policy to automatically back up the SPFILE and control file.a) Click the Policy tab under the Backup Settings pages.b) Click Automatically backup the control file and server parameter file(SPFILE) with every backup and database structural change.c) Scroll to the bottom and enter oracle and oracle for Host CredentialsUsername and Password for your server, and click “Save as PreferredCredential.”4) Test making a backup to disk, as a backup set, with oracle for Host Credentials.a) Click the Device tab under the Backup Settings pages.b) Select Backup Set as your Disk Backup Type.c) Scroll to the bottom and ensure the Host Credentials are set to oracle.d) Scroll to the top of the page and click Test Disk Backup.e) A processing message appears. When the test finishes, and you see the ‘DiskBackup Test Successful!’ message, click OK.5) Back up your entire database, with archive logs, while the database is open for useractivity. This backup should be the base for an incremental backup strategy.a) Question: What prerequisite must be met to create a valid backup of a databasewithout shutting it down?Answer: The database must be in ARCHIVELOG mode. Backups made with thedatabase open, but not in ARCHIVELOG mode, cannot be used for recovery.b) Select Availability > Schedule Backup (in the Manage section).If you find that the Oracle-Suggested Backup strategy fits your needs exactly, you

Page 152: Oracle Notes

would chose this option. For practice purposes, you will schedule a customizedbackupc) Select Whole Database as the object to be backed up.d) Confirm or enter oracle and oracle for Host Credentials Username andPassword for your server.e) Click Schedule Customized Backup.f) On the Schedule Customized Backup: Options page, select Full Backup for yourBackup Type, and select the Use as the base of an incremental backup strategycheck box.g) Select Online Backup as Backup Mode.h) In the Advanced section, select “Also back up all archived logs on disk” and“Delete all archived logs from disk after they are successfully backed up”,and then click Next to continue.i) On the Schedule Customized Backup: Settings page, select Disk for your backuplocation. (Notice that your Disk Backup Location is retained and that you couldoverride the current settings for a one-off backup. But do not click it this time.)j) Click Next.k) Accept all the defaults on the Schedule Customized Backup: Schedule page andthen click Next to continue.Note: Schedule Type should be One Time (Immediately).l) On the Schedule Customized Backup: Review page, review the RMAN script,and then click Submit Job.m) Click View Job to monitor the status of the backup job. The time for this backupdepends on your hardware and system resources.n) Click your browser’s Refresh or Requery button until the job is completed.6) Schedule nightly disk-based incremental online backups for your whole database,without archived logs. Schedule it for execution at 11:00 PM. The schedule should bein effect indefinitely.a) In Enterprise Manager, select Availability > Schedule Backup (in the Managesection).b) Select Whole Database as the object to be backed up.c) Confirm or enter oracle and oracle for Host Credentials Username andPassword for your server, and then click Schedule Customized Backup.d) On the Schedule Customized Backup: Options page, select Incremental Backupas your Backup Type.e) Select Online Backup as Backup Mode.f) In the Advanced region, select “Also backup all archived logs on disk” and“Delete all archived logs from disk after they are successfully backed up”,and then click Next to continue.g) On the Schedule Customized Backup: Settings page, select Disk as your backuplocation, and then click Next to continue.

Page 153: Oracle Notes

h) On the Schedule Customized Backup: Schedule page, change Job Name toNightly_Backup and accept the default value for Job Description.i) Select Repeating in the Schedule region. Notice how additional context sensitivedetails are displayed.j) Select By Days from the Frequency Type drop-down list, enter 1 in the RepeatEvery field, confirm that Indefinite is selected as the Repeat Until value, and enter11:00 PM as Time.k) Click Next to continue.l) On the Schedule Customized Backup: Review page, review your Settings andRMAN script.m) Click Submit Job, and then click OK.n) Click Jobs on the Availability page in the Related Links section to see thescheduled job in the Job Activity list.

Many failures of the Oracle database can be traced to some sort of mediafailure, such as disk or controller failure. In this practice, you encounter a number ofproblems from which you need to recover the database.• Recover from the loss of a control file• Recover from the loss of a data file• Recover from the loss of a redo log member• Recover from the loss of a file in the SYSTEM tablespaceSQL script files are provided for you in the /home/oracle/labs directory. Ifneeded, use the appendixes for Linux and for SQL syntax. After you set up a failure witha SQL script, you must complete the recovery before continuing with any other practice.Note: Your system may have different OS file names than shown here. Your outputmight look different. (To conserve space, blank lines have been removed.)

Before beginning one of the recovery scenarios, you need to run a script that will preparethe environment for the remaining recovery practices.1) Before setting up an individual problem, you need to navigate to your labs directoryand (in SQL*Plus) execute the lab_16_01.sql script as the SYS user. This scriptprepares some procedures to be called by the rest of this practice.In this practice, your system experiences the loss of a control file. You then go throughthe steps to recover from this loss.1) Continue in your SQL*Plus session as the SYS user. Execute the lab_16_02.sqlscript. This script deletes one of your control files.

Page 154: Oracle Notes

2) The Help desk begins receiving calls saying that the database appears to be down.Troubleshoot and recover as necessary. Use Enterprise Manager to try to start up thedatabase, and use SQL*Plus if needed.a) In Enterprise Manager, navigate to the Database home page. It reports that thedatabase is down and offers you the chance to start it up again.Note: you may see a message stating ‘Internal Error has occurred.’ If so, keeptrying to connect to using the Enterprise Manager URL. Eventually it will displaythe database home page.b) Click Startup. If you see a Connection Refused message, ignore it; the connectionwill eventually be established.c) Enter oracle as Username and Password for Host Credentials and click OK.d) Click Yes to confirm your attempted startup.e) The startup of the instance fails with Enterprise Manager. Click View Details formore information.f) Note the following, and then click OK:ORA-00205: error in identifying control file, check alertlog for more infog) Alternatively, in a new SQL*Plus session, check the current status of the instanceas the SYS user and attempt to mount it with the following commands:select status from v$instance;alter database mount;3) The instance cannot move to the mount stage because it cannot find one of the controlfiles. To find the locations of the alert log and of diagnostic information, enter thefollowing SELECT statement:SELECT NAME, VALUE FROM V$DIAG_INFO;4) Look at the last 25 lines in the log.xml file to see if you can find out what theproblem is. Still inside your SQL*Plus session, enter the following command (on oneline):host tail -25/u01/app/oracle/diag/rdbms/orcl/orcl/alert/log.xml5) Note that in the preceding example, the control02.ctl file is missing. Thismight be different in your environment. Restore the control file that is missing foryour database by copying an existing control file. Enter the following command withyour correct file names (on one line):host cp /u01/app/oracle/oradata/orcl/control01.ctl/u01/app/oracle/oradata/orcl/control02.ctl6) (Optional) To view the content of the directory, enter:host ls /u01/app/oracle/oradata/orcl7) Now mount and open the database with the following commands:connect / as sysdbaalter database mount;

Page 155: Oracle Notes

alter database open;a) Why did you have to use two commands to move the instance state fromNOMOUNT to OPEN?Answer: Because the ALTER DATABASE command enables you to change onlyone state level for each commandb) Why did you use operating system commands to restore the control file instead ofusing Oracle Recovery Manager?Answer: Because all control files are identical. As long as any one control file isintact, it can be used to restore the others.8) Exit all sessions and close all windows

Recovering from the Loss of a Data File

1) In a SQL*Plus session, as the SYS user, execute the lab_16_03.sql script fromyour labs directory. This script deletes one of your application data files.2) The Help desk has received a call from a user who is unable to access theCOUNTRIES table in the HR application schema. Count the rows in the table todetermine whether there is a problem.3) Troubleshoot and recover as necessary. The error message suggests that theexample01.dbf data file is corrupt or missing.a) In Enterprise Manager, click Availability > Perform Recovery.b) Click Advise and Recover.c) On the View and Manage Failures page, click the plus (+) icon under the failuredescription. You should see a failure like the following:Note: If you do not see the nonsystem datafile failure, keep refreshing the pageuntil it shows up.d) With the failures selected, click Advise.e) Because the file was not just renamed or moved, but deleted, you continue byclicking “Continue with Advise.”f) On the Recovery Advise page, you see the RMAN script. Click Continue.g) On the Review page, you see the failure and the suggested solution. Click“Submit Recovery Job.”h) A Processing window appears, followed by the Job Activity page. You should seea message that the job was successfully created. (Your link name is probablydifferent.)i) Click the job name link.j) On the Job Run page, check the Status in the Summary section. If it is Running,use you browser’s Refresh or Requery button until the job is completed.k) In your SQL*Plus session, verify that the HR.COUNTRIES table is now

Page 156: Oracle Notes

accessible.

In this practice, your system experiences the loss of a redo log member. You then gothrough the steps to recover from this loss.1) Make sure that you are in your labs directory. Using SQL*Plus, execute thelab_16_04.sql script as the SYS user. The lab_16_04.sql script deletes oneof your redo log files. See the error in the alert log and recover from it.2) The database continues to function normally, and no users are complaining. Log in toEnterprise Manager with the DBA1 username as SYSDBA. On the Database homepage, view alerts similar to the following ones:If you do not see similar alerts, you may need to wait a few minutes and refresh thepage. One of the failures listed may be left over from the data file recovery youperformed in the previous practice.3) Click Availability > Perform Recovery (in the Manage section).4) On the Perform Recovery page, you see the Failure Description and could directlybegin correcting the failure. But for practice purposes, you follow the steps in theData Recovery Advisor. Scroll down and ensure that your host credentials are set(oracle for both username and password). Then click the “Advise and Recover”button (which is one of the ways to invoke the Data Recovery Advisor).5) On the View and Manage Failures page, ensure that the failure is selected, and clickAdvise.6) The Manual Actions page suggests to manually restore it. In the preceding example,redo03.log is deleted. Do not click any button at this point in time.7) In a new terminal window, as the oracle user, copy an existing redo log from thesame redo log group to the missing file.Note: The actual redo log member that was lost on your machine may be differentthan the one shown here. Make sure that you are replacing the file names asappropriate for your failure.cd /u01/app/oracle/oradata/orcllscp /u01/app/oracle/flash_recovery_area/redo02b.log redo02.loglsexit8) Now return to your Manual Actions page in Enterprise Manager and click the Re-assess Failures button.a) Note that there are now no failures found.b) Question: Why did the database not crash?Answer: Because a single missing member is noncritical and does not affect the

Page 157: Oracle Notes

operation of the database. As long as there is at least one good member for eachlog group, the database operation continues.In this practice, your system experiences the loss of a file in the SYSTEM tablespace. Youthen go through the steps to recover from this loss.1) Why is recovery from the loss of a system data file or a data file belonging to an undotablespace different from recovering an application data file?Answer: Because recovery of system or undo data files must be done with thedatabase closed, whereas recovery of an application data file can be done with thedatabase open and available to users2) As the SYS user, execute the lab_16_05.sql script in your labs directory. Thisscript deletes the system data file.3) In Enterprise Manager, review the Database home page. If you see a message thatsays the connection was refused, dismiss it and reenter the EM home page URL in thebrowser. You may need to try several times before you see the Database home page.4) The database is shut down. Attempt to start your database.a) Click Startup to try to open it.b) On the ‘”Startup/Shutdown:Specify Host and Target Database Credentials” page,enter oracle and oracle as Host Credentials. Click OK.c) On the Startup/Shutdown:Confirmation page, click Yes.d) A progress page appears, followed by an error message.5) Note that the database is in a mounted state. Click Perform Recovery.a) Enter oracle and oracle as Host Credentials, and click Continue.b) On the Database Login page, enter DBA1, oracle, and SYSDBA and clickLogin.6) On the Perform Recovery page, you could select the Oracle Advised Recovery, butfor practice purposes, continue with a User Directed Recovery.a) In the User Directed Recovery section, select Datafiles from the Recovery Scopedrop-down list and “Recover to current time” as Operation Type.b) Scroll down and enter oracle and oracle as Host Credentialsc) Click Recover.d) On the Perform Object Level Recovery: Datafiles page, you should see themissing data file. Click Next.e) Because the problem is simply a deleted file rather than a bad hard drive, there isno need to restore to a different location. Select “No. Restore the files to thedefault location” and then click Next.f) On the Perform Object Level Recovery: Review page, view your current optionsand the data file. Click Edit RMAN Script to review the RMAN commands.g) Review the RMAN commands and click Submit.h) A processing page appears, followed by the Perform Recovery: Result page. Theduration of this operation depends on your system resources. The recoveryoperation should be successful.

Page 158: Oracle Notes

i) On the Perform Recovery: Result page, click Open Database.j) After you see the success message, click OK.k) Verify that the database is open and operating normally by logging in to EM asyour DBA1 user as SYSDBA, and reviewing the Database home page.

EXPORTING/IMPORTINGn the recent past, you received a number of questions about the HRschema. To analyze them without interfering in daily activities, you decide to use theData Pump Wizard to export the HR schema to file. When you perform the export, youare not sure into which database you will be importing this schema.In the end, you learn that the only database for which management approves an import isthe orcl database. So you perform the import with the Data Pump Wizard, remappingthe HR schema to DBA1 schema.Then you receive two data load requests for which you decide to use SQL*Loader.In this practice, you first grant the DBA1 user the privileges necessary to provide accessto the DATA_PUMP_DIR directory. You then export the HR schema so that you can thenimport the tables you want into the DBA1 schema. In the practice, you import only theEMPLOYEES table at this time.1) First, you need to grant the DBA1 user the appropriate privileges on theDATA_PUMP_DIR directory and create the users and roles required for this practice.A script exists that performs all the steps required to configure your environment forthis practice.a) Review the lab_17_01.sql script, which grants the DBA1 user privileges onthe DATA_PUMP_DIR directory and performs other configurations to yourenvironment, by executing the following in your labs directory:$ cat lab_17_01.sqlb) The lab_17_01.sh script calls the lab_17_01.sql script. Execute thelab_17_01.sh script now:2) Log in to Enterprise Manager as the DBA1 user in the Normal role and export theHR schema.a) Invoke Enterprise Manager as the DBA1 user as the Normal role for your orcldatabase. The Connect As setting should be Normal.b) Select Data Movement > Move Row Data > Export to Export Files.c) Select Schemas, enter oracle as Username and Password, select Save asPreferred Credential, and then click Continue.d) On the Export: Schemas page, click Add, select the HR schema, and then click theSelect button.e) You see that HR is now in the list of schemas. Click Next.

Page 159: Oracle Notes

f) On the “Export: Options” page, select DATA_PUMP_DIR from the DirectoryObjects drop-down list, and enter hrexp.log as Log File.g) Review Advanced Options (but do not change), and then click Next.h) On the “Export: Files” page, select DATA_PUMP_DIR from the DirectoryObject drop-down list, enter HREXP%U.DMP as File Name, and then click Next.i) On the “Export: Schedule” page, enter hrexp as Job Name and Export HRschema as Description, accept the immediate job start time, and then clickNext.j) On the “Export: Review” page, click Show PL/SQL and review the PL/SQL thatthe Export Wizard helped you to create.k) Click Submit Job to submit the job.l) Click the link to the HREXP job to monitor the progress. When the job shows assuccessfully completed, move on to the next step.3) Now, import the EMPLOYEES table from the exported HR schema into the DBA1schema. To get a feeling for the command-line interface, you can use the impdputility from the command line to import the EMPLOYEES table into the DBA1 userschema.a) Enter the following entire command string. Do not press [Enter] before reachingthe end of the command:impdp dba1/oracle DIRECTORY=data_pump_dir DUMPFILE=HREXP01.DMP REMAP_SCHEMA=hr:dba1 TABLES=employees LOGFILE=empimport.logNote: You may see errors on constraints and triggers not being created because onlythe EMPLOYEES table is imported and not the other objects in the schema. Theseerrors are expected.b) You can also verify that the import succeeded by viewing the log file.$ cat /u01/app/oracle/admin/orcl/dpdump/empimport.log4) Confirm that the EMPLOYEES table has been loaded into the DBA1 schema bylogging in to SQL*Plus as the DBA1 user and selecting data from the EMPLOYEEStable.a) Log in to SQL*Plus as the DBA1 user.b) Select a count of the rows from the EMPLOYEES table in the DBA1 schema, forverification of the import.

In this practice, you load data into the PRODUCT_MASTER table by using SQL*Loadervia Enterprise Manager Database Control. Data and control files are provided.1) As the DBA1 user, use Enterprise Manager to load the lab_17_02_01.dat datafile. This data file contains rows of data for the PRODUCT_MASTER table. Thelab_17_02_01.ctl file is the control file for this load.Optionally, view the lab_17_02_01.dat and lab_17_02_01.ctl files tolearn more about their structure before going further.

Page 160: Oracle Notes

a) Invoke Enterprise Manager as the DBA1 user as the Normal role for your orcldatabase.b) Select Data Movement > Move Row Data > Load Data from User Files.c) Click Use Existing Control File. If not already entered, enter oracle asUsername and as Password, click Save as Preferred Credential, and then clickContinue.d) On the “Load Data: Control File” page, enter/home/oracle/labs/lab_17_02_01.ctl as the control file name andpath, or use the flashlight icon to select this control file. Click Next.e) On the “Load Data: Data File” page, click Provide the full path and name onthe database server machine and enter/home/oracle/labs/lab_17_02_01.dat as the data file name and path,or use the flashlight icon to select this data file. Click Next.f) On the “Load Data: Load Method” page, select Conventional Path, and thenclick Next.g) On the “Load Data: Options” page, accept all defaults, but enter/home/oracle/labs/lab_17_02_01.log as the log file name and path.Review the advanced options if you want, but do not change any, and then clickNext.h) On the “Load Data: Schedule” page, enter lab_17_02_01 as Job Name andLoad data into the PRODUCT_MASTER table as Description. Let thejob start immediately, and then click Next.i) On the “Load Data: Review” page, review the loading information andparameters, and then click Submit Job.j) Click the link to the LAB_17_02_01 job to monitor the progress. After the jobshows as successfully completed, move on to the next step.k) Confirm your results by viewing your lab_17_02_01.log file in your/home/oracle/labs directory.2) As the INVENTORY user, load data into the PRODUCT_ON_HAND table by usingSQL*Loader command line. The lab_17_02_02.dat data file contains rows ofdata for the PRODUCT_ON_HAND table. The lab_17_02_02.ctl file is thecontrol file for this load.Optionally, view the lab_17_02_02.dat and lab_17_02_02.ctl files tolearn more about their structure before going further.a) Open a terminal window and navigate to the /home/oracle/labs directory.b) Enter the following SQL*Loader command (in continuation, without pressing[Enter] before reaching the end of the command):sqlldr userid=inventory/verysecure control=lab_17_02_02.ctllog=lab_17_02_02.log data=lab_17_02_02.datc) Confirm your results by viewing your lab_17_02_02.log file in your/home/oracle/labs directory.

Page 161: Oracle Notes

Adding a Column•You use the ADD clause to add columns.ALTER TABLE dept80ADD(job_id VARCHAR2(9));Table altered.•The new column becomes the last column.

Modifying a Column•You can change a column’s data type, size, anddefault value.ALTER TABLE dept80MODIFY(last_name VARCHAR2(30));Table altered.•A change to the default value affects onlysubsequent insertions to the table.

Dropping a ColumnUse the DROP COLUMN clause to drop columns you nolonger need from the table.ALTER TABLE dept80DROP COLUMN job_id;Table altered.

The SET UNUSED Option• You use the SET UNUSED option to mark one ormore columns as unused.• You use the DROP UNUSED COLUMNS option toremove the columns that are marked as unused.

Page 162: Oracle Notes

ALTER TABLE <table_name>SET UNUSED(<column_name>);ORALTER TABLE <table_name>SET UNUSED COLUMN <column_name>;

ALTER TABLE <table_name>DROP UNUSED COLUMNS;

Adding a Constraint SyntaxUse the ALTER TABLE statement to:• Add or drop a constraint, but not modify itsstructure• Enable or disable constraints• Add a NOT NULL constraint by using the MODIFYclause

ALTER TABLE <table_name>ADD [CONSTRAINT <constraint_name>]type (<column_name>);

Adding a ConstraintAdd a FOREIGN KEY constraint to the EMP2 tableindicating that a manager must already exist as a validemployee in the EMP2 table.ALTER TABLE emp2modify employee_id Primary Key;Table altered.ALTER TABLE emp2ADD CONSTRAINT emp_mgr_fkFOREIGN KEY(manager_id)REFERENCES emp2(employee_id);Table altered.

ON DELETE CASCADEDelete child rows when a parent key is deleted.ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fkFOREIGN KEY (Department_id)

Page 163: Oracle Notes

REFERENCES departments ON DELETE CASCADE);Table altered.

Deferring ConstraintsConstraints can have the following attributes:• DEFERRABLE or NOT DEFERRABLE• INITIALLY DEFERRED or INITIALLY IMMEDIATEALTER TABLE dept2ADD CONSTRAINT dept2_id_pkPRIMARY KEY (department_id)DEFERRABLE INITIALLY DEFERRED

Deferring constraint on creationSET CONSTRAINTS dept2_id_pk IMMEDIATE

ALTER SESSIONSET CONSTRAINTS= IMMEDIATE

Dropping a Constraint• Remove the manager constraint from the EMP2table.ALTER TABLE emp2DROP CONSTRAINT emp_mgr_fk;Table altered.

• Remove the PRIMARY KEY constraint on theDEPT2 table and drop the associated FOREIGNKEY constraint on the EMP2.DEPARTMENT_IDcolumn.ALTER TABLE dept2DROP PRIMARY KEY CASCADE;Table altered.

Disabling Constraints• Execute the DISABLE clause of the ALTER TABLEstatement to deactivate an integrity constraint.

Page 164: Oracle Notes

• Apply the CASCADE option to disable dependentintegrity constraints.

ALTER TABLE emp2DISABLE CONSTRAINT emp_dt_fk;Table altered.

Enabling Constraints• Activate an integrity constraint currently disabledin the table definition by using the ENABLE clause.ALTER TABLEemp2ENABLE CONSTRAINT emp_dt_fk;Table altered.•  A UNIQUE index is automatically created if youenable a UNIQUE key or PRIMARY KEY constraint.

Cascading Constraints• The CASCADE CONSTRAINTS clause is used alongwith the DROP COLUMN clause.• The CASCADE CONSTRAINTS clause drops allreferential integrity constraints that refer to theprimary and unique keys defined on the droppedcolumns.• The CASCADE CONSTRAINTS clause also drops allmulticolumn constraints defined on the droppedcolumns.

ALTER TABLE emp2DROP COLUMN employee_id CASCADE CONSTRAINTS;Table altered.ALTER TABLE test1DROP (pk, fk, col1) CASCADE CONSTRAINTS;

Overview of IndexesIndexes are created:

Page 165: Oracle Notes

• Automatically– PRIMARY KEY creation– UNIQUE KEY creation•Manually– CREATE INDEX statement– CREATE TABLE statement

CREATE INDEX with CREATE TABLEStatementCREATE TABLE NEW_EMP(employee_id NUMBER(6)PRIMARY KEY USING INDEX(CREATE INDEX emp_id_idx ONNEW_EMP(employee_id)),first_name VARCHAR2(20),last_nameVARCHAR2(25));Table created.SELECT INDEX_NAME, TABLE_NAMEFROMUSER_INDEXESWHERE TABLE_NAME = 'NEW_EMP';

Function-Based Indexes• A function-based index is based on expressions.• The index expression is built from table columns,constants, SQL functions, and user-definedfunctions.

CREATE INDEX upper_dept_name_idxON dept2(UPPER(department_name));Index created.SELECT *FROM dept2WHERE UPPER(department_name) = 'SALES';

Removing an Index

Page 166: Oracle Notes

• Remove an index from the data dictionary byusing the DROP INDEX command.DROP INDEX index;• Remove the UPPER_DEPT_NAME_IDX index fromthe data dictionary.DROP INDEX upper_dept_name_idx;Index dropped.• To drop an index, you must be the owner of theindex or have the DROP ANY INDEX privilege.

DROP TABLE ... PURGEDROP TABLE dept80 PURGE;

The FLASHBACK TABLE StatementDROP TABLE emp2;Table droppedSELECT original_name, operation, droptime,FROM recyclebin;FLASHBACK TABLE emp2 TO BEFORE DROP;

External TablesCreating a Directory for the External TableCreate a DIRECTORY object that corresponds to thedirectory on the file system where the external datasource resides.CREATE OR REPLACE DIRECTORY emp_dirAS '/.../emp_dir';GRANT READ ON DIRECTORY emp_dir TO hr;

CREATE TABLE oldemp (fname char(25), lname CHAR(25))ORGANIZATION EXTERNAL(TYPE ORACLE_LOADERDEFAULT DIRECTORY emp_dirACCESS PARAMETERS(RECORDS DELIMITED BY NEWLINENOBADFILENOLOGFILEFIELDS TERMINATED BY ','

Page 167: Oracle Notes

(fname POSITION ( 1:20) CHAR,lname POSITION (22:41) CHAR))LOCATION ('emp.dat'))PARALLEL 5REJECT LIMIT 200;

You can use subqueries in DML statements to:• Copy data from one table to another• Retrieve data from an inline view• Update data in one table based on the values ofanother table• Delete rows from one table based on rows in aanother table

Copying Rows from Another Table

Write your INSERT statement with a subquery.INSERT INTO sales_reps(id, name, salary, commission_pct)SELECT employee_id, last_name, salary, commission_pctFROMemployeesWHERE job_id LIKE '%REP%';33 rows created.•Do not use the VALUES clause.•Match the number of columns in the INSERTclause with that in the subquery.

Inserting Using a Subquery as a TargetINSERT INTO(SELECT employee_id, last_name,email, hire_date, job_id, salary,department_idFROMempl3WHERE department_id = 50)VALUES (99999, 'Taylor', 'DTAYLOR',TO_DATE('07-JUN-99', 'DD-MON-RR'),'ST_CLERK', 5000, 50);

Page 168: Oracle Notes

Inserting Using a Subquery as a TargetVerify the results.SELECT employee_id, last_name, email, hire_date,job_id, salary, department_idFROMemployeesWHERE department_id = 50;

Retrieving Data with a Subquery as SourceSELECT a.last_name, a.salary,a.department_id, b.salavgFROM employees a, (SELECT department_id, AVG(salary) salavg FROM employees GROUP BY department_id) bWHERE  a.department_id = b.department_idAND a.salary > b.salavg;

Updating Two Columns with a SubqueryUpdate the job and salary of employee 114 to matchthe job of employee 205 and the salary of employee168.UPDATESETempl3job_id= (SELECT job_idFROMemployeesWHEREemployee_id = 205),salary = (SELECT salaryFROMemployeesWHEREemployee_id = 168)WHEREemployee_id= 114;

Page 169: Oracle Notes

Updating Rows Basedon Another TableUse subqueries in UPDATE statements to update rowsin a table based on values from another table.UPDATE empl3SET department_idWHERE job_id= (SELECT department_idFROM employeesWHERE employee_id = 100)= (SELECT job_idFROM employeesWHERE employee_id = 200);

Deleting Rows Basedon Another TableUse subqueries in DELETE statements to remove rowsfrom a table based on values from another table.DELETE FROM empl3WHERE department_id =(SELECT department_idFROMdepartmentsWHERE department_nameLIKE '%Public%');

Using Explicit Default Values•DEFAULT with INSERT:INSERT INTO deptm3(department_id, department_name, manager_id)VALUES (300, 'Engineering', DEFAULT);•DEFAULT with UPDATE:

Page 170: Oracle Notes

UPDATE deptm3SET manager_id = DEFAULTWHERE department_id = 10;

Types of Multitable INSERT StatementsThe different types of multitable INSERT statementsare:• Unconditional INSERT• Conditional ALL INSERT• Conditional FIRST INSERT• Pivoting INSERT

Unconditional INSERT ALL•Select the EMPLOYEE_ID, HIRE_DATE, SALARY, andMANAGER_ID values from the EMPLOYEES table forthose employees whose EMPLOYEE_ID is greaterthan 200.• Insert these values into the SAL_HISTORY andMGR_HISTORY tables using a multitable INSERT.

INSERT ALLINTO sal_history VALUES(EMPID,HIREDATE,SAL)INTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID, hire_date HIREDATE,salary SAL, manager_id MGRFROM employeesWHERE employee_id > 200;

Conditional INSERT ALL• Select the EMPLOYEE_ID, HIRE_DATE, SALARY, andMANAGER_ID values from the EMPLOYEES table forthose employees whose EMPLOYEE_ID is greaterthan 200.• If the SALARY is greater than $10,000, insert thesevalues into the SAL_HISTORY table using aconditional multitable INSERT statement.• If the MANAGER_ID is greater than 200, insert these

Page 171: Oracle Notes

values into the MGR_HISTORY table using aconditional multitable INSERT statement.

Conditional INSERT ALLINSERT ALLWHEN SAL > 10000 THENINTO sal_history VALUES(EMPID,HIREDATE,SAL)WHEN MGR > 200THENINTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID,hire_date HIREDATE,salary SAL, manager_id MGRFROMemployeesWHERE employee_id > 200;

Conditional INSERT FIRST•Select the DEPARTMENT_ID, SUM(SALARY), andMAX(HIRE_DATE) from the EMPLOYEES table.•If the SUM(SALARY) is greater than $25,000, theninsert these values into the SPECIAL_SAL, using aconditional FIRST multitable INSERT.•If the first WHEN clause evaluates to true, then thesubsequent WHEN clauses for this row should beskipped.•For the rows that do not satisfy the first WHENcondition, insert into the HIREDATE_HISTORY_00,HIREDATE_HISTORY_99, or HIREDATE_HISTORYtables, based on the value in the HIRE_DATEcolumn using a conditional multitable INSERT.

Conditional INSERT FIRSTINSERT FIRSTWHEN SAL > 25000THENINTO special_sal VALUES(DEPTID, SAL)

Page 172: Oracle Notes

WHEN HIREDATE like ('%00%') THENINTO hiredate_history_00 VALUES(DEPTID,HIREDATE)WHEN HIREDATE like ('%99%') THENINTO hiredate_history_99 VALUES(DEPTID, HIREDATE)ELSEINTO hiredate_history VALUES(DEPTID, HIREDATE)SELECT department_id DEPTID, SUM(salary) SAL,MAX(hire_date) HIREDATEFROMemployeesGROUP BY department_id;

Pivoting INSERT• Suppose you receive a set of sales records from a   nonrelational database table,  SALES_SOURCE_DATA, in the following format: EMPLOYEE_ID, WEEK_ID, SALES_MON, SALES_TUE,SALES_WED, SALES_THUR, SALES_FRI• You want to store these records in the   SALES_INFO table in a more typical relational  format: EMPLOYEE_ID, WEEK, SALESUsing a pivoting INSERT, convert the set of salesrecords from the nonrelational database table torelational format.

Pivoting INSERTINSERT ALLINTO sales_info VALUES (employee_id,week_id,sales_MON)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_FRIFROM sales_source_data;

Page 173: Oracle Notes

The MERGE Statement•Provides the ability to conditionally update orinsert data into a database table•Performs an UPDATE if the row exists, and anINSERT if it is a new row:

– Avoids separate updates– Increases performance and ease of use– Is useful in data warehousing applications

Merging RowsInsert or update rows in the EMPL3 table to match theEMPLOYEES table.MERGE INTO empl3 cUSING employees eON (c.employee_id = e.employee_id)WHEN MATCHED THENUPDATE SETc.first_name= e.first_name,c.last_name= e.last_name,...c.department_id = e.department_idWHEN NOT MATCHED THENINSERT 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);

Merging RowsTRUNCATE TABLE empl3;SELECT *FROM empl3;no rows selectedMERGE INTO empl3 c

Page 174: Oracle Notes

USING employees eON (c.employee_id = e.employee_id)WHEN MATCHED THENUPDATE SET...WHEN NOT MATCHED THENINSERT VALUES...;SELECT *FROM empl3;

A Database Instance is a collection of Memory structures and Background processes.Oracle MEmory is categorized into two types:

1. System Global Area (SGA) SGA is a shared memory area that is allocated during startup of the instance. This memory is shared byall server and user processes.

2. Program Global Area (PGA) PGA is a private memory area that is alloted to a specific user process.

The SGA is a collection of following data structures:

1. Database Buffer Cache: is a temporary memory area that caches the data requested by the user.It helps in faster retreival of data.

2. Redo log buffer: it caches redo information. IT will be helpful during instance recovery.

3. Shared Pool: It caches information that are shareable among users.

4. Java Pool: It caches the information that requires java virtual machine (JVM).

5. Large Pool: This part of the memory wil be used when a large amt of memory allocation is required.For example during certain backup and recovery operations.

Background Processes:

Page 175: Oracle Notes

1. SMON (System Monitor) : This process is used during an instance recovery.2. PMON (Process Monitor) : This process does the cleanup job to release memory of those user processes thatare no longer available.3. DBWn (Database Writer): is reponsible for writing each blocks of data from the redo log buffer to the physicaldatabase files.4. LGWR (Log Writer) : this process is responsible to do a log entry to the control file following a log switch.5. ARCn (ARCHIVER): Each and every block of data is processed by the Archiver.

RECOVERY MANAGER (RMAN) : is a tool that allowes the user to perform backup and recovery operations.

To start RMAN:

TERMINAL 1:

export ORACLE_SID=rajlsnrctl startemctl start dbconsolesqlplus sys/manager as sysdbaSQL> startupSQL> ARCHIVE LOG LIST

TERMINAL 2:export ORACLE_SID=rajrman  target  /  nocatalog

1. Ensure that the database is in ARCHIVELOG mode:SQL> ARCHIVE LOG LISTif the Database ARCHIVELOG is disabled:

Page 176: Oracle Notes

SQL> SHUTDOWN IMMEDIATESQL> STARTUP MOUNTSQL> ALTER DATABASE ARCHIVELOG;SQL> ALTER DATABASE OPEN;

ALTER SYSTEM SET db_recovery_file_dest_size = 5087690752 SCOPE=BOTH2. Startup the database instance:

SQL> SELECT STATUS FROM V$INSTANCE;

STATUS------------OPEN

To connect to RMAN, on a different terminal window:[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalog

To see the structure of the database:RMAN> REPORT SCHEMA;

To see a list of backupsets taken:RMAN> LIST BACKUP OF DATABASE;

To see a list of image copies taken:RMAN> LIST COPY OF DATABASE;

To display outdated backups:RMAN> REPORT OBSOLETE;

To delete the outdated backups:RMAN>     DELETE NOPROMPT OBSOLETE;

To see a list of configuration settings for RMAN:RMAN> SHOW ALL;

To set the Control File Autobackup On:RMAN> CONFIGURE CONTROLFILE AUTOBACKUP ON;

Page 177: Oracle Notes

Configure RMAN to change the retention policy to redundancy 5.RMAN> CONFIGURE RETENTION POLICY TO REDUNDANCY 5;

Configure the RMAN to set the retention policy to 30 days.RMAN> CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 30 DAYS;

To take a full database backup:RMAN> BACKUP AS BACKUPSET DATABASE;

To delete the backupsets:RMAN> DELETE NOPROMPT BACKUPSET 2,7;

To take an image copy of the database:RMAN> BACKUP AS COPY DATABASE;

To delete an image copy:RMAN> DELETE NOPROMPT DATAFILECOPY 2,3,6,8,5,4,7;

To take a compressed backupset:RMAN> BACKUP AS COMPRESSED BACKUPSET DATABASE;

To list the datafiles that are required to be backed up:RMAN> REPORT NEED BACKUP;

To exclude a tablespace from full database backup:RMAN> CONFIGURE EXCLUDE FOR TABLESPACE tbsalert;

To view a list of tablespaces that are excluded:RMAN> SHOW EXCLUDE;

To take a full backup by including the excluded tablespace:RMAN> BACKUP NOEXCLUDE AS BACKUPSET DATABASE;

To take a full backup of database in compressed mode by including the excluded tablespace along withthe Archive log also:RMAN> BACKUP NOEXCLUDE AS COMPRESSED BACKUPSET DATABASE PLUS ARCHIVELOG;

Change the configuration setting to include the excluded tablespace for full backups:

Page 178: Oracle Notes

RMAN> CONFIGURE EXCLUDE FOR TABLESPACE TBSALERT CLEAR;

SQL> ALTER SYSTEM SET db_recovery_file_dest_Size=5G SCOPE=both;

To take an incremental Backup:RMAN> BACKUP AS BACKUPSET INCREMENTAL LEVEL 0 DATABASE;

The perform LEVEL 1 backup:RMAN> BACKUP AS BACKUPSET INCREMENTAL LEVEL 1 DATABASE;

To take a full backup of example tablespace:

RMAN> BACKUP AS BACKUPSET TABLESPACE example;

To take an image copy of example tablespace:RMAN> BACKUP AS COPY TABLESPACE example;

To take an offline backup:1. Shutdown the database instance2. Restart the instance in MOUNT state

SQL> SHUTDOWN IMMEDIATESQL> STARTUP MOUNT

3. Connect to recovery manager[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalog

RMAN> backup as backupset database;

4. Open the database instance:SQL> alter database open;

list backup of database;delete noprompt backupset 3,4,5,6;backup noexclude as backupset database;

Database Recovery

Page 179: Oracle Notes

--------------------------

Recovering Database with FLASHBACK command:

Steps to enable Flashback Database:

1. Connect to OEM as sys.2. Click Availability Tab.3. Click Recovery Settings4. Check the Enable Flashback Database check box. Enter the flashback retention time period. Click Apply.

SQL> conn hr/hrConnected.SQL> select sum(salary) from employees;

SUM(SALARY)-----------     691416

SQL> conn sys/manager as sysdbaConnected.SQL> SELECT current_scn FROM v$database;

CURRENT_SCN-----------    1050321

SQL> conn hr/hrConnected.SQL> UPDATE employees  2  SET salary=salary+100;

107 rows updated.

SQL> commit;

Commit complete.

Page 180: Oracle Notes

SQL> conn sys/manager as sysdbaConnected.SQL> SELECT current_scn FROM v$database;

CURRENT_SCN-----------    1050366

SQL> SELECT sum(salary) FROM hr.employees;

SUM(SALARY)-----------     702116

We need to flashback the database to the previous transaction id:

Soln:

1. Shutdown the database instance.SQL> SHUTDOWN IMMEDIATE2. Restart the database in MOUNT stateSQL> STARTUP MOUNT3. Connect to Recovery Manager[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalogRMAN> FLASHBACK DATABASE TO SCN=1050321;4. Open the Database instanceNote that when you try to open the database it will give you an error. For any incomplete recoveryopen the database with RESETLOGS option to update the control files with the database change.

SQL> ALTER DATABASE OPEN RESETLOGS;

To enable manage transactions:

SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;Database altered.

SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS;

Page 181: Oracle Notes

Another example Incomplete Recovery-----------------------------------------------------------

POINT-IN TIME RECOVERY (TIME-BASED RECOVERY)

SQL> SELECT systimestamp FROM dual;

SYSTIMESTAMP---------------------------------------------------------------------------21-SEP-15 06.30.24.578235 PM +03:00

SQL> conn hr/hrConnected.SQL> select * from job_history;

EMPLOYEE_ID START_DAT END_DATE    JOB_ID       DEPARTMENT_ID----------- --------- --------- ---------- -------------    102 13-JAN-01 24-JUL-06 IT_PROG           60    101 21-SEP-97 27-OCT-01 AC_ACCOUNT         110    101 28-OCT-01 15-MAR-05 AC_MGR             110    201 17-FEB-04 19-DEC-07 MK_REP              20    114 24-MAR-06 31-DEC-07 ST_CLERK          50    122 01-JAN-07 31-DEC-07 ST_CLERK          50    200 17-SEP-95 17-JUN-01 AD_ASST           90    176 24-MAR-06 31-DEC-06 SA_REP              80    176 01-JAN-07 31-DEC-07 SA_MAN              80    200 01-JUL-02 31-DEC-06 AC_ACCOUNT          90

10 rows selected.

SQL> delete from job_history;

10 rows deleted.

SQL> select sum(salary) from employees;

SUM(SALARY)-----------     691516

Page 182: Oracle Notes

SQL> update employees set salary=salary+500;

107 rows updated.

SQL> select sum(salary) from employees;

SUM(SALARY)-----------     745016

SQL> commit;

Commit complete.

SQL> select count(*) from employees;

  COUNT(*)----------       107

SQL> delete from employees  2  where job_id='ST_CLERK';

20 rows deleted.

SQL> commit;

Commit complete.

SQL> select count(*) from employees;

  COUNT(*)----------    87

Sln:

1. Shutdown and restart the instance in MOUNT stateSQL> SHUTDOWN IMMEDIATE

Page 183: Oracle Notes

Database closed.Database dismounted.ORACLE instance shut down.SQL> STARTUP MOUNT

2. Connect to the recovery manager:

$ export NLS_DATE_FORMAT="yyyy-mm-dd hh24:mi:ss"$ export NLS_LANG=american_america.we8iso8859p15[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalog

RMAN> run2> {3> SET UNTIL TIME='2015-09-21 18:30:00';4> RESTORE DATABASE;5> RECOVER DATABASE;6> }

3. Open the database instance with RESETLOGS optionSQL> ALTER DATABASE OPEN RESETLOGS;SQL> CONN hr/hrConnected.SQL> SELECT * FROM job_history;SQL> SELECT sum(salary) FROM employees;SQL> SELECT count(*) FROM employees;

OBJECT-LEVEL RECOVERY-------------------------------------------When a datafile is lost or damaged, you can recover it using two methods:NOTE: YOU MUST HAVE A VALID BACKUP OF THE DATABASE TO RECOVERY A DATAFILE

Scenario: Delete the datafiles example01.dbf and users01.dbf from oradata directory:Database location: /u01/app/oracle/oradata/raj

Method 1: Without shutting down the instance:----------------------------------------------------------------------Step 1: Make the datafiles offline as sys user:

Page 184: Oracle Notes

SQL> ALTER DATABASE DATAFILE 5 OFFLINE;SQL> ALTER DATABASE DATAFILE 4 OFFLINE;

Step 2: Connect to RMAN[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalogRMAN> run2> {3> RESTORE DATAFILE 4,5;4> RECOVER DATAFILE 4,5;5> }

Step 3: After the recovery, make the datafiles onlineSQL> ALTER DATABASE DATAFILE 5 ONLINE;Database altered.

SQL> ALTER DATABASE DATAFILE 4 ONLINE;Database altered.

Method 2: Shutdown the instance and restart in MOUNT state:

SQL> SHUTDOWN ABORT;ORACLE instance shut down.SQL> STARTUP MOUNT

Connect to RMAN

[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalog

RMAN> run2> {3> RESTORE DATAFILE 5;4> RECOVER DATAFILE 5;5> }

Open the Database instanceSQL> ALTER DATABASE OPEN;

Page 185: Oracle Notes

DATABLOCK RECOVERY---------------------------------------STEPS:

1. Startup the database instance:export ORACLE_SID=rajlsnrctl startemctl start dbconsolesqlplus sys/manager as sysdba

SQL> startupSQL> SELECT file_id, block_id  2  FROM dba_extents  3  WHERE segment_name='DEPARTMENTS' and owner='HR';

   FILE_ID   BLOCK_ID---------- ----------     5      168SQL> exit2. Ensure that your current working directory is desktop where you have copied mycorrupt.sh file.Run the script from the command prompt:[oracle@rajiv Desktop]$ ./mycorrupt.sh /u01/app/oracle/oradata/raj/example01.dbf 168 8192

Connect to SQLPLUS as hr user and query the departments table.

You must have a backup file.

[oracle@rajiv Desktop]$ dbv file=/u01/app/oracle/oradata/raj/example01.dbf

Open another terminal window:export ORACLE_SID=rajrman   target   /  nocatalog

RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 169,170,171;

DISASTER RECOVERY----------------------------------------DBID=2837611864

Page 186: Oracle Notes

instance name: raj

STEPS:Ensure that:1. You have your database id2. controlfile autobackup is on3. take a full database backupsBACKUP NOEXCLUDE AS BACKUPSET DATABASE PLUS ARCHIVELOG;

4. delete all files related to the database.

1. shutdown the database instance and startup in NOMOUNT state.SQL> shutdown immediateWILL GIVE ERROR SO,SQL> SHUTDOWN ABORT;SQL> STARTUP NOMOUNT;

2. Recover the control filesOpen another terminal window and connect to RMAN.[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalog

3. Set the Database IDRMAN> SET DBID=2837611864

4. Recover the control fileRMAN> RESTORE CONTROLFILE FROM AUTOBACKUP;

5. Try mounting the database:SQL> ALTER DATABASE MOUNT;

6. Connect to recovery manager and recover the database files.[oracle@rajiv Desktop]$ export ORACLE_SID=raj[oracle@rajiv Desktop]$ rman target / nocatalogRMAN> run2> {3> RESTORE DATABASE;4> RECOVER DATABASE;5> }

Page 187: Oracle Notes

7. Open the database instance with RESETLOGS option.

SQL> ALTER DATABASE OPEN RESETLOGS;

Take a fresh backup after the recovery:

RMAN> list backup of database;RMAN> backup noexclude as backupset database plus archivelog;

Loss of one control file---------------------------------If only one control file is lost, you can recovery it by making the duplicate copy of theexisting one.+9

Managing Resources---------------------------------Steps :1) Connect to OEM as SYSTASK A Create a resource group called app_user    - On the OEM, click server tab, then click consumer group link    - Click create, enter the resource group name as app_user, optionally enter the description    -Ensure that Scheduling policy is selected as Round RobinTASK BAdd the app_user and low_group consumer groups to default_plan resource planChange the level 3 cpu resource allocation percentages as below1) 60% for app_user2) 40% for low_groupSteps:  - On the OEM, click server tab, then click on the plans link.  - Select the plan called default_plan, then click edit  - Click modify button, move the app_user and low_group resorce groups to the plan, click ok.  - Under level 3, for app_user add 60, for low_group add 40, click apply.TASK CConfigure the consumer groups mappings such that the HR user belongs to app_user group, scott user belongs to low_group consumer group. Also for the scott user confirm that his oracle_user

Page 188: Oracle Notes

attribute has a higher priority than client_os_user attribute.Steps:1) On the OEM click the server tab, then click the consumer group mappings.2) Select oracle_user and click Add rule for selected type button.3) Select the consumer group as app_user and shift HR from available users to selected users.4) Select the consumer group as low_group and shift SCOTT from available users to selected users.and click ok.5) Click on the priorities tab and ensure that oracle user is before the client_os_user in the list.TASK DConfigure consumer group mappings such that the oracle_os_user belongs to the sys_group consumetgroup.Steps:1) On the OEM, click server tab, then click on the consumer group mappings link2) Select client_os_user and click the Add rule for selected type button.3) Select consumer group as sys_group, then move the oracle user to the selected user thenclick ok, apply.TASK EAssign the pm user to the following consumer groups 1) app_user2) low_group3) sys_groupSteps:1) On the OEM, click the server tab, click users link2) Select pm user , click edit, click consumers group privileges tab.3) Click edit list, move app_user,low_group, sys_group to the available list, click ok, apply.

ACTIVATE THE PLAN : DEFAULT_PLANSteps:1) On the OEM, click the server tab, on the resource manager click plans.2) Select default_plan, ensure that the actions drop down list has activate option, click go.3) When asked for confirmation, click yes.

Creating Scheduler components-----------------------------------------------------------TASK A: Create a job called job_create_session_history, this job should create a table called session_history with two columns(snap_time timestamp with local time zone, num_sessions number)

Page 189: Oracle Notes

Steps:1) On the OEM, click server tab, under oracle scheduler click jobs, click create2) Type the job name3) Under command region enter the following procedurebegin     execute immediate('CREATE TABLE HR.SESSION_HISTORY(SNAP_TIME TIMESTAMP WITH LOCAL TIME ZONE, NUM_SESSIONS NUMBER)');end;Leave all value for default, then click ok.TASK B: Create a program called prg_session, this program will take the total count of active sessionsand do a log entry into session_history table.Steps:1) On OEM, click server tab, click programs link.2) Type the program name3) Under source type the following blockdeclarex number;begin   SELECT COUNT(*) INTO x FROM V$SESSION;   INSERT INTO HR.SESSION_HISTORY VALUES(SYSTIMESTAMP, X);   COMMIT;end;

TASK C: Create a schedule called sch_session, this schedule should run every 5 seconds.Steps:1) On OEM, click server tab, click schedules link.2) Click create, then give a name of the schedule3) Under repeat select the interval as 5 seconds, let the schedule be immediate, click OK.

TASK D: Create a job called job_session, this job should run the program prg_session every five secondsSteps:1) On OEM, click server tab, click jobs link, click create, type the job name2) Under command region, click the change command type button and pick the prg_session from the look up icon3) Likewise attach the pre defined schedule by clicking on the schedules tab, then click ok.

Page 190: Oracle Notes

Managing Schema Objects=========================Your company is going through a merging process. As a result, you expect somedramatic growth in a few tables of the databases for which you are responsible. To proactivelymonitor table and index space usage, you create a test case and perform the tasks, which youexpect for your production system.$ ./lab_10_01.shPCTFREE means When inserting rows for this table, the Oracle database will keep 10% ofthe block free for future updates

2. Populate the TEST_REGIONS table by running the lab_10_02.sh script.$ ./lab_10_02.shb. Go to the Tables page on the Administration tabbed page.c. Enter HR as the Schema, and click Go.Question 2: On the Tables page, what is the number of rows for the TEST_REGIONStable, and why?Answer: The number of rows is empty because the table has not been recently analyzed.3. Best practices recommend that you gather new statistics after major DML activities, such aspopulating a new table. Do so for the HR.TEST_REGIONS table.a. On the Tables page, select the TEST_REGIONS table, then select Manage OptimizerStatistics from the Actions drop-down list and click Go.b. The Manage Optimizer Statistics page appears. Review the information and clickGather Optimizer Statistics.c. On the Review page, click Submit.d. Click the Job Name link (which most likely has a different name).e. If you are fast, you will see the job running. Click Refresh until you do not see the jobanymore.f.     Click the History tabbed page, and click the name of your job. Confirm that itsucceeded.g. Return to the HR Tables page and view the number of rows in the TEST_REGIONStable.h. The number has been updated by the Optimizer Statistics. It now shows 17000 as therow count.4. View the segment information for the HR.TEST_REGIONS table, which you can accesson the Edit Table Segments page.While you look at the segment information for the HR.TEST_REGIONS table, you noticethat the table segment has a “Wasted Space (%)” of over 20%. You decide to reorganize thetablespace usage. After doing that, confirm that your job succeeded and view the currentspace usage again. Did it increase or decrease?a. In Enterprise Manager, select Administration > Tables. Select the TEST_REGIONStable and click Edit.

Page 191: Oracle Notes

b. Click the Segments tabbed page and review the table’s segment information.c. Notice rajWasted Space (%). Your values may differ from those shown here.What is the cause of the wasted space?d. Select Reorganize from the Actions drop-down list and click Go.e. Accept the defaults on the following pages and click Next. On the Schedule page, enteroracle as Username and Password for Host Credentials.f. On the Review page, click Submit Job.g. If you see the job running, click Refresh or Reload in your browser window until it iscompleted and disappears from the Results list.h. Then click the job name link in the Confirmation window. The status of the job runshould be “Succeeded.”i. Return to the Tables page for the HR schema. Select the TEST_REGIONS table, clickedit and view the Wasted Space (%) on the Segments tab. The value should besignificantly lower than the previous value.

Managing Storage=================

Create a new tablespace called TBSALERT with a 120 MB file called alert1.dbf. Makesure that this tablespace is locally managed and uses Automatic Segment SpaceManagement. Do not make it autoextensible, and do not specify any thresholds for thistablespace. Use Enterprise Manager Database Control to create it. If this tablespace alreadyexists in your database, drop it first, including its files.a. In Enterprise Manager, select Server Tab > Tablespaces.b. Click the Create button.c. Enter TBSALERT as Name, and click the Add button in the Datafiles region.d. Enter alert1.dbf as File Name and 120 MB as File Size, and select Reuse Exisiting File.e. Click Continue, and then click OK.4. In Enterprise Manager, change the Tablespace Space Usage thresholds of the TBSALERT tablespace. Set its warning level to 55 percent and its critical level to 70 percent.a. On the Tablespaces page, select TBSALERT, click Edit, and then click Thresholds.b. Select Specify Thresholds, and enter 55 as Warning (%) a nd 70 as Critical (%).c. Optionally, click Show SQL, review the statement, and click Return.d. Click Apply to modify the threshold values.5. Using SQL*Plus, check the new threshold values for the TBSALERT tablespace.a. In your SQL*Plus session, enter:

Page 192: Oracle Notes

select warning_value,critical_valuefrom dba_thresholdswhere metrics_name='Tablespace Space Usage' andobject_name='TBSALERT';

6. Select the reason and resolution columns from DBA_ALERT_HISTORY for theTBSALERT tablespacea. In your SQL*Plus session, enter:select reason,resolutionfrom dba_alert_historywhere object_name='TBSALERT';7. Execute the lab_11_07.sh script that tcreates and populates new tables in the TBSALERT tablespace.8. Check the fullness level of the TBSALERT tablespace by using either Database Control orSQL*Plus. The current level should be around 60%. Wait for approximately 10 minutes,and check that the warning level is reached for the TBSALERT tablespace.a. In Enterprise Manager on the Tablespaces page, see Used (%).b. Navigate to the Database home page. You should see the new alert in the Space summary section.c. In SQL*Plus, enter:select sum(bytes) *100 /125829120from dba_extentswhere tablespace_name='TBSALERT';d. Enter the following command:select reasonfrom dba_outstanding_alertswhere object_name='TBSALERT';9. Execute the lab_11_09_a.sh script to add data to TBSALERT. Wait for 10 minutes andview the critical level in both the database and Database Control. Verify that TBSALERTfullness is around 75%.insert into employees4 select * from employees4;commit;insert into employees5 select * from employees5;commit;a. Enter the following command in a terminal window:$ ./lab_11_09_a.sh

b. Wait for 10 minutes and view the critical level in both the database and Database

Page 193: Oracle Notes

Control. Verify that TBSALERT fullnesshas is around 75%. In SQL*Plus, enter:select sum(bytes) *100/125829120from dba_extents where tablespace_name='TBSALERT';

c. In SQL*Plus, enter:select reason, message_levelfrom dba_outstanding_alertswhere object_name='TBSALERT';

d. In Enterprise Manager, on the Tablespaces page, see Used (%).e. Navigate to the Database home page. You should see the new alert in the SpaceSummary region. Notice the red flag instead of the yellow one.

10. Execute lab_11_10.sh to delete few rows./lab_11_10.sh

11. Now, run the Segment Advisor for the TBSALERT tablespace by using Database Control.Make sure that you run the Advisor in Comprehensive mode without time limitation.Accept and implement its recommendations. After the recommendations have beenimplemented, check whether the fullness level of TBSALERT is below 55%.a. In Enterprise Manager, select Administration > Tablespaces.b. Select TBSALERT, and then select Run Segment Advisor from the Actions drop-downlist.c. Click Go, review the objects, and click Next.d. On the Segment Advisor: Schedule page, make sure that Schedule Type is "Standard and Start is “Immediately.” Click Next.e. On the Segment Advisor: Review page, click the Submit button.f. On Advisor Central page, click Refresh.g. Select your segment Advisor Task and click View Result button.h. On the Segment Advisor Task page, click the Recommendation Details button.i. Click the Select All link, and then click the Implement button.j. On the Shrink Segment: Options page, make sure that the “Compact Segments andRelease Space” option is selected.k. Optionally, click Show SQL, review the statements, and click Return.l. Click Implement.m. On the Shrink Sement: Schedule page, click the Submit button.n. On the Scheduler Jobs page, click Refresh until you see your job in the Running table.Continue to click Refresh until you no longer see your job in the Running table. Itshould take approximately two minutes to complete.o. Navigate to the Tablespaces page and verify that the TBSALERT tablespace fullness is

Page 194: Oracle Notes

now below 55%.

12. Wait for 10 mins and check that there are no more alerts outstanding for TBSALERT tablespace.a. Navigate to the Database homeipage. You should see Problem Tablespaces 0.13. Retrieve the history of the TBSALERT Tablespace Space Usage metric for the last 24 hours.a. On the Database home page, select All Metrics in the Related Links region.b. Expand the “Tablespaces Full” category, and click the “Tablespace Space Used (%)”link.c. Make sure that you select “Real Time: Manual Refresh” from the View Data drop-downlist. Then, click the TBSALERT link.d. This takes you to the “Tablespace Space Used (%): Tablespace Name TBSALERT”page. Select “Last 24 hours” from the View Data drop-down list.