SlideShare a Scribd company logo
Introduction Chapter 1
Course Objectives After completing this course, you should be able to do the following: Install, create, and administer Oracle Database 10 g Understand Oracle SQL and PL/SQL Configure the database for an application Create and Configure Oracle Distributed Database Can Perform Backup, Restore and Recover Database
Lesson Objectives After completing this lesson, you should be able to do the following: Explain the Oracle Database architecture
Oracle Products and Services Oracle databases Oracle Application Server Oracle applications Oracle Collaboration Suite Oracle Developer Suite Oracle services
Oracle Database Architecture An Oracle server: Is a database management system that provides an open, comprehensive, integrated approach to information management Consists of an  Oracle Service  , Oracle instance  and an  Oracle database
Database Structures Storage structures Memory structures Process structures Instance Database files DB structures -  Memory -  Process -  Storage Oracle Service System Global Area (SGA) Background   processes
Oracle Memory Structures  . Database buffer cache Redo log  buffer Shared pool Large pool SGA Streams pool Server process 1 PGA Server process 2 PGA Background process PGA DB structures > Memory Process Storage
Process Structures User process:  Is started at the time a database user requests a connection to the Oracle server Server process:  Connects to the Oracle instance and is started when a user establishes a session Background processes:  Are started when an Oracle instance is started Instance Background  processes Server process PGA User process DB structures Memory > Process  Storage SGA
Oracle Instance Management System Monitor (SMON) Database Writer (DBW n ) LogWriter (LGWR) Process Monitor (PMON) Archiver (ARC n ) SGA Java pool Shared pool Large  pool Streams   pool Database buffer cache Redo log  buffer Checkpoint (CKPT) Control files Data files Redo log files Archive   log files
Server Process and Database  Buffer Cache Buffers: Pinned Clean Free or unused Dirty Server process SGA Database buffer cache Data files DBW n
Physical Database Structure  . Online redo log files Password file Parameter file Archive log files Control files Data files Alert and trace log files Backup files DB structures Memory Process > Storage
Tablespaces and Data Files Tablespaces consist of one or more data files. Data files belong to only one tablespace. Data file 1 Data file 2 USERS  tablespace
SYSTEM  and  SYSAUX  Tablespaces  The  SYSTEM  and  SYSAUX  tablespaces are mandatory tablespaces. They are created at the time of database creation. They must be online. The  SYSTEM  tablespace is used for core functionality (for example, data dictionary tables). The auxiliary  SYSAUX  tablespace is used for additional database components (such as the Enterprise Manager Repository).
Segments, Extents, and Blocks Segments exist within a tablespace. Segments are made up of a collection of extents. Extents are a collection of data blocks. Data blocks are mapped to disk blocks. Segment Extents Data blocks Disk blocks
Logical and Physical Database Structures Database Logical Physical Tablespace Data file OS block Segment Extent Oracle data block Schema
Extends and Segment
Course Examples: The  HR  Schema REGIONS REGION_ID (PK) REGION_NAME COUNTRIES COUNTRY_ID (PK) COUNTRY_NAME REGION_ID (FK) LOCATIONS LOCATION_ID (PK) STREET_ADDRESS POSTAL_CODE CITY STATE_PROVINCE COUNTRY_ID (FK) DEPARTMENTS DEPARTMENT_ID (PK) DEPARTMENT_NAME MANAGER_ID LOCATION_ID (FK) JOBS JOB_ID (PK) JOB_TITLE MIN_SALARY MAX_SALARY EMPLOYEES EMPLOYEE_ID (PK) FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID (FK) SALARY COMMISION_PCT MANAGER_ID (FK) DEPARTMENT_ID (FK) JOB_HISTORY EMPLOYEE_ID (PK) START_DATE (PK) END_DATE JOB_ID (FK) DEPARTMENT_ID (FK) REGIONS COUNTRIES LOCATIONS DEPARTMENTS JOBS EMPLOYEES JOB_HISTORY
Database Architecture: Summary of Structural Components Database Service Memory structures: System Global Area (SGA): Database buffer cache, redo buffer, and various pools Program Global Area (PGA) Process structures: User process and Server process Background processes: SMON, PMON, DBW n , CKPT, LGWR, ARC n , and so on Storage structures: Logical: Database, schema, tablespace, segment, extent, and Oracle block Physical: Files for data, parameters, redo, and OS block
Summary In this lesson, you should have learned how to: Install, create, and administer Oracle Database 10 g Configure the database for an application Employ basic monitoring procedures Implement a backup and recovery strategy Move data between databases and files
End of Chapter 1
Installing the Oracle Database Software Chapter 2
Objectives After completing this lesson, you should be able to do the following: Describe your role as a database administrator (DBA), and explain typical tasks and tools Plan an Oracle database installation Use Optimal Flexible Architecture  (OFA) Install the Oracle software by using Oracle Universal Installer (OUI)
Tasks of an Oracle Database Administrator A prioritized approach for designing, implementing, and maintaining an Oracle database involves the following tasks:  1. Evaluating the database server hardware 2. Installing the Oracle software 3. Planning the database and security strategy 4. Creating, migrating, and opening the database 5. Backing up the database 6. Enrolling system users and planning for  their Oracle Network access 7. Implementing the database design 8. Recovering from database failure 9. Monitoring database performance
Tools Used to Administer an Oracle Database Oracle Universal Installer Database Configuration Assistant Database Upgrade Assistant Oracle Net Manager Oracle Enterprise Manager SQL*Plus and  i SQL*Plus Recovery Manager  Oracle Secure Backup Data Pump SQL*Loader Command-line tools
Installation: System Requirements Memory requirements: 1 GB for the instance with Database Control Disk space requirements: 1.5 GB of swap space  400 MB of disk space in the  /tmp  directory Between 1.5 GB and 3.5 GB for the Oracle software 1.2 GB for the preconfigured database (optional) 2.4 GB for the flash recovery area (optional) Operating system: See documentation.
Checking the System Requirements Adequate temporary space 64-bit versus  32-bit issues Checks for the correct operating system (OS)   System and kernel parameters ORACLE_HOME
Optimal Flexible Architecture (OFA) OFA is designed to: Organize large amounts of software  Facilitate routine administrative tasks  Manage and administer database growth adequately  Help eliminate fragmentation of free space
Using Optimal Flexible Architecture Naming mount points: /u01 /disk01 Naming directories: /u01/app/oracle /u01/app/applmgr Naming files: Control files:  control n .ctl Redo log files:  redo n .log Data files:  tn .dbf
Setting Environment Variables ORACLE_HOME : The directory containing the Oracle software ORACLE_SID : The initial instance name (by default,  ORCL ) NLS_LANG : The language, territory, and client character set settings
Oracle Universal Installer (OUI)
Database Configuration Options
Completing Your Installation
Creating an Oracle Database Chapter 3
Objectives After completing this lesson, you should be able to do the following: Create a database with the Database Configuration Assistant (DBCA) Create a database design template with the DBCA Generate database creation scripts with the DBCA
Planning the Database As a DBA, you must plan: The logical storage structure of the database and its physical implementation: How many disk drives do you have for this? How many data files will you need? (Plan for growth.) How many tablespaces will you use? Which type of information will be stored? Are there any special storage requirements due to type or size? The overall database design A backup strategy for the database
Databases: Examples Data Warehouse: Research and marketing data State or federal tax payments  Professional licensing (doctors, nurses, and so on) Transaction Processing: Store checkout register system Automatic teller machine (ATM) transactions General Purpose:  Retail billing system, for example, of a software house or a general database.
Database Configuration Assistant (DBCA)
Using the DBCA to Create a Database
Using the DBCA to Create a Database 3 4
Using the DBCA to Create a Database 5 6 7
Using the DBCA to Create a Database 8 9
Using the DBCA to Create a Database A B 10
Using the DBCA to Create a Database 11 12
Password Management B A C
Creating a Database Design Template
Using the DBCA to Delete a Database 1 2 3
Summary In this lesson, you should have learned how to use the DBCA to: Create a database Create a database design template  Generate database creation scripts
Practice Overview:  Using the DBCA This practice covers the following topics : Creating the  ORCL  database by using the DBCA Unlocking the  HR  schema Note: Completing the database creation and unlocking the HR schema is critical for all following practice sessions. Optionally: Creating the  ORCL  database design template by using the DBCA Creating database creation scripts with the DBCA
Creating Database by Manual Component: Configure Parameter File or Init File Create Database Service Startup Instance Create Database  Setup System Database Create Database Storage Configure oracle network Create Database Objects
Create Init File Parameter File or Init File is an text file contains parameters use to configure Database Instance while it is started up. Parameters are consist of: DB_NAME =Specific name of the instance(Database) Control_file s=(Specific location and name of control file) Undo_Management =Define how to management transaction auto or by rollback segment Undo_Tablespace =Name of Tablespace to keep transaction. Processes =Number of Process allow Sessions =number of current connection DB_Block_Size =Size of unit write or read data into file.
ora_sothea
Create Database Service  Oracle Database Service: is an identifier of database on network environment. It’s a service provider to clients whom whish to connect to oracle server to get service. Syntax:  On DOS Prompt OraDim –NEW –SID  nameofservice  [-SYSPWD  internal password  –START MODE  Auto|Manual  - PFILE  ‘Path\Parameter file name’]
Syntax Delete: Oradim –Delete –SID  nameofservice
Connect to Oracle Service and Create Instance: To Create Database Instance (In-Memory Database) - Specific Oracle service (SID) SET ORACLE_SID=Oracle Service Name - Go into Oracle Utility call SQL PLUS with nolog option SQLPLUS/NOLOG Connect to specific service(SID) by database administrator CONNECT / AS SYSDBA -  Startup Database Instance with  nomount  option STARTUP NOMOUNT [PFILE=Path\Parameter File Name]
ora_sothea
Create Database File and Open Database Instance
ora_sothea
ora_sothea
Setup System For oracle 10g and above must be configure SysAux Datafile  @%Oracle_home%\rdbms\admin\catalog Install database catalog and dynamic view @%Oracle_home%\rdbms\admin\catproc Install PL/SQL Compiler and oracle pre-define functions and packages.
Create Tablespace (Storage) An tablespace is a pointer of data files on database instance. There are following type of tablespace. - System: Store system database objects - System Auxiliary: store system object support to system tablespace (this tablespace unavailable for oracle 9i or below. - Temporary tablespace: use to store query data such join, sort. - Undo Tablespace: This tablespace use transaction. - User Tablespace: Store user input data(tables) - Index Tablespace: Store index.
Create Tablespace: Create [undo] Tablespace  Name-Of-Tablespace Datafile ‘path\filename’ size  initialSize   [Temporary] [Auto extend on [Next Size  IncrementalSize]  MaxSize  MaximumDatafile;
Create net service Net Service is representative of Oracle Service in client computer, it’s used to connect to oracle server by application. Without netservice Application could not connect to Oracle. To create netservice - Open “Net Manager” - Select “Service Naming” - Click “Edit\Create” - Complete parameters as following -Net Service Name: use for connecting -Host Name: Computer Server Name(PC NAME)  -Protocol (Keep Default TCP) and Port Number  (Keep default 1521) -Oracle Service: Oracle Service Name
Connect to database On Dos: SQLPLUS  Username/password@netservicename On SQLPLUS Connect Username/password@netservicename Net Service Name
Startup and Shutdown Server Startup Oracle Server: is a process to create oracle instance. Startup: - Start oracle service - Connect to oracle service by dba (database administrator) - Set Oracle_SID= OracleServiceName - SQL/NOLOG - Connect / as SysDBA -  Startup Database Startup [Option] Pfile= ‘Path\ParameterFile’ Option: Nomount: Start for creating database Mount: Start for reconfiguring database Open: Start for working and providing service.
Shutdown Oracle Server Shutdown Oracle Server is process to close oracle server Connect to oracle server as sysdba Shutdown Shutdown [Option] Option Normal : Normally shutdown by let user disconnect oracle server by themselves. Transactional:  Wait until user save transaction then server disconnect user and shutdown instance when disconnect all user. Immediate:  Rollback all transaction and shutdown instance. Abort:  Shutdown instance without manage every thing. Check “ Startup instance when instance is started”
Configure Oracle Server to Startup Auto To let oracle server to startup automatically when Window is Started: - Configure Oracle Service to start automatic - Connect Parameter File: Name:InitDBNAME.ORA FOLDER: Oracle_HOME\Database (D:\oracle\product\10.1.0\db_2\database) - Open program “Administration Assistant for Window” - Select “Database\DatabaseName” Right Click-> Startup/Shutdown Option
ora_sothea
Configure Transactional - Shutdown Server. Open Parameter File -Add Command Undo_Management=Auto Undo_Tablespace=TablespaceName
Creating Oracle Database Objects Chapter 4
Oracle Objects Objectives: Using Data Definition Language to create: Table Index Sequence View Synonym To Create object: - Start Oracle Database Server - Connect to Oracle by User “System” - Write SQL Script: - Run Script:
Creating a Table Oracle Data Type String Char Size Varchar 4000 Varchar2 4000 NChar 2000 NVarchar2 2000 Long 2GB Number Number(N,P) Integer Float Binary BLOB 4GB DateTime Date
TABLE statement is as follows: CREATE Table Schema. table_name   ( column_name type  [CONSTRAINT  constraint_def  DEFAULT  default_exp ] [,  column_name type  [CONSTRAINT  constraint_def  DEFAULT  default_exp ]...]  ) [TABLESPACE  tab_space Storage];
Schema: Name of user to store object: Tablespace: Name of Tablespace where table is located. Storage option define extends and segment to store table’s data
Constraints Are condition of column: Primary Key: Foreign Key: Unique: Do not duplicate value Check: Set Condition for column  Not Null:
Index An index is object store address of records. It’s use to retrieve record when it’s selected. Syntax: Create Index Name-Of-Index On Table_Name(ColumnName,..) Tablespace Name-of-Tablespace. Guideline: Index set on unique column or less duplicate Index set on columns use in where condition
View View: is virtual table to view data from tables. Syntax:  Create View Name-of-View[(Col1,Col2,…)] AS  Select SQL Statement.
Sequence: Is object use to generate autonumber. Syntax: Create Sequence Name-Of-Sequence [Increment By Step] [Start With StartNumber] Attribute of Sequence .NextVal:  .CurrVal:
Synonym Is Object reference to another object: Syntax: Create [public] Synonym Name-Of-Synonym for [Schema.]ObjectName
System View use to check: DBA_Tablespaces: Store tablespace information of Server. User_Tablespaces: Similar DBA_Tablespaces store for current schema. User_Tables,DBA_Tables: DBA_Indexes,User_Indexes DBA_Views,User_Views DBA_Sequences,User_Sequences *** General form: USER_ObjectTypes Check Structure tables or views DESC Table-Name
End of Chapter 4
Structured Query Language (SQL) Chapter 5
Agenda Keyword IN and BETWEEN Dual ????? FUNCTIONS Aggregate Numeric String Date Group By Having
Keywords IN & BETWEEN IN SELECT columns FROM tables WHERE column1 in (value1, value2, .... value_n); e.g. Select name from employee where desig IN(‘Manager’, ‘Clerk’, ‘Worker’); BETWEEN SELECT columns FROM tables WHERE column1 between value1 and value2; e.g. Select name from Employee  where salary between 4500 AND 7000;
What is DUAL??? The DUAL table is a real table.  It’s owned by the user SYS and has one row.  The table has only one column, which is named DUMMY and has a string with a length of 1.  The value of DUMMY in the one and only row is X. Note:  Anyone can create a table like this, with one row, and accomplish the same thing. But it’s good practice to have one place where you always have one row and you always know the table name.
Aggregate Functions AVG MAX MIN COUNT SUM CORR VARIANCE STDDEV…
Aggregate Functions… Select count(*) from Employee; Select Count(Distinct(city)) from Employee; SELECT SUM(salary) as "Total Salary“ FROM employees where  salary > 25000; SELECT SUM(sales * 0.10) as "Commission“ FROM order_details; SELECT MIN(salary) as "Lowest salary“ FROM employees; SELECT MAX(salary) as "Highest salary“ FROM employees; SELECT Avg(salary) as "Avg Salary“ FROM employees WHERE salary > 25000; SELECT Avg(sales *  0.10) as "Average Commission“ FROM orders; select stddev(salary) from employee;
Numeric Function ABS ACOS BITAND CEIL COS COSH EXP FLOOR LN MOD NANVL POWER ROUND SIGN SIN SQRT TAN LEAST GREATEST
Numeric Function… Select abs(23.65) from dual; Select abs( 12.34 * -2) from dual; Select bitand(6,2) from dual; Select acos(0.35) from dual; Select ceil(32.65) from dual; would return 33. Select ceil(-32.65) from dual; would return -32 Select floor(32.65) from dual; would return 32. Select floor(-32.65) from dual; would return -33 Select exp(3) from dual; Select ln(20) from dual;
Numeric Function… Select greatest(2, 5, 12, 3) from dual; would return 12 Select greatest('2', '5', '12', '3') from dual; would return '5' Select greatest('apples', 'oranges', 'bananas') from dual;  Select least(2, 5, 12, 3)  from dual; would return 2 Select least ('2', '5', '12', '3') from dual; would return ‘12‘ Select least ('apples', 'oranges', 'bananas') from dual; Select mod(15, 4) from dual; Select power(3, 2) from dual; Select sqrt(5.617) from dual; Select sign(-0.675) from dual; would give -1 Select sign(0) from dual; would give 0 Select sign(7.0001) from dual; would give 1
String Function TRIM LTRIM RTRIM ASCII CHR LPAD RPAD CONCAT INSTR INITCAP LENGTH LOWER UPPER REPLACE SUBSTR
String Function… TRIM( [ leading | trailing | both  [ trim_character* ]  ]  string1 ) select TRIM('A' from 'AABABAB4AAA') from dual; select TRIM(LEADING 'A' from 'AABABAB4AAA') from dual; select TRIM(TRAILING 'A' from 'AABABAB4AAA') from dual; select TRIM(BOTH 'A' from 'AABABAB4AAA') from dual; CONCAT(string1, string2) select concat('a','b') from dual; Select ‘a’ || ‘b’ from dual;
String Function… LPAD(string, length, [set]) lpad('tech', 7); would return '  tech' lpad('tech', 2); would return 'te' lpad('tech', 8, '0'); would return '0000tech' lpad(‘this is my text', 15, 'z'); would return ' this is my text' lpad(' this is my text', 16, ‘#'); would return ‘#this is my text ' RPAD(string, length, [set]) rpad('tech', 7); would return 'tech  ' rpad('tech', 2); would return 'te' rpad('tech', 8, '0'); would return 'tech0000' rpad(' this is my text', 15, 'z'); would return ' this is my text' rpad(' this is my text', 16, ‘$'); would return ' this is my text$'
String Function… LTRIM(string, [set]) ltrim('  tech'); would return 'tech' ltrim('  tech', ' '); would return 'tech' ltrim('000123', '0'); would return '123' ltrim('123123Tech', '123'); would return 'Tech' ltrim('123123Tech123', '123'); would return 'Tech1 ltrim('xyxzyyyTech', 'xyz'); would return 'Tech' RTRIM(string, [set]) rtrim('Tech123123', '123'); would return 'Tech' rtrim('123Tech123', '123'); would return '123Tech'
String Function… LOWER(string) lower('GEORGE BURNS 123  '); would return 'george burns 123  ' UPPER(string) upper('george burns 123  '); would return 'GEORGE BURNS 123  ' INITCAP(string) initcap('GEORGE BURNS'); would return 'George Burns' LENGTH(string) length(''); would return NULL. length(‘hello'); would return 5 length(‘ hello '); would return 7 SUBSTR(string, [count]) substr('This is a test', 6) would return 'is a test' substr('TechOnTheNet', 1, 4) would return 'Tech‘ substr('TechOnTheNet', -6, 3) would return 'The'
String Function… REPLACE( string1, string_to_replace, [ replacement_string ] ) replace('123123tech', '123'); would return 'tech' replace('123tech123', '123'); would return 'tech‘ -replace('222tech, '2', '3'); would return '333tech' replace('0000123', '0'); would return '123‘ CHR( number_code ) chr(116); would return 't' chr(84); would return 'T‘ ASCII( single_character ) ascii('t') would return 116 ascii('T') would return 84 ascii('T2') would also return 84
String Function… INSTR( string1, string2, [ start_position ], [ nth_appearance ] ) instr('this is my text', ‘s') ;would return 4  instr(‘this is my text', ‘s', 5, 1) would return 7  instr('this is my text', ‘s', 1, 2) would return 7  instr('this is my text', ‘s', -7, 2) would return 4
Date Functions SYSDATE SYSTIMESTAMP ADD_MONTHS CURRENT_DATE CURRENT_TIMESTAMP EXTRACT MONTHS_BETWEEN LAST_DAY NEXT_DAY
Date Functions… Sysdate Select emp_name, sysdate from employee; SYSTIMESTAMP SELECT SYSTIMESTAMP FROM dual; add_months( date1, n ) add_months('01-Aug-03', 3) would return '01-Nov-03' add_months('01-Aug-03', -3) would return '01-May-03‘ Current_Timestamp select systimestamp from dual; ALTER SESSION SET TIME_ZONE = '+5:30'; select current_timestamp from dual; select systimestamp from dual;
Date Functions… NEXT_DAY( date, weekday ) Where weekday: Monday, Tuesday… e.g. Select next_day(sysdate, ‘MONDAY’) from dual; LAST_DAY(date) select last_day(sysdate) LAST_DATE from dual; MONTHS_BETWEEN(date1, date2 ) select months_between(sysdate, to_date('1/1/2005', 'dd/mm/yyyy')) from dual;
GROUP  BY The GROUP BY clause, along with the aggregate functions, groups a result set into multiple groups, and then produces a single row of summary information for each group.  If we have a mix of aggregate and nonaggregate expressions in the SELECT list, SQL expects that we are trying to perform a GROUP BY operation, and we must also specify  all nonaggregate expressions  in the GROUP BY clause. When we GROUP BY a column that contains NULL values for some rows, all the rows with NULL values are placed into a single group and presented as one summary row in the output.  While using GROUP BY Clause, we can filter records from the table based on a WHERE clause.
GROUP  BY… e.g. select max(salary), min(salary), desig, avg(salary) from employee group by desig; Group By with NULL values; select count(*), department from employee group by department; With where Clause select max(salary), min(salary), desig, avg(salary), count(*) from employee where salary > 5000 group by desig;
GROUP BY HAVING The HAVING clause is used to put a filter on the groups created by the GROUP BY clause. If a query has a HAVING clause along with a GROUP BY clause, the result set will include only the groups that satisfy the condition specified in the HAVING clause.  e.g. select desig, max(salary), avg(salary) from employee group by desig having avg(salary) > 5000;
ORDER BY The SQL ORDER BY clause comes in handy when you want to sort your SQL result sets by some column(s). SYNTAX: Select <field_name(s)> from <table_name(s)>  ORDER BY <EXPR>, <FIELD(s) NAME> [ASC | DESC ] Specifies a column(s) on which to sort. The ORDER BY   clause can include items not appearing in the select list, but in case of using keywords like DISTINCT then the sort columns must appear in the select list
Select Revisited Complete Syntax: SELECT  select_list  FROM  table_source  [ WHERE  search_condition  ]  [ GROUP BY  group_by_expression  ]  [ HAVING  search_condition  ]  [ ORDER BY  order_expression  [ ASC | DESC ] ]
JOIN By using joins, you can retrieve data from two or more tables based on logical relationships between the tables.  A join condition defines the way two tables are related in a query by:  Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table. Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.
JOIN… Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.  Syntax: FROM  first_table join_type second_table  [ON ( join_condition )]
JOIN… Joins can be categorized as:  Inner joins  (the typical join operation, which uses some comparison operator like = or <>). Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.  Cross joins  return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. Outer joins  can be a left, a right, or full outer join.
OUTER JOIN Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
JOIN By using joins, you can retrieve data from two or more tables based on logical relationships between the tables.  A join condition defines the way two tables are related in a query by:  Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table. Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.
JOIN… Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.  Syntax: FROM  first_table join_type second_table  [ON ( join_condition )]
JOIN… Joins can be categorized as:  Inner joins  (the typical join operation, which uses some comparison operator like = or <>). Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.  Cross joins  return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. Outer joins  can be a left, a right, or full outer join.
OUTER JOIN Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
Scalar Subqueries The Scalar Subquery can be used anywhere a value can be used. When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery.  When the subquery returns no rows, a database null is used as the result of the subquery.  Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
Predicate Subqueries Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct. IN Subquery  The IN Subquery tests whether a scalar value matches the single query column value in any subquery result row. General Syntax: value-1 [NOT] IN (query-1)
Predicate Subqueries… value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1) The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row.  The ANY, ALL, SOME specifiers give the type of match expected.  ANY and SOME must match at least one row in the subquery.  ALL must match all rows in the subquery
EXIST Subquery The EXISTS Subquery tests whether a subquery retrieves at least one row, that is, whether a qualifying row exists.  General Syntax:  EXISTS(query-1)
Table Subqueries Table Subqueries are queries used in the FROM clause, replacing a table name.  Its the result set of the Table Subquery acts like a base table in the from list. Table Subqueries can have a correlation name in the from list.
Scalar Subqueries The Scalar Subquery can be used anywhere a value can be used. When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery.  When the subquery returns no rows, a database null is used as the result of the subquery.  Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
Predicate Subqueries Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct. IN Subquery  The IN Subquery tests whether a scalar value matches the single query column value in any subquery result row. General Syntax: value-1 [NOT] IN (query-1)
Predicate Subqueries… value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1) The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row.  The ANY, ALL, SOME specifiers give the type of match expected.  ANY and SOME must match at least one row in the subquery.  ALL must match all rows in the subquery
Predicate Subqueries… EXIST Subquery The EXISTS Subquery tests whether a subquery retrieves at least one row, that is, whether a qualifying row exists.  General Syntax:  EXISTS(query-1)
Table Subqueries Table Subqueries are queries used in the FROM clause, replacing a table name.  Its the result set of the Table Subquery acts like a base table in the from list. Table Subqueries can have a correlation name in the from list.
NULLS &quot;As we know,  There are known knowns.  There are things we know we know.  We also know  There are known unknowns.  That is to say  We know there are some things  We do not know.”- Donald Rumsfeld  What is NULL ????? NULL as &quot;a  special value , or  mark , that is used to indicate the  absence  of any data value.&quot;  NULL in SQL is not a &quot;data value&quot;, but rather an  indicator  that we have  missing  data
NULLS… Nulls in Conditions: Condition Value of A Evaluation a IS NULL 10 FALSE a IS NOT NULL 10 TRUE a IS NULL NULL TRUE a IS NOT NULL NULL FALSE a = NULL 10 UNKNOWN a != NULL 10 UNKNOWN a = NULL NULL UNKNOWN a != NULL NULL UNKNOWN a = 10 NULL UNKNOWN a != 10 NULL UNKNOWN
NULLS… Nulls in SQL Functions All scalar functions (except  REPLACE ,  NVL ,   and  CONCAT ) return null when given a null argument. NVL( string1, replace_with ) e.g. select emp_name, nvl(department, 'N/A') from employee;
Alter Table ALTER TABLE table_name ADD ( column_1 column-definition, column_2 column-definition, ... column_n column_definition ); ALTER TABLE table_name MODIFY ( column_1 column_type, column_2 column_type, ... column_n column_type );
Alter Table… ALTER TABLE table_name DROP COLUMN column_name; ALTER TABLE table_name  SET UNUSED column_name; ALTER TABLE table_name RENAME COLUMN old_name to new_name;
Alter Table… The Rules for Adding or Modifying a Column You may add a column at any time if  NOT NULL  isn’t specified. You may add a  NOT NULL  column in three steps: Add the column without  NOT NULL  specified. Fill every row in that column with data. Modify the column to be  NOT NULL .
Alter Table… These are the rules for modifying a column: You can increase a character column’s width at any time. You can increase the number of digits in a NUMBER column at any time. You can increase or decrease the number of decimal places in a NUMBER column at any time. In addition, if a column is  NULL  for every row of the table, you can make any of these changes: You can change the column’s datatype. You can decrease a character column’s width. You can decrease the number of digits in a NUMBER column.
Alter Table… e.g. - Alter table mytable Add constraint pk_mytable PRIMARY KEY (a); - alter table mytable  add b varchar2(50); Alter table emp_hourly  MODIFY (HOURRATE NUMBER(5,2) DEFAULT 7.25); Alter table mytable RENAME CLOUMN a TO z; - Alter table mytable RENAME to mynewTable;
RENAME e.g. Rename mynewtable to mytable; RENAME old_table_name TO new_table_name;
DROP Table e.g. DROP table mytable; DROP TABLE table_name;
PL/SQL Chapter 6
PL/SQL Lesson Objectives Introduction to PL/SQL SQL Review Basic PL/SQL Trigger Store Procedure and Function Package
Introduction What is PL/SQL: PL is stand for Procedural Language. PL/SQL= {Procedural or Structure Programming Language} + SQL PL/SQL is a procedural programming language which improving from SQL Language by added structured programming feature in order to process business logic of information system.
Feature of PL/SQL PL/SQL use to develop business logic layer of application which run on server-side. Feature of Server-Side Code are: - Good performance - Reduce network traffics - High security - High reusable
SQL There are 3 types of SQL Command: DDL: Data Definition Language . There are follow command of DDL - Create : for creating objects -  Alter: for modifying objects - Drop: for removing objects DML (Data Manipulated Language):  Use to manipulate data. DML Consist of  - Select - Insert - Delete - Update DCL(Data Control Lanaguage) begin tran, commit,rollback,save tran
DML (Continue) Select Statement: for reading data from databases, the select statements return rows from tables: Syntax: Select *|Col1,Col2,….. From Table | Joined Tables [Where Condition] [Group By Col1,Col2,…] [Having Condition] [Order by Col1,Col2,…]
Transaction SQL Insert:  for inserting records into tables: Syntax1: Insert Into Table_Name[(Col1,Col2,…)] Values(val1,val2,…) Syntax2 Insert Into Table_Name[(Col1,Col2,…)] Select co1l,col2,…from TableName…. Delete:  for removing records (data) into tables: Delete from Table_Name [Where Condition] Update:  for modifying records (data) in tables: Update Table_Name set Col1=Expr,Col2=Expr,… [Where Condition]
Basic PL/SQL Declare Variable: PL/SQL is a structure programming language. Before use a variable must be declare above the body of program. Syntax: Declare varname1 Datatype[:=initialvalue];    VarName Datatype[:=initialvalue]; Example Declare  x integer; Str varchar2(20):=‘BBU’;
PL/SQL Data Type PL/SQL Data Type is similar to Oracle Database Data Type, However the size of some data type is difference Example varchar2 in database is 4K in pl/sql is 32k %TYPE  is use to declare a variable to match with the other. Example Declare  s varchar2(20); s1 s%type; pcode tblProducts.ProductCode%Type; %RowType  is use to declare a variable to match a record type of a table or cursor. Example Declare prow tblProducts%RowType
Assignment and Operator Assignment is most important operator. In oracle we can assign to a variable an expression or value which on memory or we can select a value from a column or row of table then assign direct to variable. Syntax1: VarName:=Expression; Syntax2  Select Col1,Col2,…. INTO var1,var2 from tablename,. [Where Condition] Syntax 1 is assign a value or expression value to varname Syntax 2: is select a single row of data  of col1,col2 from table  then assign to var1,var2
Assignment (Cont) Example: Declare Code Varchar2(10); price float; Qty Integer; … … .. -- Assign  ‘P001’ to Code Code:=‘P001’; -- Select Quatity and UnitPrice from tblProducts then assign to price and Qty. Select Quantity,UnitPrice Into Qty, Price from tblProducts  Where ProductCode=‘P001’;
Operator
Control Structure IF Statement Syntax: If Condition then Statements; [elsif condition then statements; Elsif condition then statements; … ..] [Else statements; ] End if;
Loop Statement Syntax Loop Statement1; Statement2; Exit When Condition; … . End Loop; Loop execute by repeating statement1,statement2,....  To exit loop use following: Exit When Condition or if Condition Then Exit
While Loop Syntax While Condition Loop Statement1; Statement2; ……………… . End loop;
For Statement In oracle for statement can be used to loop and scan value in collection of value or collection of records the counter variable will automatic define it data type to match collection. Syntax For counter IN Collection Loop Statements; Statements; Statements; End Loop;
For Statement Example: for I in 1..100 loop Statements; end loop; -- statement I run from 1 to 100 For pRow IN (Select * from tblProducts) Loop Statements; END LOOP; In above statement pRow is a record variable which will be stored each record.
Case Statement In oracle case statement, use to return value like a value. Syntax1: Case When Condition Then Value1 When Condion Then  Value2 … .. [else valN] END Syntax 2 Case Expression    When val1 Then Value1 When val2 Then Value2 [else valN] END;
CURSOR Cursor is a data type which its variable use to store address of records returned from select statement. Declare Cursor Cursor_Name[(Parameter,…)] is select  statement; To use cursor first open cursor then read data from cursor parse to variable Syntax Open Open Cursor_name[(arg,…)] Syntax Read Fetch Cursor_Name into var_name; Var_name must be declare as Cursor_name%rowtype. The fetch statement always move next rows while eof the Attribute  cursor_name%notfound=true Close Cursor Close Cursor_Name
Trigger Trigger is a special procedure or sub program is bound to a table’s transaction and will be execute when the bound table receive transaction. There two type of Trigger: Row Trigger and Statement Trigger Row trigger is trigger which will execute every row effect by transaction. Statement trigger is execute a time for every statement. It’s does not depend on how many rows created by transaction
Trigger Syntax: Create [or replace] trigger  trigger_name  After|Before  Transaction On  Table_name [For Each row ] [When condition] --Declare parts Begin --PL/SQL Codes; End; Transaction : [INSERT [Or Delete Or [Update [of ColumnName,…]]]
Trigger :New and :Old :New is a trigger parameter store the inserted records and new records of update statement. :Old  is a trigger parameter store the deleted records and previous records of update statement. INSERTING,DELETING,UPDATING is a Boolean parameter use to recognize transaction type.
Procedure and Function Create [Or Replace] Procedure Name-Of-Procedure(Par,…..) IS --Variable declaration Begin --PL/SQL Statement; End; Create Or Replace Function Name-Of-Function (Par,…..) Return DataType IS --Variable declaration Begin --PL/SQL Statement; Return Value,-- return the value to function End;
Procedure and Function Parameters are variable use for receiving value from argument and parsed value to arguments. Syntax: Par-Name [IN|OUT|IN OUT] DataType IN parameters use to receive value only from clients; OUT Parameter use to parse value from server to client’s arguments. IN OUT parameter for both receive and parsed. Parameter cannot specific size
Oracle Security Chapter 7
Learning Topics: Create Users Privileges and Granting Privileges Role Auditing Users
Create Users A user is a key to access database. An user must be provided some privileges (right) for access database objects and perform tasks. Syntax Create User Create User  UserNam e  Identified by  password [Password expire] [Default Tablespace  name-of-tablespace ] [Temporary tablespace  name-of-temporary-tablespace ] [Quota  {Size|Unlimited}  on  Tablespace-Name ] ---------;
Create Users(Continue) - User-Name must be string and no duplicate Password is user password Password Expire an option for user change password at first time log on Default tablespace is tablespace to store object will be created by users. Temporary tablespace is name of temporary tablespace will store data query of users. Quota is the permission to use tablespace
Create User (Example) Ex1 Create User BBUMSC Identified by bbu Password Expire Default tablespace users Temporary tablespace temp Quota 100M on Users; Ex2: Create User BBUCEO Identified by bbumanager Temporary tablespace temp;
Privileges Privilege is right to access oracle system: There are two type of Privileges System Privilege And Object Privileges System Privileges: Right to access system resources. System Privileges consist of: Create Session  Select ANY TABLE INSERT ANY TABLE UPDATE ANY TABLE DELETE ANY TABLE CREATE TABLE,CREATE VIEW,CREATE TABLESPACE,….
Privileges (Continue) Granting System Privileges: Grant Privileges,… to USERNAME [With Grant Option] Example Grant Create Session,Select Any Table,Create Tablespace,Create Table to BBUMSC;
Privileges (Continue) Are right to access data in table, view and execute store procedure, function and package: Object Privileges consist of: Select Insert Delete Update Execute Syntax: Granting Object Privileges: Grant All|Select,Insert On ObjectName to UserName [With Grant Option]; Example: Grant All on Students to BBUMSC;
Roles Role is a set of privileges use to grant to users. Syntax Create Role: Create Role RoleName; To grant privileges to role is the same user. Example: Create Role StudentRole; Grant create session,Select any table to StudentRole; Grant StudentRole to BBUMSC;
Auditing User Use to control action of users who access to oracle system. Syntax: Audit option,.. [by user] [by access|by session] [whenever [not] successful]; Audit Option - Select Table - Delete Table - Update Table - Insert Table - Session - ……..
Auditing User (Continue) To set audit user: - Set Parameter file  AUDIT_TRAIL=True - User Audit Command - Check Audit on view
End of Chapter 7
Oracle Backup & Recovery Chapter 8
Oracle Backup & Recovery 4-1 Backup/Recovery Basic 4-2 Oracle Backup/Recovery Configuration 4-3 Physical Backups 4-4 Types of Failure and Troubleshooting 4-5 Oracle Recovery without Archiving 4-6 Complete Recovery with Archiving  4-7 Incomplete Recovery with Archiving 4-8 Recovery when loss of Control Files / Online Redo Logfiles
Oracle backup/recovery basic Backup methods Backup strategy
Backup methods Logical backup export/import Database, user, table, table partition full increasement Physical backup cold/offline backup full increasement hot/online backup full Increasement archive log backup
Backup strategy Determinded by  Business Technical Management Mean-time to recover
Determine backup strategy Ask customer: What’s your backup strategy now? How many data can you loss? How long can your database be shutdonw? How long can you allow to backup? How long can you allow to recover? How many archived logs per day? How many free disk space do you have to store the archived logs? Do you consider about standby database?
Objectives Identify recovery implications of operating in “Noarchive” mode Describe the differences between “Archivelog” mode and “Noarchivelog” mode Configure a database for “Archivelog” mode and automatic archiving Use  init.ora  parameters to duplex archive log files
Overview Noarchivelog or Archivelog Mode Decision to use one or the other is dependent upon how much data can be lost due to a failure.
Online redo  log files 053 No redo history NOARCHIVELOG Mode 054 054 053 053 LGWR
Archivelog Mode Online redo  log files LGWR Archived log files 054 054 053 053 053 052 051 Redo history
Configuring for Archiving ARCH LOG_ARCHIVE_DEST=/archive/arch LOG_ARCHIVE_FORMAT=%s.arc /archive/arch052.arc Archived log file Online redo log files 053 053 052 Group 1 Group 2 052 052
Duplexing Archived Log Files ARCH Online redo log files 053 053 052 052 LOG_ARCHIVE_DUPLEX_DEST 052 052 Group 1 Group 2 LOG_ARCHIVE_DEST Archived log files
Changing Database Archive Modes Startup and mount the database Alter the mode of the database Shutdown in normal or immediate Take a full closed database backup Startup and open the database
Enabling Archive Processing Automatic archiving Manual archiving ARCH 053 053 053 053 DBA
Manual Archive ALTER SYSTEM ARCHIVE LOG all; 1 2 ARCH 052 051 052 3 051 Online redo logs
Automatic Archiving ARCH 052 051 Archived log files 053 051 052 Archived Archived Current LOG_ARCHIVE_START=TRUE Online redo logs
Obtaining Archive Log Information V$ARCHIVE_DEST V$ARCHIVED_LOG V$LOG_HISTORY Data dictionary views Command line ARCHIVE LOG LIST; V$DATABASE
Summary Complete database recovery requires: Archivelog mode Automatic archiving A database backup immediately after it is put into archivelog mode
Exercise 4-2 1. See database is running on archive or noarchive log mode: svrmgr>select * from v$database; 2. Set database to archive log mode: Edit init_sid.ora files archive_log_dest archive_log_format (see  Oracle References  about values) log_archive_start svrmgr> shutdown immediate; svrmgr> startup mount; svrmgr> alter database archivelog; svrmgr> alter database open;
Exercise 4-2 3. Check archive log configuration: Check the archive process: $ps –ef|grep arch Check archive log parameters: svrmgr> show parameter arch
Objectives Perform database backups using operating system commands Describe the recovery implications of closed and open database backups Perform closed(offline) and open(online) database backups Identify the different types of control file backups List the data dictionary views useful for backup operations
Backup methods Logical backup export/import Database, user, table, table partition full increasement Physical backup cold/offline backup full increasement hot/online backup full Increasement archive log backup
Backup Methods Physical backup Closed database Open database Archive Mode No archive Mode
Closed Database Backup Datafiles Control  Files Password File Online or Offline Storage Parameter Files Redo Log Files
Advantages of Closed Database Backups Conceptually simple Easy to perform Requires little operator interaction Reliable
Database File Information Data dictionary views V$DATAFILE V$CONTROLFILE V$LOGFILE DBA_DATA_FILES
Performing a Closed Database Backup 2 3 4 SHUTDOWN IMMEDIATE;  HOST cp <files> /backup/ STARTUP OPEN;  Data Files Control Files Parameter Files 1
Open Database Backup Datafiles Control Files Parameter Files Archived Redo Log Files Password File Online Redo Log Files
Advantages of Open Database Backups Maintains high database availability Can be done at a tablespace or datafile level Allows recovery to point-in-time
Archived Log Files ARCH Archivelog Mode Online Redo Log Files LGWR 054 054 053 053 052 051 Open Database Backup Requirements 053
Open Database Backup Options All tablespace datafiles Tablespace USER_DATA user02.dbf user01.dbf Individual datafile user02.dbf Tablespace USER_DATA user01.dbf
Performing an Open Database Backup 1 ALTER TABLESPACE user_data BEGIN BACKUP;  2 HOST cp <files> /backup/ 3 ALTER TABLESPACE user_data END BACKUP;
Backup Status Information Data dictionary views: V$BACKUP V$DATAFILE_HEADER
Backing Up a Control File Creating a binary image: alter database backup controlfile to ‘control1.bkp’; Creating a text trace file: alter database backup controlfile to trace;
Exercise 4-3 1. Cold backup: Shutdown database Copy datafile, control file, logfile, init file, password file to other place 2. Hot backup: svrmgr>ALTER TABLESPACE system BEGIN BACKUP; svrmgr>host cp /abc/system01.dbf /backup svrmgr>ALTER TABLESPACE system END BACKUP;
Categories of Failures Statement failure User process failure User error Instance failure Media failure
Causes of Statement Failures Logic error in an application Attempt to enter bad data into the table Attempt an operation with insufficient privileges Attempt to create a table but exceed allotted quota limits Attempt an INSERT or UPDATE to a table, causing an extent to be allocated, but with insufficient free space left in the tablespace
Resolutions for Statement Failures Correct logic flow of the program Modify and reissue the SQL statement Provide the necessary database privileges Change the user’s quota limit by using the ALTER USER command Add file space to the tablespace
Causes of User Process Failures The user performed an abnormal disconnect in the session The user’s session was abnormally terminated The user’s program raised an address exception terminating the session
Resolving User Process Failures The PMON process detects an abnormally terminated server process PMON rolls back the transaction and releases any resources and locks being held by it
Possible User Error Failures SQL> DROP TABLE Employee;  SQL> TRUNCATE TABLE Employee; SQL> UPDATE Employee SET SALARY =  SALARY * 1.5; SQL> COMMIT;  SQL> DELETE FROM Employee;
Resolving User Errors Train the database users Recover from a valid backup Bring back a table export Perform a point-in-time recovery
Causes of Instance Failure Power outage Hardware failures CPU Memory Disk failure Background process failure
Recovery from Instance Failure No special recovery action required Start the instance Open the database Notify users
Instance Recovery Process Unsynchronized files Roll-forward process Committed and uncommitted data in files Rollback process Committed data in data files Synchronized files
Causes of Media Failure Head crash on disk drive Physical problem reading or writing to database files File was accidentally erased
Resolving Media Failures The recovery strategy depends upon which backup method was chosen and which files are affected If available, apply archived redo log files to recover data committed since the last backup
Database Synchronization All data files (except offline and read-only) must be synchronized for the database to open Synchronization is based on the current checkpoint number Applying redo logs synchronizes files Redo logs are automatically requested by Oracle
The Alert Log File Records informational and error messages for Oracle Reflects the ongoing status of the system Continuously written to, with new messages being appended to the end of the alert file Shows date and time of startup, shutdown, recovery operations, and so on
Oracle Trace Files Created by Oracle background processes Written to destination specified by parameter BACKGROUND_DUMP_DEST Source of additional diagnostic information
Summary Understand the types of failures and the degree of DBA intervention Locate error messages in the alert log and trace files
Exercise 4-4 View alert log to calculate archive log size per day
Objectives Note the implications of media failure with a database in noarchivelog mode Recover a database in noarchivelog mode after media failure Restore files to a different location if media failure occurs
Overview Database Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 146 145 146 146 146 146 Instance SGA Redo Log   Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA User Process Server Process PGA Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 144 145 144 144 144 144
Media Failure and Recovery Without Archiving Failure Loss of disk, datafile, or corruption Recovery Restore all datafiles, control files, and redo logs Restoring password and parameter files is optional
Recovery Without Archiving Advantages Easy to perform, with low risk of error Recovery time = Time to restore all files Disadvantages Data is lost and must be reapplied manually The entire database is restored to the point of the last whole closed backup
Recovery Without Archiving Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database 145 146 146 146 146 146 Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Backup 143 144 144 144 144 144 Restore most recent backup Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database 143 144 144 144 144 144
Restoring to a Different Location Rename the file or directory location: SVRMGR> connect system/manager as sysdba; Connected. SVRMGR> startup mount pfile=initDB00.ora; Oracle instance started. SVRMGR> alter database rename file  2>  ‘/disk1/data/user_01.dbf’  3> to ‘disk2/data/user_01.dbf’; Statement Processed. SVRMGR> alter database open;
Overview Database Database Password File Archived Log Files Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 146 145 146 146 146 146 User Process Server Process PGA Data  File 2 146 Instance SGA Redo Log   Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH Data Buffer   Cache
Media Failure and Recovery with Archiving Failure Loss of disk, datafile, or corruption Recovery Datafiles for restore must be offline Restore only lost or damaged datafiles Do not restore the control file, redo logs, password, or parameter files Recover the datafiles
Recovery with Archiving (Complete Recovery) Advantages Only need to restore lost files Recovers all data to the time of failure Recovery time = Time to restore lost files and apply all archived logs Disadvantages Must have all archived logs since the  backup from which you are restoring
Complete Recovery Methods 1.  Closed database recovery: For system, rollback segment data files, or whole database 2.  Open database recovery, with database initially open: For file loss 3.  Open database recovery with database initially closed: For hardware failure 4. Recover a datafile with no backup
Complete Recovery: Method 1  145 146 Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database 146 145 146 146 146 146 Archived Log File 144 Restore Data File 2 (Log Seq   144) Data  File 2 144 1 Instance SGA Redo Log   Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Instance SGA Redo Log   Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Mount Instance 2 Data Buffer   Cache Apply Log  Files 3 Open the database 4
Complete Recovery: Method 2  Instance SGA Redo Log   Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL ARCH 145 146 Data Buffer   Cache Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database 146 145 146 146 146 146 Archived Log File 144 Offline Data File 2 Data  File 2 146 1 PMON DBWR SMON LGWR CKPT User Process Server Process PGA Restore Data File 2 (Log Seq   144) Data  File 2 144 2 Apply Log Files 3 Online Data File 2 Data  File 2 146 4
Complete Recovery: Method 3  145 146 Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database 146 145 146 146 146 146 Archived Log File 144 Mount the database 1 Instance SGA Redo Log   Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH Instance SGA Redo Log   Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Data Buffer   Cache Offline Data File 2 Data  File 2 146 2 Open Database 3 Restore Data File 2 (Log Seq   144) Data  File 2 144 4 Apply Log Files 5 Online Data File 2 Data  File 2 146 6
Complete Recovery: Method 4  145 146 Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database 146 145 146 146 146 146 Archived Log File 144 Offline Data File 2 Data  File 2 146 1 Recreate Data File 2 (Log Seq   144) Data  File 2 144 2 Apply Log Files 3 Online Data File 2 Data  File 2 146 4 Instance SGA Redo Log   Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Data Buffer   Cache
Recover Syntax Recover a closed database:  SVRMGR> recover database; SVRMGR> recover datafile    >  ‘/disk1/data/df2.dbf’; SVRMGR> alter database recover; SVRMGR> recover tablespace USER_DATA; SVRMGR> recover datafile 2; SVRMGR> alter database recover datafile 2; Recover an open database:
Recovery Using Archived Logs To change archive location, use the ‘alter system archive log …’ command To automatically apply redo log files: Issue ‘set autorecovery on’ before starting media recovery Enter ‘auto’ when prompted for an archived log file Use the ‘recover automatic’ command
Files Needed for Recovery View V$RECOVER_FILE to locate datafiles needing recovery View V$ARCHIVED_LOG for a list of all archived logs for the database View V$RECOVERY_LOG for a list of all archived logs required for recovery
Overview Database Password File Archived Log Files Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 146 145 146 146 146 146 Instance SGA Redo Log   Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA User Process Server Process PGA
Reasons for Incomplete Recovery User error Complete recovery fails because an archived log is lost Recovery using a backup control file Loss of all unarchived redo logs and the datafile
Recovery with Archiving (Incomplete Recovery) Advantages Recovers prior to the time of failure Provides recovery in situations where complete recovery is not possible Disadvantages Database taken back in time (lose data) Recovery time = Time to restore all datafiles + apply required archived logs
Types of Incomplete Recovery Time-based recovery Cancel-based recovery Recovery using a backup control file Change-based recovery
“ recover” Command Syntax Recover a database until cancel:  SVRMGR> recover database until cancel; SVRMGR> recover database 2>  until time ‘1997-12-04:14:22:03’; Recover a database until time:  SVRMGR> recover database  2>  until time ‘1997-12-04:14:22:03’ 3>  using backup controlfile; Recover using backup control file:
Recovery Steps 1. Shut down and backup the database 2. Restore all data files 3. Do not restore the control file, redo logs,  password, or parameter files 4. Mount the database and recover the datafiles before the time of failure 5. Open the database with “resetlogs” 6. Perform a closed database backup
Recovery Guidelines Follow/Record all steps since most errors occur during this type of recovery Take whole database backup before and after recovery to assist future recovery Always check if recovery is successful Backup the control file regularly Backup archived logs
Time-Based Recovery Scenario: The current time is 12 PM on 9-DEC-97 Your training DBA just told you he  dropped the employee (EMP) table The table was dropped around  11:45 AM Database activity is minimal because most staff are currently in a meeting The table must be recovered
“ Until Time” Recovery Instance SGA Redo Log   Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA User Process Server Process PGA Shutdown and backup the database 1 Mount database 2 Instance SGA Redo Log   Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH Password File Parameter File Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 Database EMP 146 145 146 146 146 146 Archived Log File 144 Restore all Data Files (Log Seq   144) 3 Data  File 3 Data  File 2 Data  File 1 144 144 144 EMP 4 5 145 145 145 146 145 145 145 145 146 Data  File 3 Redo log File 2 Data  File 2 Control  Files Redo log File 1 Data  File 1 1 0 1 1 1 1 EMP Open Database 揜 esetlogs 6 User Process Server Process PGA User Process Server Process PGA Backup database 7
Cancel-Based Recovery Scenario: The current time is 12 PM on 9-DEC-97 Your training DBA dropped the EMP table while trying to fix bad blocks Log files exist on the disk containing the employee data file The table was dropped around  11:45 AM
Cancel-Based Recovery Findings: Redo logs are not multiplexed One of the online redo logs is missing The missing redo log is not archived The redo log contained information from 11:34 AM Twenty six minutes of data will be lost Users can recover their data
Backup Control File Recovery Scenario: The current time is 12 PM on 9-DEC-97 Your training DBA dropped the entire employee tablespace, not just the table The error occurred around 11:45 AM Many employee records were updated this morning, but not since 11:00 AM Backups are taken every night
Backup Control File Recovery Findings: The backup last night contains datafiles and control files required for recovery  Employee tablespace has one datafile The current log sequence number is 61 You confirm that the tablespace was dropped at 11:44:54 AM on 9-DEC-97. Datafile number 4 is offline.
Recover database syntax RECOVER [AUTOMATIC] DATABASE  [USING BACKUP CONTROLFILE]  [UNTIL < CANCEL | TIME date | CHANGE integer> ] [NOPARALLEL | PARALLEL [integer] ]
Loss of control files Should not loss of all control files if configured multiple control files If loss all control files: Method 1: Recreate control file Method 2: Restore backup control file
Recreate control files You must get all database structure before recreate control files
Recreate control file svrmgr>alter database backup controlfile to trace; The create control file command will exist in the latest trace file Edit the trace file and save to script Run the create control file script
Restore backup control file Restore backup control file svrmgr> recover database using backup controlfile;
Loss of a Redo Log File Loss of a Redo Log file: Archiving still occurs using a good online redo log file Loss of all redo log files for a group should ‘NEVER’ occur if the database is configured properly using mirrored redo log files
Redo Log File Recovery Non-Current logs: Add group, drop group Current logs: If database shutdown normally: 1. Recover database until cancel 2. Alter database open resetlogs If database shutdown abnormally: Have backups: Restore from backups RECOVER DATABASE UNTIL CANCEL and cancel when prev log applied No backup Can be startup in a corruption status Ask Oracle support
Scenario 1 Loss of non-current logfiles: svrmgr>alter database add logfile ‘new_file_name’ size 1m; svrmgr>alter database drop logfile <‘old_file_name’ | group n>
Scenario 2 Loss of current logfile and instance is shutdown normally: svrmgr>recover database until cancel; cancel svrmgr>alter database open resetlogs;
Scenario 3 Loss of current logfile and instance is shutdown abnormally: Have backups Restore backups svrmgr>recover database until cancel; svrmgr>alter database open resetlogs; No backups Ask Oracle support _allow_resetlogs_corruption in init_sid.ora svrmgr>recover database using backup controfile until cancel; svrmgr>alter database open resetlogs; Export database
Ad

More Related Content

What's hot (13)

Introduction to oracle
Introduction to oracleIntroduction to oracle
Introduction to oracle
Madhavendra Dutt
 
Less04 Instance
Less04 InstanceLess04 Instance
Less04 Instance
vivaankumar
 
Oracle Database Introduction
Oracle Database IntroductionOracle Database Introduction
Oracle Database Introduction
Chhom Karath
 
Introduction to oracle
Introduction to oracleIntroduction to oracle
Introduction to oracle
Sumit Tambe
 
Oracle architecture
Oracle architectureOracle architecture
Oracle architecture
Sandeep Kamath
 
Introduction to oracle(2)
Introduction to oracle(2)Introduction to oracle(2)
Introduction to oracle(2)
Sumit Tambe
 
Oracle 10g Introduction 1
Oracle 10g Introduction 1Oracle 10g Introduction 1
Oracle 10g Introduction 1
Eryk Budi Pratama
 
Oracle DBA
Oracle DBAOracle DBA
Oracle DBA
shivankuniversity
 
Oracle db architecture
Oracle db architectureOracle db architecture
Oracle db architecture
Simon Huang
 
Oracle RDBMS architecture
Oracle RDBMS architectureOracle RDBMS architecture
Oracle RDBMS architecture
Martin Berger
 
Overview of oracle database
Overview of oracle databaseOverview of oracle database
Overview of oracle database
Samar Prasad
 
12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
Amrit Kaur
 
Oracle architecture ppt
Oracle architecture pptOracle architecture ppt
Oracle architecture ppt
Deepak Shetty
 
Oracle Database Introduction
Oracle Database IntroductionOracle Database Introduction
Oracle Database Introduction
Chhom Karath
 
Introduction to oracle
Introduction to oracleIntroduction to oracle
Introduction to oracle
Sumit Tambe
 
Introduction to oracle(2)
Introduction to oracle(2)Introduction to oracle(2)
Introduction to oracle(2)
Sumit Tambe
 
Oracle db architecture
Oracle db architectureOracle db architecture
Oracle db architecture
Simon Huang
 
Oracle RDBMS architecture
Oracle RDBMS architectureOracle RDBMS architecture
Oracle RDBMS architecture
Martin Berger
 
Overview of oracle database
Overview of oracle databaseOverview of oracle database
Overview of oracle database
Samar Prasad
 
12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
Amrit Kaur
 
Oracle architecture ppt
Oracle architecture pptOracle architecture ppt
Oracle architecture ppt
Deepak Shetty
 

Viewers also liked (7)

Online portfolio
Online portfolioOnline portfolio
Online portfolio
Chelsea Goodman
 
Lwm
LwmLwm
Lwm
sarita
 
JoyStudy
JoyStudyJoyStudy
JoyStudy
thysothea
 
Agile management jan2011
Agile management jan2011Agile management jan2011
Agile management jan2011
mahalp2
 
Fostering self organization – ten ninja techniques for managers
Fostering self organization – ten ninja techniques for managersFostering self organization – ten ninja techniques for managers
Fostering self organization – ten ninja techniques for managers
mahalp2
 
G5 Mrs Booth-group 1 :Atlantis's adventure
G5 Mrs Booth-group 1 :Atlantis's adventureG5 Mrs Booth-group 1 :Atlantis's adventure
G5 Mrs Booth-group 1 :Atlantis's adventure
vduvieusart
 
G5 Mr Kanter group1
G5 Mr Kanter group1G5 Mr Kanter group1
G5 Mr Kanter group1
vduvieusart
 
Agile management jan2011
Agile management jan2011Agile management jan2011
Agile management jan2011
mahalp2
 
Fostering self organization – ten ninja techniques for managers
Fostering self organization – ten ninja techniques for managersFostering self organization – ten ninja techniques for managers
Fostering self organization – ten ninja techniques for managers
mahalp2
 
G5 Mrs Booth-group 1 :Atlantis's adventure
G5 Mrs Booth-group 1 :Atlantis's adventureG5 Mrs Booth-group 1 :Atlantis's adventure
G5 Mrs Booth-group 1 :Atlantis's adventure
vduvieusart
 
G5 Mr Kanter group1
G5 Mr Kanter group1G5 Mr Kanter group1
G5 Mr Kanter group1
vduvieusart
 
Ad

Similar to ora_sothea (20)

MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
Douglas Bernardini
 
Capitulo 01 Dba 2
Capitulo 01 Dba 2Capitulo 01 Dba 2
Capitulo 01 Dba 2
Julio Pari
 
App D
App DApp D
App D
Sudharsan S
 
Less02 Installation
Less02 InstallationLess02 Installation
Less02 Installation
vivaankumar
 
Less02 Installation
Less02  InstallationLess02  Installation
Less02 Installation
vivaankumar
 
Sg1 Cover Page
Sg1 Cover PageSg1 Cover Page
Sg1 Cover Page
vivaankumar
 
Introduction to oracle
Introduction to oracleIntroduction to oracle
Introduction to oracle
durgaprasad1407
 
Oracle DBA Training in Hyderabad
Oracle DBA Training in HyderabadOracle DBA Training in Hyderabad
Oracle DBA Training in Hyderabad
united global soft
 
Oracle DBA Training in Hyderabad
Oracle DBA Training in HyderabadOracle DBA Training in Hyderabad
Oracle DBA Training in Hyderabad
Ugs8008
 
Orcale dba training
Orcale dba trainingOrcale dba training
Orcale dba training
Ugs8008
 
Ora01_OraArc.pdf
Ora01_OraArc.pdfOra01_OraArc.pdf
Ora01_OraArc.pdf
NamNguynMu
 
R12 d49656 gc10-apps dba 07
R12 d49656 gc10-apps dba 07R12 d49656 gc10-apps dba 07
R12 d49656 gc10-apps dba 07
zeesniper
 
Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...
Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...
Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...
united global soft
 
Orcale dba Online training India
Orcale dba Online training IndiaOrcale dba Online training India
Orcale dba Online training India
united global soft
 
Orcale DBA Online Training in India
Orcale DBA Online Training in IndiaOrcale DBA Online Training in India
Orcale DBA Online Training in India
united global soft
 
Oracle DBA Online Training in India
Oracle DBA Online Training in IndiaOracle DBA Online Training in India
Oracle DBA Online Training in India
united global soft
 
Orcale dba training
Orcale dba trainingOrcale dba training
Orcale dba training
united global soft
 
Oracle DBA Training in Hyderabad
Oracle DBA Training in HyderabadOracle DBA Training in Hyderabad
Oracle DBA Training in Hyderabad
united global soft
 
Oracle DBA Online Trainingin India
Oracle DBA Online Trainingin IndiaOracle DBA Online Trainingin India
Oracle DBA Online Trainingin India
united global soft
 
ORACLE Architechture.ppt
ORACLE Architechture.pptORACLE Architechture.ppt
ORACLE Architechture.ppt
aggarwalb
 
Capitulo 01 Dba 2
Capitulo 01 Dba 2Capitulo 01 Dba 2
Capitulo 01 Dba 2
Julio Pari
 
Less02 Installation
Less02 InstallationLess02 Installation
Less02 Installation
vivaankumar
 
Less02 Installation
Less02  InstallationLess02  Installation
Less02 Installation
vivaankumar
 
Oracle DBA Training in Hyderabad
Oracle DBA Training in HyderabadOracle DBA Training in Hyderabad
Oracle DBA Training in Hyderabad
united global soft
 
Oracle DBA Training in Hyderabad
Oracle DBA Training in HyderabadOracle DBA Training in Hyderabad
Oracle DBA Training in Hyderabad
Ugs8008
 
Orcale dba training
Orcale dba trainingOrcale dba training
Orcale dba training
Ugs8008
 
Ora01_OraArc.pdf
Ora01_OraArc.pdfOra01_OraArc.pdf
Ora01_OraArc.pdf
NamNguynMu
 
R12 d49656 gc10-apps dba 07
R12 d49656 gc10-apps dba 07R12 d49656 gc10-apps dba 07
R12 d49656 gc10-apps dba 07
zeesniper
 
Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...
Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...
Oracle DBA Online Training in India,Oracle DBA Training in USA,Oracle DBA Tra...
united global soft
 
Orcale dba Online training India
Orcale dba Online training IndiaOrcale dba Online training India
Orcale dba Online training India
united global soft
 
Orcale DBA Online Training in India
Orcale DBA Online Training in IndiaOrcale DBA Online Training in India
Orcale DBA Online Training in India
united global soft
 
Oracle DBA Online Training in India
Oracle DBA Online Training in IndiaOracle DBA Online Training in India
Oracle DBA Online Training in India
united global soft
 
Oracle DBA Training in Hyderabad
Oracle DBA Training in HyderabadOracle DBA Training in Hyderabad
Oracle DBA Training in Hyderabad
united global soft
 
Oracle DBA Online Trainingin India
Oracle DBA Online Trainingin IndiaOracle DBA Online Trainingin India
Oracle DBA Online Trainingin India
united global soft
 
ORACLE Architechture.ppt
ORACLE Architechture.pptORACLE Architechture.ppt
ORACLE Architechture.ppt
aggarwalb
 
Ad

Recently uploaded (20)

GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 

ora_sothea

  • 2. Course Objectives After completing this course, you should be able to do the following: Install, create, and administer Oracle Database 10 g Understand Oracle SQL and PL/SQL Configure the database for an application Create and Configure Oracle Distributed Database Can Perform Backup, Restore and Recover Database
  • 3. Lesson Objectives After completing this lesson, you should be able to do the following: Explain the Oracle Database architecture
  • 4. Oracle Products and Services Oracle databases Oracle Application Server Oracle applications Oracle Collaboration Suite Oracle Developer Suite Oracle services
  • 5. Oracle Database Architecture An Oracle server: Is a database management system that provides an open, comprehensive, integrated approach to information management Consists of an Oracle Service , Oracle instance and an Oracle database
  • 6. Database Structures Storage structures Memory structures Process structures Instance Database files DB structures - Memory - Process - Storage Oracle Service System Global Area (SGA) Background processes
  • 7. Oracle Memory Structures . Database buffer cache Redo log buffer Shared pool Large pool SGA Streams pool Server process 1 PGA Server process 2 PGA Background process PGA DB structures > Memory Process Storage
  • 8. Process Structures User process: Is started at the time a database user requests a connection to the Oracle server Server process: Connects to the Oracle instance and is started when a user establishes a session Background processes: Are started when an Oracle instance is started Instance Background processes Server process PGA User process DB structures Memory > Process Storage SGA
  • 9. Oracle Instance Management System Monitor (SMON) Database Writer (DBW n ) LogWriter (LGWR) Process Monitor (PMON) Archiver (ARC n ) SGA Java pool Shared pool Large pool Streams pool Database buffer cache Redo log buffer Checkpoint (CKPT) Control files Data files Redo log files Archive log files
  • 10. Server Process and Database Buffer Cache Buffers: Pinned Clean Free or unused Dirty Server process SGA Database buffer cache Data files DBW n
  • 11. Physical Database Structure . Online redo log files Password file Parameter file Archive log files Control files Data files Alert and trace log files Backup files DB structures Memory Process > Storage
  • 12. Tablespaces and Data Files Tablespaces consist of one or more data files. Data files belong to only one tablespace. Data file 1 Data file 2 USERS tablespace
  • 13. SYSTEM and SYSAUX Tablespaces The SYSTEM and SYSAUX tablespaces are mandatory tablespaces. They are created at the time of database creation. They must be online. The SYSTEM tablespace is used for core functionality (for example, data dictionary tables). The auxiliary SYSAUX tablespace is used for additional database components (such as the Enterprise Manager Repository).
  • 14. Segments, Extents, and Blocks Segments exist within a tablespace. Segments are made up of a collection of extents. Extents are a collection of data blocks. Data blocks are mapped to disk blocks. Segment Extents Data blocks Disk blocks
  • 15. Logical and Physical Database Structures Database Logical Physical Tablespace Data file OS block Segment Extent Oracle data block Schema
  • 17. Course Examples: The HR Schema REGIONS REGION_ID (PK) REGION_NAME COUNTRIES COUNTRY_ID (PK) COUNTRY_NAME REGION_ID (FK) LOCATIONS LOCATION_ID (PK) STREET_ADDRESS POSTAL_CODE CITY STATE_PROVINCE COUNTRY_ID (FK) DEPARTMENTS DEPARTMENT_ID (PK) DEPARTMENT_NAME MANAGER_ID LOCATION_ID (FK) JOBS JOB_ID (PK) JOB_TITLE MIN_SALARY MAX_SALARY EMPLOYEES EMPLOYEE_ID (PK) FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID (FK) SALARY COMMISION_PCT MANAGER_ID (FK) DEPARTMENT_ID (FK) JOB_HISTORY EMPLOYEE_ID (PK) START_DATE (PK) END_DATE JOB_ID (FK) DEPARTMENT_ID (FK) REGIONS COUNTRIES LOCATIONS DEPARTMENTS JOBS EMPLOYEES JOB_HISTORY
  • 18. Database Architecture: Summary of Structural Components Database Service Memory structures: System Global Area (SGA): Database buffer cache, redo buffer, and various pools Program Global Area (PGA) Process structures: User process and Server process Background processes: SMON, PMON, DBW n , CKPT, LGWR, ARC n , and so on Storage structures: Logical: Database, schema, tablespace, segment, extent, and Oracle block Physical: Files for data, parameters, redo, and OS block
  • 19. Summary In this lesson, you should have learned how to: Install, create, and administer Oracle Database 10 g Configure the database for an application Employ basic monitoring procedures Implement a backup and recovery strategy Move data between databases and files
  • 21. Installing the Oracle Database Software Chapter 2
  • 22. Objectives After completing this lesson, you should be able to do the following: Describe your role as a database administrator (DBA), and explain typical tasks and tools Plan an Oracle database installation Use Optimal Flexible Architecture (OFA) Install the Oracle software by using Oracle Universal Installer (OUI)
  • 23. Tasks of an Oracle Database Administrator A prioritized approach for designing, implementing, and maintaining an Oracle database involves the following tasks: 1. Evaluating the database server hardware 2. Installing the Oracle software 3. Planning the database and security strategy 4. Creating, migrating, and opening the database 5. Backing up the database 6. Enrolling system users and planning for their Oracle Network access 7. Implementing the database design 8. Recovering from database failure 9. Monitoring database performance
  • 24. Tools Used to Administer an Oracle Database Oracle Universal Installer Database Configuration Assistant Database Upgrade Assistant Oracle Net Manager Oracle Enterprise Manager SQL*Plus and i SQL*Plus Recovery Manager Oracle Secure Backup Data Pump SQL*Loader Command-line tools
  • 25. Installation: System Requirements Memory requirements: 1 GB for the instance with Database Control Disk space requirements: 1.5 GB of swap space 400 MB of disk space in the /tmp directory Between 1.5 GB and 3.5 GB for the Oracle software 1.2 GB for the preconfigured database (optional) 2.4 GB for the flash recovery area (optional) Operating system: See documentation.
  • 26. Checking the System Requirements Adequate temporary space 64-bit versus 32-bit issues Checks for the correct operating system (OS)  System and kernel parameters ORACLE_HOME
  • 27. Optimal Flexible Architecture (OFA) OFA is designed to: Organize large amounts of software Facilitate routine administrative tasks Manage and administer database growth adequately Help eliminate fragmentation of free space
  • 28. Using Optimal Flexible Architecture Naming mount points: /u01 /disk01 Naming directories: /u01/app/oracle /u01/app/applmgr Naming files: Control files: control n .ctl Redo log files: redo n .log Data files: tn .dbf
  • 29. Setting Environment Variables ORACLE_HOME : The directory containing the Oracle software ORACLE_SID : The initial instance name (by default, ORCL ) NLS_LANG : The language, territory, and client character set settings
  • 33. Creating an Oracle Database Chapter 3
  • 34. Objectives After completing this lesson, you should be able to do the following: Create a database with the Database Configuration Assistant (DBCA) Create a database design template with the DBCA Generate database creation scripts with the DBCA
  • 35. Planning the Database As a DBA, you must plan: The logical storage structure of the database and its physical implementation: How many disk drives do you have for this? How many data files will you need? (Plan for growth.) How many tablespaces will you use? Which type of information will be stored? Are there any special storage requirements due to type or size? The overall database design A backup strategy for the database
  • 36. Databases: Examples Data Warehouse: Research and marketing data State or federal tax payments Professional licensing (doctors, nurses, and so on) Transaction Processing: Store checkout register system Automatic teller machine (ATM) transactions General Purpose: Retail billing system, for example, of a software house or a general database.
  • 38. Using the DBCA to Create a Database
  • 39. Using the DBCA to Create a Database 3 4
  • 40. Using the DBCA to Create a Database 5 6 7
  • 41. Using the DBCA to Create a Database 8 9
  • 42. Using the DBCA to Create a Database A B 10
  • 43. Using the DBCA to Create a Database 11 12
  • 45. Creating a Database Design Template
  • 46. Using the DBCA to Delete a Database 1 2 3
  • 47. Summary In this lesson, you should have learned how to use the DBCA to: Create a database Create a database design template Generate database creation scripts
  • 48. Practice Overview: Using the DBCA This practice covers the following topics : Creating the ORCL database by using the DBCA Unlocking the HR schema Note: Completing the database creation and unlocking the HR schema is critical for all following practice sessions. Optionally: Creating the ORCL database design template by using the DBCA Creating database creation scripts with the DBCA
  • 49. Creating Database by Manual Component: Configure Parameter File or Init File Create Database Service Startup Instance Create Database Setup System Database Create Database Storage Configure oracle network Create Database Objects
  • 50. Create Init File Parameter File or Init File is an text file contains parameters use to configure Database Instance while it is started up. Parameters are consist of: DB_NAME =Specific name of the instance(Database) Control_file s=(Specific location and name of control file) Undo_Management =Define how to management transaction auto or by rollback segment Undo_Tablespace =Name of Tablespace to keep transaction. Processes =Number of Process allow Sessions =number of current connection DB_Block_Size =Size of unit write or read data into file.
  • 52. Create Database Service Oracle Database Service: is an identifier of database on network environment. It’s a service provider to clients whom whish to connect to oracle server to get service. Syntax: On DOS Prompt OraDim –NEW –SID nameofservice [-SYSPWD internal password –START MODE Auto|Manual - PFILE ‘Path\Parameter file name’]
  • 53. Syntax Delete: Oradim –Delete –SID nameofservice
  • 54. Connect to Oracle Service and Create Instance: To Create Database Instance (In-Memory Database) - Specific Oracle service (SID) SET ORACLE_SID=Oracle Service Name - Go into Oracle Utility call SQL PLUS with nolog option SQLPLUS/NOLOG Connect to specific service(SID) by database administrator CONNECT / AS SYSDBA - Startup Database Instance with nomount option STARTUP NOMOUNT [PFILE=Path\Parameter File Name]
  • 56. Create Database File and Open Database Instance
  • 59. Setup System For oracle 10g and above must be configure SysAux Datafile @%Oracle_home%\rdbms\admin\catalog Install database catalog and dynamic view @%Oracle_home%\rdbms\admin\catproc Install PL/SQL Compiler and oracle pre-define functions and packages.
  • 60. Create Tablespace (Storage) An tablespace is a pointer of data files on database instance. There are following type of tablespace. - System: Store system database objects - System Auxiliary: store system object support to system tablespace (this tablespace unavailable for oracle 9i or below. - Temporary tablespace: use to store query data such join, sort. - Undo Tablespace: This tablespace use transaction. - User Tablespace: Store user input data(tables) - Index Tablespace: Store index.
  • 61. Create Tablespace: Create [undo] Tablespace Name-Of-Tablespace Datafile ‘path\filename’ size initialSize [Temporary] [Auto extend on [Next Size IncrementalSize] MaxSize MaximumDatafile;
  • 62. Create net service Net Service is representative of Oracle Service in client computer, it’s used to connect to oracle server by application. Without netservice Application could not connect to Oracle. To create netservice - Open “Net Manager” - Select “Service Naming” - Click “Edit\Create” - Complete parameters as following -Net Service Name: use for connecting -Host Name: Computer Server Name(PC NAME) -Protocol (Keep Default TCP) and Port Number (Keep default 1521) -Oracle Service: Oracle Service Name
  • 63. Connect to database On Dos: SQLPLUS Username/password@netservicename On SQLPLUS Connect Username/password@netservicename Net Service Name
  • 64. Startup and Shutdown Server Startup Oracle Server: is a process to create oracle instance. Startup: - Start oracle service - Connect to oracle service by dba (database administrator) - Set Oracle_SID= OracleServiceName - SQL/NOLOG - Connect / as SysDBA - Startup Database Startup [Option] Pfile= ‘Path\ParameterFile’ Option: Nomount: Start for creating database Mount: Start for reconfiguring database Open: Start for working and providing service.
  • 65. Shutdown Oracle Server Shutdown Oracle Server is process to close oracle server Connect to oracle server as sysdba Shutdown Shutdown [Option] Option Normal : Normally shutdown by let user disconnect oracle server by themselves. Transactional: Wait until user save transaction then server disconnect user and shutdown instance when disconnect all user. Immediate: Rollback all transaction and shutdown instance. Abort: Shutdown instance without manage every thing. Check “ Startup instance when instance is started”
  • 66. Configure Oracle Server to Startup Auto To let oracle server to startup automatically when Window is Started: - Configure Oracle Service to start automatic - Connect Parameter File: Name:InitDBNAME.ORA FOLDER: Oracle_HOME\Database (D:\oracle\product\10.1.0\db_2\database) - Open program “Administration Assistant for Window” - Select “Database\DatabaseName” Right Click-> Startup/Shutdown Option
  • 68. Configure Transactional - Shutdown Server. Open Parameter File -Add Command Undo_Management=Auto Undo_Tablespace=TablespaceName
  • 69. Creating Oracle Database Objects Chapter 4
  • 70. Oracle Objects Objectives: Using Data Definition Language to create: Table Index Sequence View Synonym To Create object: - Start Oracle Database Server - Connect to Oracle by User “System” - Write SQL Script: - Run Script:
  • 71. Creating a Table Oracle Data Type String Char Size Varchar 4000 Varchar2 4000 NChar 2000 NVarchar2 2000 Long 2GB Number Number(N,P) Integer Float Binary BLOB 4GB DateTime Date
  • 72. TABLE statement is as follows: CREATE Table Schema. table_name ( column_name type [CONSTRAINT constraint_def DEFAULT default_exp ] [, column_name type [CONSTRAINT constraint_def DEFAULT default_exp ]...] ) [TABLESPACE tab_space Storage];
  • 73. Schema: Name of user to store object: Tablespace: Name of Tablespace where table is located. Storage option define extends and segment to store table’s data
  • 74. Constraints Are condition of column: Primary Key: Foreign Key: Unique: Do not duplicate value Check: Set Condition for column Not Null:
  • 75. Index An index is object store address of records. It’s use to retrieve record when it’s selected. Syntax: Create Index Name-Of-Index On Table_Name(ColumnName,..) Tablespace Name-of-Tablespace. Guideline: Index set on unique column or less duplicate Index set on columns use in where condition
  • 76. View View: is virtual table to view data from tables. Syntax: Create View Name-of-View[(Col1,Col2,…)] AS Select SQL Statement.
  • 77. Sequence: Is object use to generate autonumber. Syntax: Create Sequence Name-Of-Sequence [Increment By Step] [Start With StartNumber] Attribute of Sequence .NextVal: .CurrVal:
  • 78. Synonym Is Object reference to another object: Syntax: Create [public] Synonym Name-Of-Synonym for [Schema.]ObjectName
  • 79. System View use to check: DBA_Tablespaces: Store tablespace information of Server. User_Tablespaces: Similar DBA_Tablespaces store for current schema. User_Tables,DBA_Tables: DBA_Indexes,User_Indexes DBA_Views,User_Views DBA_Sequences,User_Sequences *** General form: USER_ObjectTypes Check Structure tables or views DESC Table-Name
  • 81. Structured Query Language (SQL) Chapter 5
  • 82. Agenda Keyword IN and BETWEEN Dual ????? FUNCTIONS Aggregate Numeric String Date Group By Having
  • 83. Keywords IN & BETWEEN IN SELECT columns FROM tables WHERE column1 in (value1, value2, .... value_n); e.g. Select name from employee where desig IN(‘Manager’, ‘Clerk’, ‘Worker’); BETWEEN SELECT columns FROM tables WHERE column1 between value1 and value2; e.g. Select name from Employee where salary between 4500 AND 7000;
  • 84. What is DUAL??? The DUAL table is a real table. It’s owned by the user SYS and has one row. The table has only one column, which is named DUMMY and has a string with a length of 1. The value of DUMMY in the one and only row is X. Note: Anyone can create a table like this, with one row, and accomplish the same thing. But it’s good practice to have one place where you always have one row and you always know the table name.
  • 85. Aggregate Functions AVG MAX MIN COUNT SUM CORR VARIANCE STDDEV…
  • 86. Aggregate Functions… Select count(*) from Employee; Select Count(Distinct(city)) from Employee; SELECT SUM(salary) as &quot;Total Salary“ FROM employees where salary > 25000; SELECT SUM(sales * 0.10) as &quot;Commission“ FROM order_details; SELECT MIN(salary) as &quot;Lowest salary“ FROM employees; SELECT MAX(salary) as &quot;Highest salary“ FROM employees; SELECT Avg(salary) as &quot;Avg Salary“ FROM employees WHERE salary > 25000; SELECT Avg(sales * 0.10) as &quot;Average Commission“ FROM orders; select stddev(salary) from employee;
  • 87. Numeric Function ABS ACOS BITAND CEIL COS COSH EXP FLOOR LN MOD NANVL POWER ROUND SIGN SIN SQRT TAN LEAST GREATEST
  • 88. Numeric Function… Select abs(23.65) from dual; Select abs( 12.34 * -2) from dual; Select bitand(6,2) from dual; Select acos(0.35) from dual; Select ceil(32.65) from dual; would return 33. Select ceil(-32.65) from dual; would return -32 Select floor(32.65) from dual; would return 32. Select floor(-32.65) from dual; would return -33 Select exp(3) from dual; Select ln(20) from dual;
  • 89. Numeric Function… Select greatest(2, 5, 12, 3) from dual; would return 12 Select greatest('2', '5', '12', '3') from dual; would return '5' Select greatest('apples', 'oranges', 'bananas') from dual; Select least(2, 5, 12, 3) from dual; would return 2 Select least ('2', '5', '12', '3') from dual; would return ‘12‘ Select least ('apples', 'oranges', 'bananas') from dual; Select mod(15, 4) from dual; Select power(3, 2) from dual; Select sqrt(5.617) from dual; Select sign(-0.675) from dual; would give -1 Select sign(0) from dual; would give 0 Select sign(7.0001) from dual; would give 1
  • 90. String Function TRIM LTRIM RTRIM ASCII CHR LPAD RPAD CONCAT INSTR INITCAP LENGTH LOWER UPPER REPLACE SUBSTR
  • 91. String Function… TRIM( [ leading | trailing | both [ trim_character* ] ] string1 ) select TRIM('A' from 'AABABAB4AAA') from dual; select TRIM(LEADING 'A' from 'AABABAB4AAA') from dual; select TRIM(TRAILING 'A' from 'AABABAB4AAA') from dual; select TRIM(BOTH 'A' from 'AABABAB4AAA') from dual; CONCAT(string1, string2) select concat('a','b') from dual; Select ‘a’ || ‘b’ from dual;
  • 92. String Function… LPAD(string, length, [set]) lpad('tech', 7); would return ' tech' lpad('tech', 2); would return 'te' lpad('tech', 8, '0'); would return '0000tech' lpad(‘this is my text', 15, 'z'); would return ' this is my text' lpad(' this is my text', 16, ‘#'); would return ‘#this is my text ' RPAD(string, length, [set]) rpad('tech', 7); would return 'tech ' rpad('tech', 2); would return 'te' rpad('tech', 8, '0'); would return 'tech0000' rpad(' this is my text', 15, 'z'); would return ' this is my text' rpad(' this is my text', 16, ‘$'); would return ' this is my text$'
  • 93. String Function… LTRIM(string, [set]) ltrim(' tech'); would return 'tech' ltrim(' tech', ' '); would return 'tech' ltrim('000123', '0'); would return '123' ltrim('123123Tech', '123'); would return 'Tech' ltrim('123123Tech123', '123'); would return 'Tech1 ltrim('xyxzyyyTech', 'xyz'); would return 'Tech' RTRIM(string, [set]) rtrim('Tech123123', '123'); would return 'Tech' rtrim('123Tech123', '123'); would return '123Tech'
  • 94. String Function… LOWER(string) lower('GEORGE BURNS 123 '); would return 'george burns 123 ' UPPER(string) upper('george burns 123 '); would return 'GEORGE BURNS 123 ' INITCAP(string) initcap('GEORGE BURNS'); would return 'George Burns' LENGTH(string) length(''); would return NULL. length(‘hello'); would return 5 length(‘ hello '); would return 7 SUBSTR(string, [count]) substr('This is a test', 6) would return 'is a test' substr('TechOnTheNet', 1, 4) would return 'Tech‘ substr('TechOnTheNet', -6, 3) would return 'The'
  • 95. String Function… REPLACE( string1, string_to_replace, [ replacement_string ] ) replace('123123tech', '123'); would return 'tech' replace('123tech123', '123'); would return 'tech‘ -replace('222tech, '2', '3'); would return '333tech' replace('0000123', '0'); would return '123‘ CHR( number_code ) chr(116); would return 't' chr(84); would return 'T‘ ASCII( single_character ) ascii('t') would return 116 ascii('T') would return 84 ascii('T2') would also return 84
  • 96. String Function… INSTR( string1, string2, [ start_position ], [ nth_appearance ] ) instr('this is my text', ‘s') ;would return 4 instr(‘this is my text', ‘s', 5, 1) would return 7 instr('this is my text', ‘s', 1, 2) would return 7 instr('this is my text', ‘s', -7, 2) would return 4
  • 97. Date Functions SYSDATE SYSTIMESTAMP ADD_MONTHS CURRENT_DATE CURRENT_TIMESTAMP EXTRACT MONTHS_BETWEEN LAST_DAY NEXT_DAY
  • 98. Date Functions… Sysdate Select emp_name, sysdate from employee; SYSTIMESTAMP SELECT SYSTIMESTAMP FROM dual; add_months( date1, n ) add_months('01-Aug-03', 3) would return '01-Nov-03' add_months('01-Aug-03', -3) would return '01-May-03‘ Current_Timestamp select systimestamp from dual; ALTER SESSION SET TIME_ZONE = '+5:30'; select current_timestamp from dual; select systimestamp from dual;
  • 99. Date Functions… NEXT_DAY( date, weekday ) Where weekday: Monday, Tuesday… e.g. Select next_day(sysdate, ‘MONDAY’) from dual; LAST_DAY(date) select last_day(sysdate) LAST_DATE from dual; MONTHS_BETWEEN(date1, date2 ) select months_between(sysdate, to_date('1/1/2005', 'dd/mm/yyyy')) from dual;
  • 100. GROUP BY The GROUP BY clause, along with the aggregate functions, groups a result set into multiple groups, and then produces a single row of summary information for each group. If we have a mix of aggregate and nonaggregate expressions in the SELECT list, SQL expects that we are trying to perform a GROUP BY operation, and we must also specify all nonaggregate expressions in the GROUP BY clause. When we GROUP BY a column that contains NULL values for some rows, all the rows with NULL values are placed into a single group and presented as one summary row in the output. While using GROUP BY Clause, we can filter records from the table based on a WHERE clause.
  • 101. GROUP BY… e.g. select max(salary), min(salary), desig, avg(salary) from employee group by desig; Group By with NULL values; select count(*), department from employee group by department; With where Clause select max(salary), min(salary), desig, avg(salary), count(*) from employee where salary > 5000 group by desig;
  • 102. GROUP BY HAVING The HAVING clause is used to put a filter on the groups created by the GROUP BY clause. If a query has a HAVING clause along with a GROUP BY clause, the result set will include only the groups that satisfy the condition specified in the HAVING clause. e.g. select desig, max(salary), avg(salary) from employee group by desig having avg(salary) > 5000;
  • 103. ORDER BY The SQL ORDER BY clause comes in handy when you want to sort your SQL result sets by some column(s). SYNTAX: Select <field_name(s)> from <table_name(s)> ORDER BY <EXPR>, <FIELD(s) NAME> [ASC | DESC ] Specifies a column(s) on which to sort. The ORDER BY clause can include items not appearing in the select list, but in case of using keywords like DISTINCT then the sort columns must appear in the select list
  • 104. Select Revisited Complete Syntax: SELECT select_list FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ]
  • 105. JOIN By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. A join condition defines the way two tables are related in a query by: Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table. Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.
  • 106. JOIN… Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause. Syntax: FROM first_table join_type second_table [ON ( join_condition )]
  • 107. JOIN… Joins can be categorized as: Inner joins (the typical join operation, which uses some comparison operator like = or <>). Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. Outer joins can be a left, a right, or full outer join.
  • 108. OUTER JOIN Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
  • 109. JOIN By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. A join condition defines the way two tables are related in a query by: Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table. Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.
  • 110. JOIN… Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause. Syntax: FROM first_table join_type second_table [ON ( join_condition )]
  • 111. JOIN… Joins can be categorized as: Inner joins (the typical join operation, which uses some comparison operator like = or <>). Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. Outer joins can be a left, a right, or full outer join.
  • 112. OUTER JOIN Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
  • 113. Scalar Subqueries The Scalar Subquery can be used anywhere a value can be used. When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery. When the subquery returns no rows, a database null is used as the result of the subquery. Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
  • 114. Predicate Subqueries Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct. IN Subquery The IN Subquery tests whether a scalar value matches the single query column value in any subquery result row. General Syntax: value-1 [NOT] IN (query-1)
  • 115. Predicate Subqueries… value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1) The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row. The ANY, ALL, SOME specifiers give the type of match expected. ANY and SOME must match at least one row in the subquery. ALL must match all rows in the subquery
  • 116. EXIST Subquery The EXISTS Subquery tests whether a subquery retrieves at least one row, that is, whether a qualifying row exists. General Syntax: EXISTS(query-1)
  • 117. Table Subqueries Table Subqueries are queries used in the FROM clause, replacing a table name. Its the result set of the Table Subquery acts like a base table in the from list. Table Subqueries can have a correlation name in the from list.
  • 118. Scalar Subqueries The Scalar Subquery can be used anywhere a value can be used. When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery. When the subquery returns no rows, a database null is used as the result of the subquery. Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
  • 119. Predicate Subqueries Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct. IN Subquery The IN Subquery tests whether a scalar value matches the single query column value in any subquery result row. General Syntax: value-1 [NOT] IN (query-1)
  • 120. Predicate Subqueries… value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1) The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row. The ANY, ALL, SOME specifiers give the type of match expected. ANY and SOME must match at least one row in the subquery. ALL must match all rows in the subquery
  • 121. Predicate Subqueries… EXIST Subquery The EXISTS Subquery tests whether a subquery retrieves at least one row, that is, whether a qualifying row exists. General Syntax: EXISTS(query-1)
  • 122. Table Subqueries Table Subqueries are queries used in the FROM clause, replacing a table name. Its the result set of the Table Subquery acts like a base table in the from list. Table Subqueries can have a correlation name in the from list.
  • 123. NULLS &quot;As we know, There are known knowns. There are things we know we know. We also know There are known unknowns. That is to say We know there are some things We do not know.”- Donald Rumsfeld What is NULL ????? NULL as &quot;a special value , or mark , that is used to indicate the absence of any data value.&quot; NULL in SQL is not a &quot;data value&quot;, but rather an indicator that we have missing data
  • 124. NULLS… Nulls in Conditions: Condition Value of A Evaluation a IS NULL 10 FALSE a IS NOT NULL 10 TRUE a IS NULL NULL TRUE a IS NOT NULL NULL FALSE a = NULL 10 UNKNOWN a != NULL 10 UNKNOWN a = NULL NULL UNKNOWN a != NULL NULL UNKNOWN a = 10 NULL UNKNOWN a != 10 NULL UNKNOWN
  • 125. NULLS… Nulls in SQL Functions All scalar functions (except REPLACE , NVL , and CONCAT ) return null when given a null argument. NVL( string1, replace_with ) e.g. select emp_name, nvl(department, 'N/A') from employee;
  • 126. Alter Table ALTER TABLE table_name ADD ( column_1 column-definition, column_2 column-definition, ... column_n column_definition ); ALTER TABLE table_name MODIFY ( column_1 column_type, column_2 column_type, ... column_n column_type );
  • 127. Alter Table… ALTER TABLE table_name DROP COLUMN column_name; ALTER TABLE table_name SET UNUSED column_name; ALTER TABLE table_name RENAME COLUMN old_name to new_name;
  • 128. Alter Table… The Rules for Adding or Modifying a Column You may add a column at any time if NOT NULL isn’t specified. You may add a NOT NULL column in three steps: Add the column without NOT NULL specified. Fill every row in that column with data. Modify the column to be NOT NULL .
  • 129. Alter Table… These are the rules for modifying a column: You can increase a character column’s width at any time. You can increase the number of digits in a NUMBER column at any time. You can increase or decrease the number of decimal places in a NUMBER column at any time. In addition, if a column is NULL for every row of the table, you can make any of these changes: You can change the column’s datatype. You can decrease a character column’s width. You can decrease the number of digits in a NUMBER column.
  • 130. Alter Table… e.g. - Alter table mytable Add constraint pk_mytable PRIMARY KEY (a); - alter table mytable add b varchar2(50); Alter table emp_hourly MODIFY (HOURRATE NUMBER(5,2) DEFAULT 7.25); Alter table mytable RENAME CLOUMN a TO z; - Alter table mytable RENAME to mynewTable;
  • 131. RENAME e.g. Rename mynewtable to mytable; RENAME old_table_name TO new_table_name;
  • 132. DROP Table e.g. DROP table mytable; DROP TABLE table_name;
  • 134. PL/SQL Lesson Objectives Introduction to PL/SQL SQL Review Basic PL/SQL Trigger Store Procedure and Function Package
  • 135. Introduction What is PL/SQL: PL is stand for Procedural Language. PL/SQL= {Procedural or Structure Programming Language} + SQL PL/SQL is a procedural programming language which improving from SQL Language by added structured programming feature in order to process business logic of information system.
  • 136. Feature of PL/SQL PL/SQL use to develop business logic layer of application which run on server-side. Feature of Server-Side Code are: - Good performance - Reduce network traffics - High security - High reusable
  • 137. SQL There are 3 types of SQL Command: DDL: Data Definition Language . There are follow command of DDL - Create : for creating objects - Alter: for modifying objects - Drop: for removing objects DML (Data Manipulated Language): Use to manipulate data. DML Consist of - Select - Insert - Delete - Update DCL(Data Control Lanaguage) begin tran, commit,rollback,save tran
  • 138. DML (Continue) Select Statement: for reading data from databases, the select statements return rows from tables: Syntax: Select *|Col1,Col2,….. From Table | Joined Tables [Where Condition] [Group By Col1,Col2,…] [Having Condition] [Order by Col1,Col2,…]
  • 139. Transaction SQL Insert: for inserting records into tables: Syntax1: Insert Into Table_Name[(Col1,Col2,…)] Values(val1,val2,…) Syntax2 Insert Into Table_Name[(Col1,Col2,…)] Select co1l,col2,…from TableName…. Delete: for removing records (data) into tables: Delete from Table_Name [Where Condition] Update: for modifying records (data) in tables: Update Table_Name set Col1=Expr,Col2=Expr,… [Where Condition]
  • 140. Basic PL/SQL Declare Variable: PL/SQL is a structure programming language. Before use a variable must be declare above the body of program. Syntax: Declare varname1 Datatype[:=initialvalue]; VarName Datatype[:=initialvalue]; Example Declare x integer; Str varchar2(20):=‘BBU’;
  • 141. PL/SQL Data Type PL/SQL Data Type is similar to Oracle Database Data Type, However the size of some data type is difference Example varchar2 in database is 4K in pl/sql is 32k %TYPE is use to declare a variable to match with the other. Example Declare s varchar2(20); s1 s%type; pcode tblProducts.ProductCode%Type; %RowType is use to declare a variable to match a record type of a table or cursor. Example Declare prow tblProducts%RowType
  • 142. Assignment and Operator Assignment is most important operator. In oracle we can assign to a variable an expression or value which on memory or we can select a value from a column or row of table then assign direct to variable. Syntax1: VarName:=Expression; Syntax2 Select Col1,Col2,…. INTO var1,var2 from tablename,. [Where Condition] Syntax 1 is assign a value or expression value to varname Syntax 2: is select a single row of data of col1,col2 from table then assign to var1,var2
  • 143. Assignment (Cont) Example: Declare Code Varchar2(10); price float; Qty Integer; … … .. -- Assign ‘P001’ to Code Code:=‘P001’; -- Select Quatity and UnitPrice from tblProducts then assign to price and Qty. Select Quantity,UnitPrice Into Qty, Price from tblProducts Where ProductCode=‘P001’;
  • 145. Control Structure IF Statement Syntax: If Condition then Statements; [elsif condition then statements; Elsif condition then statements; … ..] [Else statements; ] End if;
  • 146. Loop Statement Syntax Loop Statement1; Statement2; Exit When Condition; … . End Loop; Loop execute by repeating statement1,statement2,.... To exit loop use following: Exit When Condition or if Condition Then Exit
  • 147. While Loop Syntax While Condition Loop Statement1; Statement2; ……………… . End loop;
  • 148. For Statement In oracle for statement can be used to loop and scan value in collection of value or collection of records the counter variable will automatic define it data type to match collection. Syntax For counter IN Collection Loop Statements; Statements; Statements; End Loop;
  • 149. For Statement Example: for I in 1..100 loop Statements; end loop; -- statement I run from 1 to 100 For pRow IN (Select * from tblProducts) Loop Statements; END LOOP; In above statement pRow is a record variable which will be stored each record.
  • 150. Case Statement In oracle case statement, use to return value like a value. Syntax1: Case When Condition Then Value1 When Condion Then Value2 … .. [else valN] END Syntax 2 Case Expression When val1 Then Value1 When val2 Then Value2 [else valN] END;
  • 151. CURSOR Cursor is a data type which its variable use to store address of records returned from select statement. Declare Cursor Cursor_Name[(Parameter,…)] is select statement; To use cursor first open cursor then read data from cursor parse to variable Syntax Open Open Cursor_name[(arg,…)] Syntax Read Fetch Cursor_Name into var_name; Var_name must be declare as Cursor_name%rowtype. The fetch statement always move next rows while eof the Attribute cursor_name%notfound=true Close Cursor Close Cursor_Name
  • 152. Trigger Trigger is a special procedure or sub program is bound to a table’s transaction and will be execute when the bound table receive transaction. There two type of Trigger: Row Trigger and Statement Trigger Row trigger is trigger which will execute every row effect by transaction. Statement trigger is execute a time for every statement. It’s does not depend on how many rows created by transaction
  • 153. Trigger Syntax: Create [or replace] trigger trigger_name After|Before Transaction On Table_name [For Each row ] [When condition] --Declare parts Begin --PL/SQL Codes; End; Transaction : [INSERT [Or Delete Or [Update [of ColumnName,…]]]
  • 154. Trigger :New and :Old :New is a trigger parameter store the inserted records and new records of update statement. :Old is a trigger parameter store the deleted records and previous records of update statement. INSERTING,DELETING,UPDATING is a Boolean parameter use to recognize transaction type.
  • 155. Procedure and Function Create [Or Replace] Procedure Name-Of-Procedure(Par,…..) IS --Variable declaration Begin --PL/SQL Statement; End; Create Or Replace Function Name-Of-Function (Par,…..) Return DataType IS --Variable declaration Begin --PL/SQL Statement; Return Value,-- return the value to function End;
  • 156. Procedure and Function Parameters are variable use for receiving value from argument and parsed value to arguments. Syntax: Par-Name [IN|OUT|IN OUT] DataType IN parameters use to receive value only from clients; OUT Parameter use to parse value from server to client’s arguments. IN OUT parameter for both receive and parsed. Parameter cannot specific size
  • 158. Learning Topics: Create Users Privileges and Granting Privileges Role Auditing Users
  • 159. Create Users A user is a key to access database. An user must be provided some privileges (right) for access database objects and perform tasks. Syntax Create User Create User UserNam e Identified by password [Password expire] [Default Tablespace name-of-tablespace ] [Temporary tablespace name-of-temporary-tablespace ] [Quota {Size|Unlimited} on Tablespace-Name ] ---------;
  • 160. Create Users(Continue) - User-Name must be string and no duplicate Password is user password Password Expire an option for user change password at first time log on Default tablespace is tablespace to store object will be created by users. Temporary tablespace is name of temporary tablespace will store data query of users. Quota is the permission to use tablespace
  • 161. Create User (Example) Ex1 Create User BBUMSC Identified by bbu Password Expire Default tablespace users Temporary tablespace temp Quota 100M on Users; Ex2: Create User BBUCEO Identified by bbumanager Temporary tablespace temp;
  • 162. Privileges Privilege is right to access oracle system: There are two type of Privileges System Privilege And Object Privileges System Privileges: Right to access system resources. System Privileges consist of: Create Session Select ANY TABLE INSERT ANY TABLE UPDATE ANY TABLE DELETE ANY TABLE CREATE TABLE,CREATE VIEW,CREATE TABLESPACE,….
  • 163. Privileges (Continue) Granting System Privileges: Grant Privileges,… to USERNAME [With Grant Option] Example Grant Create Session,Select Any Table,Create Tablespace,Create Table to BBUMSC;
  • 164. Privileges (Continue) Are right to access data in table, view and execute store procedure, function and package: Object Privileges consist of: Select Insert Delete Update Execute Syntax: Granting Object Privileges: Grant All|Select,Insert On ObjectName to UserName [With Grant Option]; Example: Grant All on Students to BBUMSC;
  • 165. Roles Role is a set of privileges use to grant to users. Syntax Create Role: Create Role RoleName; To grant privileges to role is the same user. Example: Create Role StudentRole; Grant create session,Select any table to StudentRole; Grant StudentRole to BBUMSC;
  • 166. Auditing User Use to control action of users who access to oracle system. Syntax: Audit option,.. [by user] [by access|by session] [whenever [not] successful]; Audit Option - Select Table - Delete Table - Update Table - Insert Table - Session - ……..
  • 167. Auditing User (Continue) To set audit user: - Set Parameter file AUDIT_TRAIL=True - User Audit Command - Check Audit on view
  • 169. Oracle Backup & Recovery Chapter 8
  • 170. Oracle Backup & Recovery 4-1 Backup/Recovery Basic 4-2 Oracle Backup/Recovery Configuration 4-3 Physical Backups 4-4 Types of Failure and Troubleshooting 4-5 Oracle Recovery without Archiving 4-6 Complete Recovery with Archiving 4-7 Incomplete Recovery with Archiving 4-8 Recovery when loss of Control Files / Online Redo Logfiles
  • 171. Oracle backup/recovery basic Backup methods Backup strategy
  • 172. Backup methods Logical backup export/import Database, user, table, table partition full increasement Physical backup cold/offline backup full increasement hot/online backup full Increasement archive log backup
  • 173. Backup strategy Determinded by Business Technical Management Mean-time to recover
  • 174. Determine backup strategy Ask customer: What’s your backup strategy now? How many data can you loss? How long can your database be shutdonw? How long can you allow to backup? How long can you allow to recover? How many archived logs per day? How many free disk space do you have to store the archived logs? Do you consider about standby database?
  • 175. Objectives Identify recovery implications of operating in “Noarchive” mode Describe the differences between “Archivelog” mode and “Noarchivelog” mode Configure a database for “Archivelog” mode and automatic archiving Use init.ora parameters to duplex archive log files
  • 176. Overview Noarchivelog or Archivelog Mode Decision to use one or the other is dependent upon how much data can be lost due to a failure.
  • 177. Online redo log files 053 No redo history NOARCHIVELOG Mode 054 054 053 053 LGWR
  • 178. Archivelog Mode Online redo log files LGWR Archived log files 054 054 053 053 053 052 051 Redo history
  • 179. Configuring for Archiving ARCH LOG_ARCHIVE_DEST=/archive/arch LOG_ARCHIVE_FORMAT=%s.arc /archive/arch052.arc Archived log file Online redo log files 053 053 052 Group 1 Group 2 052 052
  • 180. Duplexing Archived Log Files ARCH Online redo log files 053 053 052 052 LOG_ARCHIVE_DUPLEX_DEST 052 052 Group 1 Group 2 LOG_ARCHIVE_DEST Archived log files
  • 181. Changing Database Archive Modes Startup and mount the database Alter the mode of the database Shutdown in normal or immediate Take a full closed database backup Startup and open the database
  • 182. Enabling Archive Processing Automatic archiving Manual archiving ARCH 053 053 053 053 DBA
  • 183. Manual Archive ALTER SYSTEM ARCHIVE LOG all; 1 2 ARCH 052 051 052 3 051 Online redo logs
  • 184. Automatic Archiving ARCH 052 051 Archived log files 053 051 052 Archived Archived Current LOG_ARCHIVE_START=TRUE Online redo logs
  • 185. Obtaining Archive Log Information V$ARCHIVE_DEST V$ARCHIVED_LOG V$LOG_HISTORY Data dictionary views Command line ARCHIVE LOG LIST; V$DATABASE
  • 186. Summary Complete database recovery requires: Archivelog mode Automatic archiving A database backup immediately after it is put into archivelog mode
  • 187. Exercise 4-2 1. See database is running on archive or noarchive log mode: svrmgr>select * from v$database; 2. Set database to archive log mode: Edit init_sid.ora files archive_log_dest archive_log_format (see Oracle References about values) log_archive_start svrmgr> shutdown immediate; svrmgr> startup mount; svrmgr> alter database archivelog; svrmgr> alter database open;
  • 188. Exercise 4-2 3. Check archive log configuration: Check the archive process: $ps –ef|grep arch Check archive log parameters: svrmgr> show parameter arch
  • 189. Objectives Perform database backups using operating system commands Describe the recovery implications of closed and open database backups Perform closed(offline) and open(online) database backups Identify the different types of control file backups List the data dictionary views useful for backup operations
  • 190. Backup methods Logical backup export/import Database, user, table, table partition full increasement Physical backup cold/offline backup full increasement hot/online backup full Increasement archive log backup
  • 191. Backup Methods Physical backup Closed database Open database Archive Mode No archive Mode
  • 192. Closed Database Backup Datafiles Control Files Password File Online or Offline Storage Parameter Files Redo Log Files
  • 193. Advantages of Closed Database Backups Conceptually simple Easy to perform Requires little operator interaction Reliable
  • 194. Database File Information Data dictionary views V$DATAFILE V$CONTROLFILE V$LOGFILE DBA_DATA_FILES
  • 195. Performing a Closed Database Backup 2 3 4 SHUTDOWN IMMEDIATE; HOST cp <files> /backup/ STARTUP OPEN; Data Files Control Files Parameter Files 1
  • 196. Open Database Backup Datafiles Control Files Parameter Files Archived Redo Log Files Password File Online Redo Log Files
  • 197. Advantages of Open Database Backups Maintains high database availability Can be done at a tablespace or datafile level Allows recovery to point-in-time
  • 198. Archived Log Files ARCH Archivelog Mode Online Redo Log Files LGWR 054 054 053 053 052 051 Open Database Backup Requirements 053
  • 199. Open Database Backup Options All tablespace datafiles Tablespace USER_DATA user02.dbf user01.dbf Individual datafile user02.dbf Tablespace USER_DATA user01.dbf
  • 200. Performing an Open Database Backup 1 ALTER TABLESPACE user_data BEGIN BACKUP; 2 HOST cp <files> /backup/ 3 ALTER TABLESPACE user_data END BACKUP;
  • 201. Backup Status Information Data dictionary views: V$BACKUP V$DATAFILE_HEADER
  • 202. Backing Up a Control File Creating a binary image: alter database backup controlfile to ‘control1.bkp’; Creating a text trace file: alter database backup controlfile to trace;
  • 203. Exercise 4-3 1. Cold backup: Shutdown database Copy datafile, control file, logfile, init file, password file to other place 2. Hot backup: svrmgr>ALTER TABLESPACE system BEGIN BACKUP; svrmgr>host cp /abc/system01.dbf /backup svrmgr>ALTER TABLESPACE system END BACKUP;
  • 204. Categories of Failures Statement failure User process failure User error Instance failure Media failure
  • 205. Causes of Statement Failures Logic error in an application Attempt to enter bad data into the table Attempt an operation with insufficient privileges Attempt to create a table but exceed allotted quota limits Attempt an INSERT or UPDATE to a table, causing an extent to be allocated, but with insufficient free space left in the tablespace
  • 206. Resolutions for Statement Failures Correct logic flow of the program Modify and reissue the SQL statement Provide the necessary database privileges Change the user’s quota limit by using the ALTER USER command Add file space to the tablespace
  • 207. Causes of User Process Failures The user performed an abnormal disconnect in the session The user’s session was abnormally terminated The user’s program raised an address exception terminating the session
  • 208. Resolving User Process Failures The PMON process detects an abnormally terminated server process PMON rolls back the transaction and releases any resources and locks being held by it
  • 209. Possible User Error Failures SQL> DROP TABLE Employee; SQL> TRUNCATE TABLE Employee; SQL> UPDATE Employee SET SALARY = SALARY * 1.5; SQL> COMMIT; SQL> DELETE FROM Employee;
  • 210. Resolving User Errors Train the database users Recover from a valid backup Bring back a table export Perform a point-in-time recovery
  • 211. Causes of Instance Failure Power outage Hardware failures CPU Memory Disk failure Background process failure
  • 212. Recovery from Instance Failure No special recovery action required Start the instance Open the database Notify users
  • 213. Instance Recovery Process Unsynchronized files Roll-forward process Committed and uncommitted data in files Rollback process Committed data in data files Synchronized files
  • 214. Causes of Media Failure Head crash on disk drive Physical problem reading or writing to database files File was accidentally erased
  • 215. Resolving Media Failures The recovery strategy depends upon which backup method was chosen and which files are affected If available, apply archived redo log files to recover data committed since the last backup
  • 216. Database Synchronization All data files (except offline and read-only) must be synchronized for the database to open Synchronization is based on the current checkpoint number Applying redo logs synchronizes files Redo logs are automatically requested by Oracle
  • 217. The Alert Log File Records informational and error messages for Oracle Reflects the ongoing status of the system Continuously written to, with new messages being appended to the end of the alert file Shows date and time of startup, shutdown, recovery operations, and so on
  • 218. Oracle Trace Files Created by Oracle background processes Written to destination specified by parameter BACKGROUND_DUMP_DEST Source of additional diagnostic information
  • 219. Summary Understand the types of failures and the degree of DBA intervention Locate error messages in the alert log and trace files
  • 220. Exercise 4-4 View alert log to calculate archive log size per day
  • 221. Objectives Note the implications of media failure with a database in noarchivelog mode Recover a database in noarchivelog mode after media failure Restore files to a different location if media failure occurs
  • 222. Overview Database Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 146 145 146 146 146 146 Instance SGA Redo Log Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA User Process Server Process PGA Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 144 145 144 144 144 144
  • 223. Media Failure and Recovery Without Archiving Failure Loss of disk, datafile, or corruption Recovery Restore all datafiles, control files, and redo logs Restoring password and parameter files is optional
  • 224. Recovery Without Archiving Advantages Easy to perform, with low risk of error Recovery time = Time to restore all files Disadvantages Data is lost and must be reapplied manually The entire database is restored to the point of the last whole closed backup
  • 225. Recovery Without Archiving Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database 145 146 146 146 146 146 Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Backup 143 144 144 144 144 144 Restore most recent backup Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database 143 144 144 144 144 144
  • 226. Restoring to a Different Location Rename the file or directory location: SVRMGR> connect system/manager as sysdba; Connected. SVRMGR> startup mount pfile=initDB00.ora; Oracle instance started. SVRMGR> alter database rename file 2> ‘/disk1/data/user_01.dbf’ 3> to ‘disk2/data/user_01.dbf’; Statement Processed. SVRMGR> alter database open;
  • 227. Overview Database Database Password File Archived Log Files Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 146 145 146 146 146 146 User Process Server Process PGA Data File 2 146 Instance SGA Redo Log Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH Data Buffer Cache
  • 228. Media Failure and Recovery with Archiving Failure Loss of disk, datafile, or corruption Recovery Datafiles for restore must be offline Restore only lost or damaged datafiles Do not restore the control file, redo logs, password, or parameter files Recover the datafiles
  • 229. Recovery with Archiving (Complete Recovery) Advantages Only need to restore lost files Recovers all data to the time of failure Recovery time = Time to restore lost files and apply all archived logs Disadvantages Must have all archived logs since the backup from which you are restoring
  • 230. Complete Recovery Methods 1. Closed database recovery: For system, rollback segment data files, or whole database 2. Open database recovery, with database initially open: For file loss 3. Open database recovery with database initially closed: For hardware failure 4. Recover a datafile with no backup
  • 231. Complete Recovery: Method 1 145 146 Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database 146 145 146 146 146 146 Archived Log File 144 Restore Data File 2 (Log Seq 144) Data File 2 144 1 Instance SGA Redo Log Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Instance SGA Redo Log Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Mount Instance 2 Data Buffer Cache Apply Log Files 3 Open the database 4
  • 232. Complete Recovery: Method 2 Instance SGA Redo Log Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL ARCH 145 146 Data Buffer Cache Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database 146 145 146 146 146 146 Archived Log File 144 Offline Data File 2 Data File 2 146 1 PMON DBWR SMON LGWR CKPT User Process Server Process PGA Restore Data File 2 (Log Seq 144) Data File 2 144 2 Apply Log Files 3 Online Data File 2 Data File 2 146 4
  • 233. Complete Recovery: Method 3 145 146 Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database 146 145 146 146 146 146 Archived Log File 144 Mount the database 1 Instance SGA Redo Log Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH Instance SGA Redo Log Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Data Buffer Cache Offline Data File 2 Data File 2 146 2 Open Database 3 Restore Data File 2 (Log Seq 144) Data File 2 144 4 Apply Log Files 5 Online Data File 2 Data File 2 146 6
  • 234. Complete Recovery: Method 4 145 146 Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database 146 145 146 146 146 146 Archived Log File 144 Offline Data File 2 Data File 2 146 1 Recreate Data File 2 (Log Seq 144) Data File 2 144 2 Apply Log Files 3 Online Data File 2 Data File 2 146 4 Instance SGA Redo Log Buffer Large Pool Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA Data Buffer Cache
  • 235. Recover Syntax Recover a closed database: SVRMGR> recover database; SVRMGR> recover datafile > ‘/disk1/data/df2.dbf’; SVRMGR> alter database recover; SVRMGR> recover tablespace USER_DATA; SVRMGR> recover datafile 2; SVRMGR> alter database recover datafile 2; Recover an open database:
  • 236. Recovery Using Archived Logs To change archive location, use the ‘alter system archive log …’ command To automatically apply redo log files: Issue ‘set autorecovery on’ before starting media recovery Enter ‘auto’ when prompted for an archived log file Use the ‘recover automatic’ command
  • 237. Files Needed for Recovery View V$RECOVER_FILE to locate datafiles needing recovery View V$ARCHIVED_LOG for a list of all archived logs for the database View V$RECOVERY_LOG for a list of all archived logs required for recovery
  • 238. Overview Database Password File Archived Log Files Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 146 145 146 146 146 146 Instance SGA Redo Log Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA User Process Server Process PGA
  • 239. Reasons for Incomplete Recovery User error Complete recovery fails because an archived log is lost Recovery using a backup control file Loss of all unarchived redo logs and the datafile
  • 240. Recovery with Archiving (Incomplete Recovery) Advantages Recovers prior to the time of failure Provides recovery in situations where complete recovery is not possible Disadvantages Database taken back in time (lose data) Recovery time = Time to restore all datafiles + apply required archived logs
  • 241. Types of Incomplete Recovery Time-based recovery Cancel-based recovery Recovery using a backup control file Change-based recovery
  • 242. “ recover” Command Syntax Recover a database until cancel: SVRMGR> recover database until cancel; SVRMGR> recover database 2> until time ‘1997-12-04:14:22:03’; Recover a database until time: SVRMGR> recover database 2> until time ‘1997-12-04:14:22:03’ 3> using backup controlfile; Recover using backup control file:
  • 243. Recovery Steps 1. Shut down and backup the database 2. Restore all data files 3. Do not restore the control file, redo logs, password, or parameter files 4. Mount the database and recover the datafiles before the time of failure 5. Open the database with “resetlogs” 6. Perform a closed database backup
  • 244. Recovery Guidelines Follow/Record all steps since most errors occur during this type of recovery Take whole database backup before and after recovery to assist future recovery Always check if recovery is successful Backup the control file regularly Backup archived logs
  • 245. Time-Based Recovery Scenario: The current time is 12 PM on 9-DEC-97 Your training DBA just told you he dropped the employee (EMP) table The table was dropped around 11:45 AM Database activity is minimal because most staff are currently in a meeting The table must be recovered
  • 246. “ Until Time” Recovery Instance SGA Redo Log Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH User Process Server Process PGA User Process Server Process PGA Shutdown and backup the database 1 Mount database 2 Instance SGA Redo Log Buffer Data Buffer Large Pool Locks Shared Pool Data Dict. Cache Shared SQL & PLSQL PMON DBWR SMON LGWR CKPT ARCH Password File Parameter File Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 Database EMP 146 145 146 146 146 146 Archived Log File 144 Restore all Data Files (Log Seq 144) 3 Data File 3 Data File 2 Data File 1 144 144 144 EMP 4 5 145 145 145 146 145 145 145 145 146 Data File 3 Redo log File 2 Data File 2 Control Files Redo log File 1 Data File 1 1 0 1 1 1 1 EMP Open Database 揜 esetlogs 6 User Process Server Process PGA User Process Server Process PGA Backup database 7
  • 247. Cancel-Based Recovery Scenario: The current time is 12 PM on 9-DEC-97 Your training DBA dropped the EMP table while trying to fix bad blocks Log files exist on the disk containing the employee data file The table was dropped around 11:45 AM
  • 248. Cancel-Based Recovery Findings: Redo logs are not multiplexed One of the online redo logs is missing The missing redo log is not archived The redo log contained information from 11:34 AM Twenty six minutes of data will be lost Users can recover their data
  • 249. Backup Control File Recovery Scenario: The current time is 12 PM on 9-DEC-97 Your training DBA dropped the entire employee tablespace, not just the table The error occurred around 11:45 AM Many employee records were updated this morning, but not since 11:00 AM Backups are taken every night
  • 250. Backup Control File Recovery Findings: The backup last night contains datafiles and control files required for recovery Employee tablespace has one datafile The current log sequence number is 61 You confirm that the tablespace was dropped at 11:44:54 AM on 9-DEC-97. Datafile number 4 is offline.
  • 251. Recover database syntax RECOVER [AUTOMATIC] DATABASE [USING BACKUP CONTROLFILE] [UNTIL < CANCEL | TIME date | CHANGE integer> ] [NOPARALLEL | PARALLEL [integer] ]
  • 252. Loss of control files Should not loss of all control files if configured multiple control files If loss all control files: Method 1: Recreate control file Method 2: Restore backup control file
  • 253. Recreate control files You must get all database structure before recreate control files
  • 254. Recreate control file svrmgr>alter database backup controlfile to trace; The create control file command will exist in the latest trace file Edit the trace file and save to script Run the create control file script
  • 255. Restore backup control file Restore backup control file svrmgr> recover database using backup controlfile;
  • 256. Loss of a Redo Log File Loss of a Redo Log file: Archiving still occurs using a good online redo log file Loss of all redo log files for a group should ‘NEVER’ occur if the database is configured properly using mirrored redo log files
  • 257. Redo Log File Recovery Non-Current logs: Add group, drop group Current logs: If database shutdown normally: 1. Recover database until cancel 2. Alter database open resetlogs If database shutdown abnormally: Have backups: Restore from backups RECOVER DATABASE UNTIL CANCEL and cancel when prev log applied No backup Can be startup in a corruption status Ask Oracle support
  • 258. Scenario 1 Loss of non-current logfiles: svrmgr>alter database add logfile ‘new_file_name’ size 1m; svrmgr>alter database drop logfile <‘old_file_name’ | group n>
  • 259. Scenario 2 Loss of current logfile and instance is shutdown normally: svrmgr>recover database until cancel; cancel svrmgr>alter database open resetlogs;
  • 260. Scenario 3 Loss of current logfile and instance is shutdown abnormally: Have backups Restore backups svrmgr>recover database until cancel; svrmgr>alter database open resetlogs; No backups Ask Oracle support _allow_resetlogs_corruption in init_sid.ora svrmgr>recover database using backup controfile until cancel; svrmgr>alter database open resetlogs; Export database

Editor's Notes

  • #3: Course Objectives In this course, you install the Oracle Database 10 g Enterprise Edition software, create a new database, and learn how to administer the database. You also configure the database to support an application and perform tasks such as creating users, defining storage structures, and setting up security. This course uses a fictional application. However, you perform all the core tasks that are necessary for a real application. Database administration does not end after the database is configured. You also learn how to protect your database by designing a backup and recovery strategy, and how to monitor the database to ensure that it operates smoothly.
  • #5: Oracle Products Oracle databases: The Oracle database is the first database that is designed for enterprise grid computing (the most flexible and cost-effective way to manage information and applications). Oracle Application Server: Oracle’s Java 2 Platform, Enterprise Edition (J2EE)–certified server integrates everything that is needed to develop and deploy Web-based applications. The application server deploys e-business portals, Web services, and transactional applications, including PL/SQL, Oracle Forms, and J2EE-based applications. Oracle applications: Oracle E-Business Suite is a complete set of business applications for managing and automating processes across your organization. Oracle Collaboration Suite: Oracle Collaboration Suite is a single, integrated system for all your organization’s communications data: voice, e-mail, fax, wireless, calendar information, and files. Oracle Developer Suite: Oracle Developer Suite is a complete, integrated environment that combines application development and business intelligence tools. Oracle services: Services such as Oracle Consulting and Oracle University provide you with the necessary expertise for your Oracle projects. For useful links to a variety of resources, see the appendix titled “Next Steps, Continuing Your Education.”
  • #6: Oracle Database Architecture The Oracle server is the key to information management. In general, an Oracle server must reliably manage a large amount of data in a multiuser environment so that many users can concurrently access the same data. All this must be accomplished while delivering high performance. An Oracle server must also prevent unauthorized access and provide efficient solutions for failure recovery.
  • #7: Database Structures Each running Oracle database is associated with an Oracle instance. When a database is started on a database server, the Oracle software allocates a shared memory area called the System Global Area (SGA) and starts several Oracle background processes. This combination of the SGA and the Oracle processes is called an Oracle instance. After starting an instance, the Oracle software associates the instance with a specific database. This is called mounting the database. The database is then ready to be opened, which makes it accessible to authorized users. Multiple instances can execute concurrently on the same computer, each accessing its own physical database. You can look at the Oracle database architecture as various interrelated structural components. An Oracle database uses memory structures and processes to manage and access the database. All memory structures exist in the main memory of the computers that constitute the database server. Processes are jobs that work in the memory of these computers. A process is defined as a “thread of control” or a mechanism in an operating system that can run a series of steps.
  • #8: Oracle Memory Structures The basic memory structures associated with an Oracle instance include the following: System Global Area (SGA): Shared by all server and background processes Program Global Area (PGA): Private to each server and background process. There is one PGA for each process. The SGA is a memory area that contains data and control information for the instance. The SGA includes the following data structures: Database buffer cache: Caches blocks of data retrieved from the database Redo log buffer: Caches redo information (used for instance recovery) until it can be written to the physical redo log files stored on the disk Shared pool: Caches various constructs that can be shared among users Large pool: Is an optional area that provides large memory allocations for certain large processes, such as Oracle backup and recovery operations, and I/O server processes Java pool: Is used for all session-specific Java code and data within the Java Virtual Machine (JVM) Streams pool: Is used by Oracle Streams When you start the instance by using Enterprise Manager or SQL*Plus, the amount of memory allocated for the SGA is displayed.
  • #9: Process Structures When you invoke an application program or an Oracle tool, such as Enterprise Manager, the Oracle server creates a server process to execute the commands issued by the application. The Oracle server also creates a set of background processes for an instance that interact with each other and with the operating system to manage the memory structures, asynchronously perform I/O to write data to disk, and perform other required tasks. Which background processes are present depends on the features that are being used in the database.
  • #10: Oracle Instance Management An Oracle database server consists of an Oracle database and an Oracle instance. An Oracle instance is made up of memory structures, known as the System Global Area (SGA), and background processes that handle much of the behind-the-scenes work involved in running an instance. The most common background processes are the following: System Monitor (SMON): Performs crash recovery when the instance is started following a failure Process Monitor (PMON): Performs process cleanup when a user process fails Database Writer (DBW n ): Writes modified blocks from the database buffer cache to the data files on the disk Checkpoint (CKPT): Updates all the data files and control files of the database to indicate the most recent checkpoint LogWriter (LGWR): Writes redo log entries to the disk Archiver (ARC n ): Copies redo log files to the archival storage when a log switch occurs
  • #11: Server Process and Database Buffer Cache When a query is processed, the Oracle server process looks in the database buffer cache for any blocks that it needs. If the block is not found in the database buffer cache, the server process reads the block from the data file and places a copy in the database buffer cache. Because subsequent requests for the same block may find the block in memory, the requests may not require physical reads. The Oracle server uses the least recently used algorithm to age out buffers that have not been accessed recently to make room for new blocks in the database buffer cache. Buffers in the buffer cache can be in one of the following four states: Pinned: Multiple sessions are kept from writing to the same block at the same time. Other sessions wait to access the block. Clean: The buffer is now unpinned and is a candidate for immediate aging out, if the current contents (data block) are not referenced again. Either the contents are in sync with the block contents stored on the disk or the buffer contains a consistent read (CR) snapshot of a block. Free or unused: The buffer is empty because the instance has just started. This state is very similar to the clean state, except that the buffer has not been used. Dirty: The buffer is no longer pinned but the contents (data block) have changed and must be flushed to the disk by DBW n before it can be aged out.
  • #12: Physical Database Structure The files that constitute an Oracle database are organized into the following: Control files: Contain data about the database itself (that is, physical database structure information). These files are critical to the database. Without them, you cannot open data files to access the data within the database. Data files: Contain the user or application data of the database Online redo log files: Allow for instance recovery of the database. If the database crashes and does not lose any data files, then the instance can recover the database with the information in these files. The following additional files are important to the successful running of the database: Parameter file: Is used to define how the instance is configured when it starts up Password file: Allows users to connect remotely to the database and perform administrative tasks Backup files: Are used for database recovery. You typically restore a backup file when a media failure or user error has damaged or deleted the original file. Archive log files: Contain an ongoing history of the data changes (redo) that are generated by the instance. Using these files and a backup of the database, you can recover a lost data file. That is, archive logs enable the recovery of restored data files.
  • #13: Tablespaces and Data Files A database is divided into logical storage units called tablespaces, which can be used to group related logical structures together. Each database is logically divided into one or more tablespaces. One or more data files are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. Note: You can also create the bigfile tablespaces, which are tablespaces with a single but very large (up to 4 billion data blocks) data file. The traditional smallfile tablespaces (which are the default) can contain multiple data files, but the files cannot be as large. For more information about the bigfile tablespaces, see the Database Administrator’s Guide .
  • #14: SYSTEM and SYSAUX Tablespaces Each Oracle database contains a SYSTEM tablespace and a SYSAUX tablespace. They are automatically created when the database is created. The system default is to create a smallfile tablespace. You can also create bigfile tablespaces, which enable the Oracle database to manage ultralarge files (up to 8 exabytes). A tablespace can be online (accessible) or offline (not accessible). The SYSTEM tablespace is always online when the database is open. It stores tables that support the core functionality of the database, such as the data dictionary tables. The SYSAUX tablespace is an auxiliary tablespace to the SYSTEM tablespace. The SYSAUX tablespace stores many database components, and it must be online for the correct functioning of all database components.
  • #15: Segments, Extents, and Blocks Database objects, such as tables and indexes, are stored as segments in tablespaces. Each segment contains one or more extents. An extent consists of contiguous data blocks, which means that each extent can exist only in one data file. Data blocks are the smallest unit of I/O in the database. When the database requests a set of data blocks from the operating system (OS), the OS maps this to an actual file system or disk block on the storage device. Because of this, you need not know the physical address of any of the data in your database. This also means that a data file can be striped or mirrored on several disks. The size of the data block can be set at the time of the creation of the database. The default size of 8 KB is adequate for most databases. If your database supports a data warehouse application that has large tables and indexes, then a larger block size may be beneficial. If your database supports a transactional application where reads and writes are random, then specifying a smaller block size may be beneficial. The maximum block size depends on your OS. The minimum Oracle block size is 2 KB and should rarely (if ever) be used. You can have tablespaces with different block sizes. However, this should be used only for transportable tablespaces. For details, see the Database Administrator’s Guide .
  • #16: Logical and Physical Database Structures An Oracle database is a collection of data that is treated as a unit. The general purpose of a database is to store and retrieve related information. The database has logical structures and physical structures. Tablespaces A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional one for application indexes. Databases, Tablespaces, and Data Files The relationship among databases, tablespaces, and data files is illustrated in the slide. Each database is logically divided into one or more tablespaces. One or more data files are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. If it is a TEMPORARY tablespace, instead of a data file, then the tablespace has a temporary file.
  • #17: Logical and Physical Database Structures (continued) Schemas A schema is a collection of database objects that are owned by a database user. Schema objects are the logical structures that directly refer to the database’s data. Schema objects include such structures as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links. In general, schema objects include everything that your application creates in the database. Data Blocks At the finest level of granularity, an Oracle database’s data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on the disk. A data block size is specified for each tablespace when it is created. A database uses and allocates free database space in Oracle data blocks. Extents The next level of logical database space is called an extent. An extent is a specific number of contiguous data blocks (obtained in a single allocation) that are used to store a specific type of information. Segments The level of logical database storage above an extent is called a segment. A segment is a set of extents allocated for a certain logical structure. For example, the different types of segments include: Data segments: Each nonclustered, non-indexed-organized table has a data segment. All of the table’s data is stored in the extents of its data segment. For a partitioned table, each partition has a data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster’s data segment. Index segments: Each index has an index segment that stores all of its data. For a partitioned index, each partition has an index segment. Undo segments: One UNDO tablespace is created by the database administrator to temporarily store undo information. The information in an undo segment is used to generate read-consistent database information and, during database recovery, to roll back uncommitted transactions for users. Temporary segments: Temporary segments are created by the Oracle database when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment’s extents are returned to the instance for future use. Specify a default temporary tablespace for every user or a default temporary tablespace, which is used databasewide. The Oracle database dynamically allocates space. When the existing extents of a segment are full, additional extents are added. Because extents are allocated as needed, the extents of a segment may or may not be contiguous on the disk.
  • #18: Course Examples: The HR Sample Schema The examples used in this course are from a human resources (HR) application, which can be created as part of the starter database. The following are some principal business rules of the HR application: Each department may be the employer of one or more employees. Each employee may be assigned to one and only one department. Each job must be a job for one or more employees. Each employee must be currently assigned to one and only one job. When an employee changes his or her department or job, a record in the JOB_HISTORY table records the start and end dates of the past assignments. JOB_HISTORY records are identified by a composite primary key (PK): the EMPLOYEE_ID and the START_DATE columns. Notation: PK = Primary Key, FK = Foreign Key Solid lines represent mandatory foreign key (FK) constraints and dashed lines represent optional FK constraints. The EMPLOYEES table also has an FK constraint with itself. This is an implementation of the business rule: Each employee may be reporting directly to one and only one manager. The FK is optional because the top employee does not report to another employee.
  • #19: Database Architecture: Summary of Structural Components In this lesson, you learned at a high level about the structural components of the Oracle database: memory, process, and storage structures. More details are covered in the following lessons .
  • #23: Prepared By THY SOTHEA, MSc in IT
  • #24: Prepared By THY SOTHEA, MSc in IT Tasks of an Oracle Database Administrator A DBA is typically responsible for installing the Oracle software and creating the database. As a DBA, you may be responsible for creating database storage structures, such as tablespaces. In addition, you may create the schema or set of objects to hold application data. You must ensure that the database is available for users. You can accomplish this by starting up the database, backing up the database on a regular basis, and monitoring the performance of the database. These tasks should be performed within the framework of a security strategy. As you proceed through the lessons in this course, you learn how to perform each of these tasks. You can also refer to the Oracle Database Administrator’s Guide for additional information about each of the tasks outlined in the slide. In this lesson, you focus on installation. For this core task, consider the following subtasks: Understand how the installation fits into the overall technical architecture of an organization. Review (and update) capacity plans. Choose the database software (required version and options). Ensure that system requirements are met for all chosen elements.
  • #25: Prepared By THY SOTHEA, MSc in IT Tools Used to Administer an Oracle Database You can use the following tools for installation and upgrade: Oracle Universal Installer (OUI): Oracle Universal Installer installs your Oracle software and options. It can automatically launch the Database Configuration Assistant (DBCA) to create a database. Database Configuration Assistant (DBCA): It creates a database from Oracle-supplied templates. It enables you to copy a preconfigured seed database. Alternatively, you can create your own database and templates. Database Upgrade Assistant (DBUA): This tool guides you through the upgrade of your existing database to a new Oracle release. Oracle Net Manager: This is used to configure network connectivity for your Oracle databases and applications.
  • #26: Prepared By THY SOTHEA, MSc in IT Installation: System Requirements A standard installation can be completed on a computer with 1 GB of RAM and 1.5 GB of swap space or larger. Depending on the activity level of the machine on which you are installing the Oracle database software, the standard installation can complete in 20 minutes or less. Some installation details: Oracle Database 10 g ships only one seed database template. Duplicated files are removed. Many other products and demonstrations are installable from additional CDs. The hardware requirements listed in the slide are minimal requirements across all platforms. Your installation may have additional requirements (especially disk space). Note: An Enterprise Edition installation type that includes a standard seed database is referred to as a “standard installation.”
  • #27: Prepared By THY SOTHEA, MSc in IT Checking the System Requirements The Oracle Database 10 g installation automates most of the prerequisite checks: Adequate temporary space is checked for. It is determined what the minimum temporary space requirements are for installation and configuration, and those requirements are validated during the installation process. 64-bit installations are prevented from being installed into Oracle homes with 32-bit software already installed (and vice versa). On the Linux platform, RedHat-3.0, 4.0, Asianux 1.0, 2.0, and SUSE Linux E.S. 9.0 are certified. The installation process checks whether all the required OS patches are installed. The installation process checks whether all the required system and kernel parameters are set correctly. The installation process verifies that the DISPLAY environment variable is set and that the user has sufficient permissions to display to the specified DISPLAY . The installation process verifies that the system has sufficient swapping set. The installation process verifies that the Oracle home into which the new installation is being performed is either empty or is one of a handful of supported releases on top of which Oracle Database 10 g can be installed, and that they are registered in the Oracle inventory.
  • #28: Prepared By THY SOTHEA, MSc in IT Optimal Flexible Architecture (OFA) OFA is a method for configuring the Oracle database and other databases. OFA takes advantage of the capabilities of the OS and disk subsystems to create an easy-to-administer configuration that allows maximum flexibility for growing and high-performance databases. The methods described here are the basics of OFA. OFA is designed to: Organize large amounts of complicated software and data on the disk to avoid device bottlenecks and poor performance Facilitate routine administrative tasks, such as software and data backup, which are often vulnerable to data corruption Facilitate switching between multiple Oracle databases Adequately manage and administer database growth Help eliminate fragmentation of free space in the data dictionary, isolate other fragmentation, and minimize resource contention For details about the goals and implementation of OFA, refer to the Oracle Installation Guide for UNIX Systems .
  • #29: Prepared By THY SOTHEA, MSc in IT Using Optimal Flexible Architecture At the core of OFA is a naming scheme that gives you a standard to apply to your mount points (which are often the physical disks), directories and subdirectories on those mount points, and finally the files themselves. Mount point syntax: Name all mount points by using the / pm syntax, where p is a string constant and m is a unique fixed-length key (typically a two-digit number) used to distinguish each mount point. The examples of mount points are /u01 and /u02 . Home directories syntax: Name all home directories by using the / pm / h / u syntax, where pm is a mount point name, h is a standard directory name, and u is the name of the owner of the directory. The examples of OFA-compliant home directories are: /u01/app/oracle /u01/home/oracle Software directories syntax: Store each version of the Oracle software in a directory matching the pattern: / pm / h / u /product/ v . Here, product is a literal and v is a variable for the version number. This syntax helps to enable the OFA feature of simultaneously executing multiple versions of application software. An OFA-compliant installation of the Oracle Database 10 g version 10.2.0 looks like: /u01/app/oracle/product/10.2.0
  • #30: Prepared By THY SOTHEA, MSc in IT Setting Environment Variables There are many Oracle environment variables, and those mentioned here are very important to a successful installation and use of an Oracle database. None of these are required to be set, but by setting them before the installation, you can avoid future problems. ORACLE_BASE : Specifies the base of the Oracle directory structure for OFA. Use of this is optional, but if used, this can facilitate future installations and upgrades. It is a directory path, as shown in this example: /u01/app/oracle ORACLE_HOME : Specifies the directory containing the Oracle software. It is a directory path, as shown in this example: $ORACLE_BASE/product/10.2.0/db_1 ORACLE_SID : The initial instance name (by default, ORCL ). It is a string of numbers and letters that must begin with a letter. Oracle Corporation suggests that a maximum of eight characters be used for system identifiers.
  • #31: Prepared By THY SOTHEA, MSc in IT Oracle Universal Installer (OUI) Oracle Universal Installer (OUI) is a Java application that performs component-based installations and enables different levels of integrated bundle, suite, and Web-based installations, as well as complex logic in a single package. The installation engine is easily portable across all Java-enabled platforms, and platform-specific issues can be encapsulated from the overall installation process. OUI provides the following capabilities for addressing software management and distribution: Automatic dependency resolution and complex logic handling Installation from the Web Component and suite installations Implicit deinstallation Support for multiple Oracle homes NLS or globalization support Support for distributed installations Unattended “silent” installations that use response files In Windows: Insert the Oracle database installation medium, navigate to the client directory and double-click setup.exe to start OUI. After the Welcome page, select your installation type: Instant Client, Administrator, Runtime, or Custom.
  • #32: Prepared By THY SOTHEA, MSc in IT Database Configuration Options Your installation process continues: 6. Navigate through the OUI pages and specify your database configuration options. OUI displays a summary of your installation choices. 7. Click Install to begin your installation of the Oracle software. If you chose to create a starter database as part of the installation, then OUI invokes all of these configuration assistants: Oracle Net Configuration Assistant: This configures basic network components during installation, including: Listener names and protocol addresses Naming methods that the client will use to resolve connect identifiers to connect descriptors Net service names in a tnsnames.ora file Directory server usage Oracle Database Configuration Assistant (DBCA): This creates the starter database that you selected. When this configuration assistant finishes, you can unlock accounts and change passwords. i SQL*Plus Configuration Assistant: This configures the Oracle Application Server Containers for J2EE (OC4J) instance, which is used by i SQLPlus, and other tools to connect to the Oracle database.
  • #33: Prepared By THY SOTHEA, MSc in IT Completing Your Installation 10. When your installation process comes to an end, note the URLs for future use.
  • #35: Prepared By THY SOTHEA, MSc in IT
  • #36: Prepared By THY SOTHEA, MSc in IT Planning the Database It is important to plan how the logical storage structure of the database will affect system performance and various database management operations. For example, before creating any tablespaces for your database, you should know how many data files will make up the tablespace, what type of information will be stored in each tablespace, and on which disk drives the data files will be physically stored. When planning the overall logical storage of the database structure, take into account the effects that this structure will have when the database is actually created and running. You may have database objects that have special storage requirements due to type or size. In distributed database environments, this planning stage is extremely important. The physical location of frequently accessed data dramatically affects application performance. During the planning stage, develop a backup strategy for the database. You can alter the logical storage structure or design of the database to improve backup efficiency. Backup strategies are introduced in a later lesson. These are the types of questions and considerations, which you will encounter as a DBA, and this course (in its entirety) is designed to help you answer them.
  • #37: Prepared By THY SOTHEA, MSc in IT Databases: Examples Different types of databases have their own specific instance and storage requirements. Your Oracle database software includes templates for the creation of these different types of databases. Characteristics of these examples are the following: Data Warehouse: Store data for long periods and retrieve them in read operations. Transaction Processing: Accommodate many, but usually small, transactions. General Purpose: Work with transactions and store them for a medium length of time.
  • #38: Prepared By THY SOTHEA, MSc in IT Database Configuration Assistant (DBCA) You can use the Database Configuration Assistant (DBCA) to create, change the configuration of, or delete a database. You can also create a database from a list of predefined templates or use an existing database as a sample to create a new database or template. This is sometimes referred to as “database cloning.” You can invoke the DBCA by performing the following steps: 1. Log on to your computer as a member of the administrative group that is authorized to install the Oracle software. 2. If required, set environment variables. 3. Enter dbca to invoke the DBCA. 4. Click Next to continue. DBCA offers you a choice of assisting with several operations, for example, creating a database.
  • #39: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Create a Database You can use the DBCA to create a database as follows: 1. Select Create a Database on the DBCA Operations page to invoke a wizard that enables you to configure and create a database. The wizard prompts you to provide configuration information as outlined in the steps that follow. On most pages, the wizard provides a default setting that you can accept. 2. Select the type of database template to be used in creating the database. There are templates for Data Warehouse, General Purpose, and Transaction Processing databases that copy a preconfigured database, including data files. These data files include control files, redo log files, and data files for various included tablespaces. Click Show Details to see the configuration for each type of database. For more complex environments, you may want to select the Custom Database option.
  • #40: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Create a Database (continued) 3. Database Identification: Enter the Global Database Name in the form database_name.domain_name , and the system identifier (SID). The SID defaults to the database name and uniquely identifies the instance associated with the database. 4. Management Options: Use this page to set up your database so that it can be managed with Oracle Enterprise Manager. Select the default: Configure the Database with Enterprise Manager.
  • #41: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Create a Database (continued) 5. Database Credentials: Use this page to specify the passwords for the administrative accounts, such as SYS and SYSTEM . In class, use oracle as password for all administrative accounts. 6. Storage Options: Specify the type of storage mechanism (such as File System) that you would want your database to use. 7. Database File Locations: C hoose according to your needs. Oracle Managed Files (OMF) eliminate the need for you to directly manage the operating system files comprising an Oracle database. You specify operations in terms of database objects rather than file names. For more details, see the lesson titled “Managing Database Storage Structures.”
  • #42: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Create a Database (continued) 8. Recovery Configuration: If required, specify a flash recovery area and enable archiving. 9. Database Content: These pages provide options for selecting components, such as Sample Schemas, and for using custom scripts.
  • #43: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Create a Database (continued) 10. Initialization Parameters: The tabs on this page provide access to pages that enable you to change default initialization parameter settings: Memory: Use this page to set the initialization parameters that control memory usage. Use either (A) Typical or (B) Custom memory allocation. Sizing: To specify block size, enter the size in bytes or accept the default. Character Sets: Use this page to specify the character sets for your database. Best Practice Tip: Oracle recommends (whenever possible) that you use Unicode for a database character set because it provides optimal flexibility for supporting Web technologies as well as many spoken languages. Connection Mode: Select Dedicated or Shared Server Mode. For more details, see the lesson titled “Configuring the Oracle Network Environment.” Note: Several initialization parameters are set for the lifetime of a database, such as the DB_BLOCK_SIZE and CHARACTER_SET parameters.
  • #44: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Create a Database (continued) 11. Database Storage: If you have selected one of the preconfigured templates for a database, then you cannot add or remove control files or data files. Note: You may want to save your database definition as an HTML file for easy reference. 12. Creation Options: You have the options of creating your database at this time, saving the database definition as a template, and generating scripts. If you choose all options, then the DBCA first saves the database template, then generates the scripts into your destination directory, and finally creates your database.
  • #45: Prepared By THY SOTHEA, MSc in IT Password Management After the DBCA finishes, note the following information for future reference: Location of installation log files (see A) Global database name (see B) System identifier (SID) (see B) Server parameter file name and location (see B) Enterprise Manager URL (see C) Click Password Management to unlock database accounts that you plan to use. Provide a password when you unlock an account.
  • #46: Prepared By THY SOTHEA, MSc in IT Creating a Database Design Template A template is a predefined database definition that you use as a starting point for a new database. If you do not create a template as part of the database creation process, you can do it anytime by invoking the DBCA. You have three ways to create a template: From an existing template From an existing database (structure only) From an existing database (structure as well as data) The DBCA guides you through the steps to create a database design template.
  • #47: Prepared By THY SOTHEA, MSc in IT Using the DBCA to Delete a Database To delete (or configure) a database in UNIX or Linux, you must set ORACLE_SID in the shell from which DBCA is launched. Start the DBCA by entering dbca in a terminal window, and click Next on the Welcome page. To delete the database, perform the following steps: 1. On the Operations page, select Delete a Database, and click Next. 2. Select the database that you want to delete (in class, hist ), and click Finish. 3. Click Yes to confirm your deletion.
  • #48: Prepared By THY SOTHEA, MSc in IT
  • #49: Prepared By THY SOTHEA, MSc in IT
  • #180: LOG_ARCHIVE_FORMAT=“LOG%s_%t.arc” %s log sequence number %t thread number
  • #237: 8
  • #238: 8
  • #240: 4
  • #242: 7
  • #244: 4
  • #245: 4
  • #246: 23
  • #248: 23
  • #249: 23
  • #250: 23
  • #251: 23