311
Tulsi ocp Understanding Oracle Fundamentals

3_day_back_end

Embed Size (px)

DESCRIPTION

3_day_back_end

Citation preview

Page 1: 3_day_back_end

Tulsi ocp

Understanding Oracle Fundamentals

Page 2: 3_day_back_end

Tulsi ocp

Database structure

Oracle database has both physical and logical Structure

-physical structure is made of o/s files-logical structure is made of one or more tablespaces and schema objects

Page 3: 3_day_back_end

Tulsi ocp

Physical Structures

Data files

Redo log files

Control files

Page 4: 3_day_back_end

Tulsi ocp

Physical structures

Data files are used to store all the database objects which are administered by the oracle system.Redo log files contain records of all database changes which are carried out in the course of transactionsControl files record information about physical structure of database

Page 5: 3_day_back_end

Tulsi ocp

Physical structure and the database

A B C

datfile1

datfile 2datfile3 datfile4

The total size of this database is size(A)+size(B)+size(c)

Page 6: 3_day_back_end

Tulsi ocpDatabase

OverviewOverviewInstance

SGA

Redo logbuffer

Data buffercache

Shared pool

Data dict.cache

Librarycache

PMONDBW0SMON LGWRCKPT Others

Userprocess

Serverprocess

PGA

Control files

Data files

Redo logfiles

Archived log files

Parameterfile

Passwordfile

Page 7: 3_day_back_end

Tulsi ocp

Logical structure

••DatabaseDatabase••TablespaceTablespace••SegmentSegment••ExtentExtent••datablockdatablock

Page 8: 3_day_back_end

Tulsi ocp

Tablespace(contd)

Oracle stores data logically in tablespaceslogical storage unitSYSTEM tablespace is always present and is always ONLINE. Contains the Data DictionaryOne or more user defined table spaces can be present, which may be ONLINE or OFFLINE

Page 9: 3_day_back_end

Tulsi ocp

Schema ObjectsTables Indexes - for faster accessSynonyms - to mask owner(security)Sequences -used to automatically generate numbersViews - virtual tablesTriggersStored Procedures and FunctionsClusters - faster access

Page 10: 3_day_back_end

Tulsi ocp

Tablespace containing object from multiple schemas

user1.tab1 user2.tab2

user1.tab1.ind user3.tab1

User tablespace

Page 11: 3_day_back_end

Tulsi ocp

Space Allocation

A tablespace can contain objects from different schemasWhen an object is created in a tablespace storage is allocated in logical units called extentsAn extent is a logical unit of database storage space allocation made up of a contiguous number of data blocks

Page 12: 3_day_back_end

Tulsi ocp

TRAINING tablespaceSYSTEM tablespace

Data3.ora4 MB

Data1.ora4 MB Data2.ora

1 MB

ORACLE DatabaseORACLE Database

user1.tbl1

usr2.tbl1

usr2.vw1Data Dictionary

usr3.tbl1

Page 13: 3_day_back_end

Tulsi ocp

Data Blocks and Extents

Data Block– At the finest level of granularity, data is stored in

Data blocks. – One block corresponds to a number of physical

bytes on the diskExtents– Storage allocation is done in terms of extents– Set of contiguous data blocks– One extent cannot span files

Page 14: 3_day_back_end

Tulsi ocp

Data Blocks

Header: Block addr. & segment typeTable directoryRow directoryRow dataPCTFREEPCTUSED

Page 15: 3_day_back_end

Tulsi ocp

Segments

Segment – Set of extents that have been allocated for a

specific data structure– All extents belonging to a segment are stored in

one tablespace

Page 16: 3_day_back_end

Tulsi ocp

Types of Segments

Data Segment – Every non-clustered table has it’s own data

segment– Every cluster has it’s own data segment

Index Segment– Every index has it’s own index segment

Page 17: 3_day_back_end

Tulsi ocp

Types of Segments(contd)

Rollback Segment– Created to store “undo” information

Temporary Segment– Used as temporary work areas to complete

execution of SQL statements

Page 18: 3_day_back_end

Tulsi ocp

Oracle Instance

ORACLE Instance consists of– SGA– ORACLE Background processes

Page 19: 3_day_back_end

Tulsi ocp

Oracle InstanceOracle Instance

Background Background processesprocesses

Memory Memory structuresstructures

Instance

SGA

Redo logbuffer

Data buffercache

Shared pool

PMONDBW0SMON LGWRCKPT Others

An Oracle instance:Is a means to access an Oracle databaseAlways opens one and only one database

Page 20: 3_day_back_end

Tulsi ocp

Memory Structures & Processes

Memory Structures:– SGA [System Global Area]– PGA [Program Global Area]

Processes– User Process– ORACLE Processes

Server ProcessesBackground Processes

Page 21: 3_day_back_end

Tulsi ocp

System Global Area

User User User User

LGWR SMON PMON RECODBWR

Page 22: 3_day_back_end

Tulsi ocp

Memory Structures

System Global Area

Database buffercache

sharedpool

Redo logbuffer

Data dictionarycache

Library cache

Page 23: 3_day_back_end

Tulsi ocp

Page 24: 3_day_back_end

Tulsi ocp

Page 25: 3_day_back_end

Tulsi ocp

Page 26: 3_day_back_end

Tulsi ocp

Processes

User processes– Created and maintained to execute code of an

application programORACLE Processes– Server processes– Background processes

Page 27: 3_day_back_end

Tulsi ocp

Server Process

Handle requests from Client ProcessCommunicate to ORACLE to carry out requests from Client ProcessEx: Reading data from data file into SGA if data is not present in the SGA database buffer

Page 28: 3_day_back_end

Tulsi ocp

Page 29: 3_day_back_end

Tulsi ocp

Page 30: 3_day_back_end

Tulsi ocp

Background Processes

Database writer(DBWR)Log writer(LGWR)Archiver(ARCH)System Monitor(SMON)Process Monitor(PMON)Checkpoint(CKPT)

Page 31: 3_day_back_end

Tulsi ocp

DBWR

The database writer process writes the modified data base buffer blocks on to the database files on disk Keeps most frequently used blocks in memory

Page 32: 3_day_back_end

Tulsi ocp

Page 33: 3_day_back_end

Tulsi ocp

DBWR(contd)

The database writer writes modified data blocks when– the buffer is full and a data block which is not in

memory is required– at checkpoint time-all committed and

uncommitted data is written

Page 34: 3_day_back_end

Tulsi ocp

LGWR

The log writer is the process responsible for emptying the contents of the redo log buffer onto the redo log files.The log writer writes when– the redo log buffer is 1/3 full– at commit time– whenever the database buffers are written– checkpoint time

Page 35: 3_day_back_end

Tulsi ocp

Page 36: 3_day_back_end

Tulsi ocp

SMON and PMON

SMON performs instance recovery at startup , makes free blocks available and cleans up temporary segmentsPMON performs process recovery when a process fails, cleans up cache and resources used by a process

Page 37: 3_day_back_end

Tulsi ocp

SMON

Detection of deadlocks and termination of one of the transactionsFree fragmented spaceRelease temporary segmentsAutomatic Instance recovery when an instance failure has occurred(by using Redo Log)

Page 38: 3_day_back_end

Tulsi ocp

PMON

PMON is the process responsible for freeing resources and rolling back aborted transactions if a user process terminates abnormally due to some error

Page 39: 3_day_back_end

Tulsi ocp

CKPT

Optional processSignals DBWR to write at checkpointsDBWR writes contents of DB buffer to diskUpdates headers of data files and control files to reflect the most recent checkpoint

Page 40: 3_day_back_end

Tulsi ocp

Page 41: 3_day_back_end

Tulsi ocp

Page 42: 3_day_back_end

Tulsi ocp

Page 43: 3_day_back_end

Tulsi ocp

SGA Buffers

Database buffer cache is emptied onto the data files using the LRU algorithmRedo log buffers have the changes made to the databaseRedo log buffers-are emptied onto redo log files

Page 44: 3_day_back_end

Tulsi ocp

SGA Buffers (contd)

The data blocks which have been requested by a user program are placed in the database buffer cache before they can be processed by the user program. Once a data block has been placed in one of the buffers then it can be used not only by the process which first requested it, but by any other user process

Page 45: 3_day_back_end

Tulsi ocp

SGA Shared Pool

The shared pool-Oracle uses this area of the SGA to store parsed SQL statements, compiled functions and procedures, data dictionary information and database triggers. Can be accessed by multiple applications

Page 46: 3_day_back_end

Tulsi ocp

PGA

Data and control info for one single server processAllocated only when user gets connected

Page 47: 3_day_back_end

Tulsi ocp

Page 48: 3_day_back_end

Tulsi ocp

Database and Instance Startup

Start database [reads Parameter file before this]– allocate & create SGA, Background processes

Mount database– Associate database with previously started instance– Find and open control file– Read Redo /data file names from this file and confirm

existence

Open database– Open online log files and data files– Automatically perform instance recovery(SMON)– Acquire one/more rollback segments

Page 49: 3_day_back_end

Tulsi ocp

Database and Instance Shutdown

Close database– Write all buffer data to disk– Close Online redo files and data files– Close database

Dismount database– Close control files– Dissociate database from Instance

Shut down instance– Remove SGA from memory

T i t b k d

Page 50: 3_day_back_end

Tulsi ocpDatabase

Control files

Data files

Redo logfiles

Passwordfile

Parameterfile

Tracefiles

ALERTfile

InstanceSGA

Shared pool

Userprocess

Serverprocess

PGA

OverviewOverview

Page 51: 3_day_back_end

Tulsi ocp

Database

Logical Physical

Tablespace Data file

OS blockOracleblock

Segment

Extent

OverviewOverview

Page 52: 3_day_back_end

Tulsi ocp

Block Space Utilization ParametersBlock Space Utilization Parameters

INITRANSINITRANS

MAXTRANSMAXTRANS

PCTFREEPCTFREE

PCTUSEDPCTUSED

Page 53: 3_day_back_end

Tulsi ocp

Block Space UsageBlock Space Usage

InsertsInserts

InsertsInserts

InsertsInserts

InsertsInserts

1 2

3 4

PCTFREE=20PCTFREE=20 PCTUSED=40PCTUSED=40

80%80%

80%80%

40%40%

Page 54: 3_day_back_end

Tulsi ocp

Page 55: 3_day_back_end

Tulsi ocp

Row chaining

The data for a row in a table may be too large to fit into a single data block. In the first case, the row is too large to fit into one data block when it is first inserted. In this case, Oracle stores the data for the row in a chain of data blocks (one or more) reserved for that segment. Row chaining most often occurs with large rows, such as rows that contain a column of datatypeLONG or LONG RAW. Row chaining in these cases is unavoidable.

Page 56: 3_day_back_end

Tulsi ocp

Row Migration

a row that originally fit into one data block is updated so that the overall row length increases, and the block's free space is already completely filled. In this case, Oracle migratesthe data for the entire row to a new data block, assuming the entire row can fit in a new block. Oracle preserves the original row piece of a migrated row to point to the new block containing the migrated row; the rowid of a migrated row does not change

Page 57: 3_day_back_end

Tulsi ocp

Building a Database for Performance

• Creating a database is the first step in managing a

database system• A database may have been created

automaticallyas part of Oracle9i Server installation, or you

cancreate a new one later

Page 58: 3_day_back_end

Tulsi ocp

To create a new database, you must have thefollowing:• A privileged account authenticated in one of

thefollowing ways:– By the operating system– Using a password file• Sufficient memory to start the instance• Sufficient disk space for the planned

database

Page 59: 3_day_back_end

Tulsi ocp

Planning Database File Locations

• Keep at least two active copies of a databasecontrol file on at least two different devices.• Multiplex the redo log files and put groupmembers on different disks.• Separate data files whose data:– Will participate in disk resource contention

acrossdifferent physical disk resources– Have different life spans

Have different administrative characteristics

Page 60: 3_day_back_end

Tulsi ocp

Creating a Database

An Oracle database can be created using:• Oracle Database Configuration Assistant• The CREATE DATABASE command

Page 61: 3_day_back_end

Tulsi ocp

Complete Database Creation

Complete database creation using the following

options:• Create database• Save as a database template• Generate database creation scripts

Page 62: 3_day_back_end

Tulsi ocp

Creating a Database Manually

• Decide on a unique instance and database name

• Choose a database character set• Set the operating system variables• Edit / Create the initialization parameter file• Start the instance (nomount)• Execute the CREATE DATABASE command• Run scripts to generate the data dictionary

andaccomplish post creation steps

Page 63: 3_day_back_end

Tulsi ocp

Tuning questions

who tunes?application designersapplication developersdatabase administratorssystem administrators

Page 64: 3_day_back_end

Tulsi ocp

Why tune?How much tuning ?

There are basically two forms of tuningspeed : short response timehigh throughput scalability: higher load at a comparable response time or throughput

Page 65: 3_day_back_end

Tulsi ocp

Tuning goals

Reducing or eliminating waitsAccessing the least number of blocksCaching blocks in memoryResponse timeThroughputloadrecovery time

Page 66: 3_day_back_end

Tulsi ocp

Examples of Measurable Tuning Goals

Improved response timeImproved database availabilityImproved database hit percentagesImproved memory utilizationfewer waits

Page 67: 3_day_back_end

Tulsi ocp

Common Tuning Problems

Bad session managementBad cursor managementBad relational designs

Page 68: 3_day_back_end

Tulsi ocp

proactive tuning considerations during development

Tune the designTune the applicationTune the memoryTune I/OTune contentionTune the operating system

Page 69: 3_day_back_end

Tulsi ocp

Tuning steps during production

Locate the bottleneck by using toolsDetermine the reason for the bottleneckResolve the causeCheck that the bottleneck has been resolved

Page 70: 3_day_back_end

Tulsi ocp

Performance versus safety Trade-offs

Factors that affect performance

Multiple control filesMultiple redo log members in a groupfrequent checkpointingBacking up datafilesPerforming archivingBlock check numberNumber of concurrent users and transactions

Page 71: 3_day_back_end

Tulsi ocp

To enhance performance, you can use the following data access methods:Indexes1. B-tree2. Bitmap3. Reverse keyClustersHistograms

Page 72: 3_day_back_end

Tulsi ocp

Page 73: 3_day_back_end

Tulsi ocp

Page 74: 3_day_back_end

Tulsi ocp

Bitmap indexes

used for low cardinality columnsgood for multiple predicatesMinimal storage space usedBest for read-only systemsgood for very large tables

Page 75: 3_day_back_end

Tulsi ocp

Creating bitmap indexes

Page 76: 3_day_back_end

Tulsi ocp

Comparison of B*tree and bitmap indexes

Page 77: 3_day_back_end

Tulsi ocp

Reverse Key Index

Page 78: 3_day_back_end

Tulsi ocp

Creating reverse Key index

Page 79: 3_day_back_end

Tulsi ocp

clusters

Page 80: 3_day_back_end

Tulsi ocp

Cluster types

Page 81: 3_day_back_end

Tulsi ocp

Histograms

Describe data distribution of a particular columnAllow the cost based optimizer to estimate the selectivity of a query

Page 82: 3_day_back_end

Tulsi ocp

Overview of SQL Processing Architecture

The SQL processing architecture contains the following main components:ParserOptimizerRow Source GeneratorSQL Execution Engine

Page 83: 3_day_back_end

Tulsi ocp

Page 84: 3_day_back_end

Tulsi ocp

parser

The parser performs two functions:Syntax analysis: This checks SQL statements

for correct syntax.Semantic analysis: This checks, for example,

that the current database objects and object attributes referenced are correct.

Page 85: 3_day_back_end

Tulsi ocp

optimizer

The optimizer uses internal rules or costing methods to determine the most efficient way of producing the result of the query. The Oracle server provides twomethods of optimization: cost-based optimizer (CBO) rule-based optimizer (RBO).

Page 86: 3_day_back_end

Tulsi ocp

Row Source Generator

The row source generator receives the optimal plan from the optimizer. It outputs the execution plan for the SQL statement. The execution plan is a collection of row sources structured in the form of a tree.Each row source returns a set of rows for that

step.

Page 87: 3_day_back_end

Tulsi ocp

SQL Execution Engine

SQL execution is the component that operates on the execution plan associated with a SQL statement. It then produces the results of the query. Each row source produced by the row source generator is executed by the SQL execution engine.

Page 88: 3_day_back_end

Tulsi ocp

Steps in Optimizer Operations

Evaluation of expressions and conditions Statement transformation Choice of optimizer approaches Choice of access paths Choice of join orders Choice of join methods

Page 89: 3_day_back_end

Tulsi ocp

Explain plan

Page 90: 3_day_back_end

Tulsi ocp

Page 91: 3_day_back_end

Tulsi ocp

Page 92: 3_day_back_end

Tulsi ocp

Optimization approaches

Cost based optimizationRule based optimization

Page 93: 3_day_back_end

Tulsi ocp

CBO

Cost based (CBO)= Using the cost-based approach, the optimizer determines which execution plan is most efficient by considering available access paths and factoring in information based on statistics for the schema objects Chooses least cost pathstatistics driven

Page 94: 3_day_back_end

Tulsi ocp

RBO

uses a ranking systemsyntax drivenorder of conditions does not matter

Page 95: 3_day_back_end

Tulsi ocp

Architecture of the CBOQuery TransformerEstimatorPlan Generator

Page 96: 3_day_back_end

Tulsi ocp

Page 97: 3_day_back_end

Tulsi ocp

Query transformer– The main objective of the query transformer is to

determine if it is advantageous to change the form of the query so that it enables generation of a better query plan.

Page 98: 3_day_back_end

Tulsi ocp

Estimator– Selectivity– Cardinality

Effective cardinalityGroup cardinalityJoin cardinalityDistinct cardinality

– CostDisk I/OCpu usageMemory usage as units of work

Page 99: 3_day_back_end

Tulsi ocp

Understanding Access Paths for the CBO

Full Table Scans Sample Table Scans Rowid Scans Index Scans Cluster Scans Hash Scans

Page 100: 3_day_back_end

Tulsi ocp

How the CBO Chooses the Join Method

A nested loop join is inefficient when a join returns a large number of rows (typically, more than 10,000 rows is considered large), and the optimizer might choose not to use it. The cost of a nested loop join is calculated by the following formula:

cost = access cost of A + (access cost of B * number of rows from A)

Page 101: 3_day_back_end

Tulsi ocp

Hash join

cost = (access cost of A * number of hash partitions of B) + access cost of B

Sort-merge join

cost = access cost of A + access cost of B + (sort cost of A + sort cost of B)

Page 102: 3_day_back_end

Tulsi ocp

Use EXPLAIN PLAN and TKPROF To Tune

Page 103: 3_day_back_end

Tulsi ocp

The Plan TableA plan table holds execution plans generated by the EXPLAIN PLAN statement.

The typical name for a plan table is plan_table, but you may use any name you wish.

Create the plan table by running utlxplan.sql, located in $ORACLE_HOME/rdbms/admin.

Page 104: 3_day_back_end

Tulsi ocp

Important Columns in the Plan Table

statement_id Unique identifier for each execution plantimestamp When the execution plan was generatedoperation The operation performed in one step of the execution plan, such as “table access”options Additional information about the operation, such as “by index ROWID”object name Name of table, index, view, etc. accessedoptimizer Optimizer goal used when creating

execution planid Step number in execution planparent_id Step number of parent step

Page 105: 3_day_back_end

Tulsi ocp

EXPLAIN PLAN Prerequisites

INSERT privilege on a plan tableAll necessary privileges to execute the statement being explainedSELECT privileges on underlying tables of views, if the statement being explained involves views

Page 106: 3_day_back_end

Tulsi ocp

EXPLAIN PLAN SyntaxEXPLAIN PLAN

[SET STATEMENT_ID = <string in single quotes>]

[INTO <plan table name>]

FOR

<SQL statement>;

Page 107: 3_day_back_end

Tulsi ocp

Querying an Execution Plan from the Plan Table

Use a CONNECT BY clause to trace the hierarchyUse LPAD function to indent rows, making the hierarchy easier to followPut statement_id in WHERE clause to retrieve only one execution plan at a timeSample script on next slide shows the most important informationYou can also try utlxpls.sql or utlxplp.sql in $ORACLE_HOME/rdbms/admin

Page 108: 3_day_back_end

Tulsi ocp

Trace Files and TKPROF

The Oracle server process managing a database session writes a verbose trace file when SQL trace is enabled for the session. TKPROF is a utility provided by Oracle that formats SQL trace files into very helpful and readable reports. TKPROF is installed automatically when the database server software is installed. You invoke TKPROF from the operating system command line; there is no graphical interface for TKPROF.

Page 109: 3_day_back_end

Tulsi ocp

Enabling SQL TraceAt the instance level:sql_trace = true

timed_statistics = true (optional)

In your own session:ALTER SESSION SET sql_trace = TRUE;

ALTER SESSION SET timed_statistics = TRUE; (optional)

Page 110: 3_day_back_end

Tulsi ocp

Finding the Trace FileLook in the user dump destination. On OFA compliant systems this will be$ORACLE_BASE/admin/$ORACLE_SID/udumpCheck timestamps and file contents to see which trace file is yours

Page 111: 3_day_back_end

Tulsi ocp

Formatting a Trace File with TKPROF

Invoke TKPROF from the operating system prompt like this:tkprof <trace file> <output file> \

[explain=<username/password>] \[sys=n] [sort=<keyword>]

Page 112: 3_day_back_end

Tulsi ocp

TKPROF Command-line Arguments

trace file The SQL trace file to be formattedoutput file The formatted output to be written by TKPROFexplain= Database login to be used if you want the output to

include execution planssys=n Omit “recursive SQL” performed by the SYS user

tkprof <trace file> <output file> \[explain=<username/password>] \[sys=n]

Page 113: 3_day_back_end

Tulsi ocp

TKPROF Sample OutputSELECT a.customer_name, a.customer_number, b.invoice_number,

b.invoice_type, b.invoice_date, b.total_amount, c.line_number,c.part_number, c.quantity, c.unit_cost

FROM customers a, invoices b, invoice_items cWHERE c.invoice_id = :b1AND c.line_number = :b2AND b.invoice_id = c.invoice_idAND a.customer_id = b.customer_id

call count cpu elapsed disk query current rows------- ------ -------- ---------- ---------- ---------- ---------- ----------Parse 1 0.05 0.02 0 0 0 0Execute 1 0.00 0.00 0 0 0 0Fetch 2 0.00 0.00 8 8 0 1------- ------ -------- ---------- ---------- ---------- ---------- ----------total 4 0.05 0.02 8 8 0 1

Misses in library cache during parse: 1Optimizer goal: CHOOSEParsing user id: 34 (RSCHRAG)

Page 114: 3_day_back_end

Tulsi ocp

Execution Plan OperationsTABLE ACCESS FULL

Perform a full table scan of the indicated table and retrieve all rows that meet criteria from the WHERE clause. Input: no subordinate operations. Output: the necessary columns from the rows meeting all criteria.

SORT ORDER BY

Sort the input rows for the purpose of satisfying an ORDER BY clause. Input: the rows to be sorted.Output: the rows in sorted order.

Page 115: 3_day_back_end

Tulsi ocp

Execution Plan OperationsINDEX UNIQUE SCAN

Look up a complete key in a unique index. Input:usually no subordinate operations. (Key values typically come from the original query or a parent operation.) Output: zero or one ROWIDs from the index.

INDEX RANGE SCAN

Look up a key in a non-unique index, or an incomplete key in a unique index. Input: usually no subordinate operations. Output: zero or more ROWIDs from the index.

Page 116: 3_day_back_end

Tulsi ocp

Execution Plan OperationsTABLE ACCESS BY INDEX ROWID

Look up rows in a table by their ROWIDs. Input: a list of ROWIDs to look up. Output: the necessary columns from the rows with the given ROWIDs.

NESTED LOOPS

Perform a join between two sets of row data using the nested loops algorithm. Inputs: two separate sets of row data. Output: the results of the join.

For each row Oracle reads from the first input, the operations that make up the second input are executed once and matching rows generate output.

Page 117: 3_day_back_end

Tulsi ocp

Execution Plan OperationsHASH JOIN

Perform a join between two sets of row data using the hash join algorithm. Inputs: two separate sets of row data. Output: the results of the join.

Oracle reads all rows from the second input and builds a hash structure, before reading each row from the first input one at a time. For each row from the first input, the hash structure is probed and matching rows generate output.

Page 118: 3_day_back_end

Tulsi ocp

Execution Plan Operations

NESTED LOOPS OUTER

Same as the NESTED LOOPS operation, except that an outer join is performed.

SORT GROUP BY

Same as the SORT ORDER BY operation, except that the rows are sorted and grouped to satisfy a GROUP BY clause.

Page 119: 3_day_back_end

Tulsi ocp

Elements of a TKPROF ReportReport heading

– TKPROF version, date run, sort option, trace fileOne entry for each distinct SQL statement in trace file

– Listing of SQL statement– OCI call statistics: count of parse, execute, and fetch

calls, rows processed, and time and I/O used– Parse information: parsing user, recursive depth,

library cache misses, and optimizer mode– Row source operation listing– Execution plan listing (optional)– Wait event listing (optional)

Page 120: 3_day_back_end

Tulsi ocp

Sample TKPROF Report Heading

TKPROF: Release 8.1.6.1.0 - Production on Wed Aug 9 19:06:36 2000

(c) Copyright 1999 Oracle Corporation. All rights reserved.

Trace file: example.trcSort options: default************************************************************************count = number of times OCI procedure was executedcpu = cpu time in seconds executing elapsed = elapsed time in seconds executingdisk = number of physical reads of buffers from diskquery = number of buffers gotten for consistent readcurrent = number of buffers gotten in current mode (usually for update)rows = number of rows processed by the fetch or execute call

Page 121: 3_day_back_end

Tulsi ocp

Sample Call StatisticsSELECT table_nameFROM user_tablesORDER BY table_name

call count cpu elapsed disk query current rows------- ------ -------- ---------- --------- --------- --------- ---------Parse 1 0.01 0.02 0 0 0 0Execute 1 0.00 0.00 0 0 0 0Fetch 14 0.59 0.99 0 33633 0 194------- ------ -------- ---------- --------- --------- --------- ---------total 16 0.60 1.01 0 33633 0 194

Misses in library cache during parse: 1Optimizer goal: CHOOSEParsing user id: RSCHRAG [recursive depth: 0]

Page 122: 3_day_back_end

Tulsi ocp

What the TKPROF Sample on the Previous Slide Tells Us

The application called on Oracle to parse this statement once while SQL trace was enabled.The parse took 0.01 CPU seconds, 0.02 elapsed seconds.No disk I/Os or buffer gets took place during the parse, suggesting that no misses in the dictionary cache.Oracle was called on to execute this statement once.The execution took under 0.01 CPU seconds.No disk I/Os or buffer gets took place during the execution. (Queries often defer the work to the fetch phase.)Oracle was called on 14 times to perform a fetch, and a total of194 rows were returned.

Page 123: 3_day_back_end

Tulsi ocp

What the TKPROF Sample Tells Us (continued)

Fetching took 0.59 CPU seconds, 0.99 elapsed seconds.Fetching required 33,633 buffer gets in consistent mode, but no physical reads were required.The statement was not in the library cache (shared pool) when the parse call came in.The cost-based optimizer and a goal of “choose” were used to parse the statement.The RSCHRAG user was connected to the database when the parse occurred.This statement was executed directly by the application; it was not invoked recursively by the SYS user or a database trigger.

Page 124: 3_day_back_end

Tulsi ocp

Sample Row Source Operation ListingRows Row Source Operation------- ---------------------------------------------------

194 SORT ORDER BY194 NESTED LOOPS195 NESTED LOOPS OUTER195 NESTED LOOPS OUTER195 NESTED LOOPS

11146 TABLE ACCESS BY INDEX ROWID OBJ$11146 INDEX RANGE SCAN (object id 34)11339 TABLE ACCESS CLUSTER TAB$12665 INDEX UNIQUE SCAN (object id 3)

33 INDEX UNIQUE SCAN (object id 33)193 TABLE ACCESS CLUSTER SEG$387 INDEX UNIQUE SCAN (object id 9)194 TABLE ACCESS CLUSTER TS$388 INDEX UNIQUE SCAN (object id 7)

Page 125: 3_day_back_end

Tulsi ocp

Sample Execution Plan ListingRows Execution Plan------- ---------------------------------------------------

0 SELECT STATEMENT GOAL: CHOOSE194 SORT (ORDER BY)194 NESTED LOOPS195 NESTED LOOPS (OUTER)195 NESTED LOOPS (OUTER)195 NESTED LOOPS

11146 TABLE ACCESS (BY INDEX ROWID) OF 'OBJ$'11146 INDEX (RANGE SCAN) OF 'I_OBJ2' (UNIQUE)11339 TABLE ACCESS (CLUSTER) OF 'TAB$'12665 INDEX (UNIQUE SCAN) OF 'I_OBJ#' (NON-UNIQUE)

33 INDEX (UNIQUE SCAN) OF 'I_OBJ1' (UNIQUE)193 TABLE ACCESS (CLUSTER) OF 'SEG$'387 INDEX (UNIQUE SCAN) OF 'I_FILE#_BLOCK#' (NON-UNIQUE)194 TABLE ACCESS (CLUSTER) OF 'TS$'388 INDEX (UNIQUE SCAN) OF 'I_TS#' (NON-UNIQUE)

Page 126: 3_day_back_end

Tulsi ocp

TKPROF Reports: More Than Just Execution Plans

Listing of SQL statements and library cache miss information helps you determine if applications are using Oracle’s shared SQL facility effectively.Parse, execute, and fetch call counts help you determine if applications are using Oracle APIs effectively. CPU and I/O statistics help you zero in on resource-intensive SQL statements. Row counts on individual steps of the execution plans help you rework inefficient execution plans.

Page 127: 3_day_back_end

Tulsi ocp

STATSPACK

Installing of statspackC:/ORACLE/ORA92/RDBMS/ADMIN/SPCREATE.SQL

Collection of statisticsEXECUTE STATSPACK.SNAPAutomatic collection of statisticsC:/ORACLE/ORA92/RDBMS/ADMIN/SPAUTO.SQLProduce a report

C:/ORACLE/ORA92/RDBMS/ADMIN/SPREPORT.SQLTo collect timing information

set timed_statistics=TRUE

Page 128: 3_day_back_end

Tulsi ocp

Statspack output

Information found on the first page:Database and instance nameTime at which the snapshots were taken Current size of the cachesLoad profile

Page 129: 3_day_back_end

Tulsi ocp

UTLBSTAT AND UTLESTAT

THESE UTILITIESGATHER PERFORMANCE FIGUES OVER

A DEFINED PERIODRun the scripts form sql*plus as sysdbaStatspack provide clearer statistics

Page 130: 3_day_back_end

Tulsi ocp

Sql*plus autotrace

Create the plan_table tableCreate and grant the plustrace roleSql> c:/…../sqlplus/admin/plustrce.sqlGrant plustrce to scott;

Set autotrace on

Page 131: 3_day_back_end

-by tulsi ocp

Getting Started With the Oracle Getting Started With the Oracle ServerServer

Page 132: 3_day_back_end

Tulsi ocp

ToolSQL*Plus Line Mode

Oracle Enterprise Manager

SQL*Loader

Export or Import utility

Password File utility

DescriptionA utility used for administrative tasks such as starting up, shutting down, or recovering a databaseGraphical user interface to administer, monitor, and tune one or more databases

Utility for loading data from external files into Oracle tables

Utility for exporting or importing data in Oracle format

Utility for creating database password file

Database Administration Tools: Examples

Page 133: 3_day_back_end

Tulsi ocp

Database Administrator Users

The two default database administrator users SYS

and SYSTEM are:Created automaticallyGranted the DBA role

Page 134: 3_day_back_end

Tulsi ocp

Users SYS and SYSTEM

SYS

Password: change_on_install

Owner of the database data dictionary

SYSTEM

Password:manager

Owner of additional internal tables and views used by Oracle tools

Page 135: 3_day_back_end

Tulsi ocp

Operating System Authentication

Set up the user to be authenticated by the operating system.Set REMOTE_LOGIN_PASSWORDFILE to NONE.Use the following commands to connect to a database:CONNECT / AS SYSDBA

CONNECT / AS SYSOPER

CONNECT / AS SYSDBA

CONNECT / AS SYSOPER

Page 136: 3_day_back_end

Tulsi ocp

The Oracle unified system management enterprise frameworkCentral view of complete managed systemSet of underlying servicesFree-of-charge DBA Management PackPerformance, tuning, diagnostics, and change management packsApplication Management Pack

What Is Oracle Enterprise Manager?

Page 137: 3_day_back_end

Tulsi ocp

Configuration Assistant

Page 138: 3_day_back_end

Tulsi ocp

Enterprise Manager ConsoleEnterprise Manager Enterprise Manager ConsoleConsole

5 621 3 4

Page 139: 3_day_back_end

Tulsi ocp

DBA Management Pack

Instance ManagerSecurity ManagerStorage ManagerSchema ManagerSQL*Plus WorksheetTools and wizards for data management and backup

Page 140: 3_day_back_end

-by tulsi ocp

Managing an Oracle Instance

Page 141: 3_day_back_end

Tulsi ocpDatabase

Control files

Data files

Redo logfiles

Passwordfile

Parameterfile

Tracefiles

ALERTfile

InstanceSGA

Shared pool

Userprocess

Serverprocess

PGA

OverviewOverview

Page 142: 3_day_back_end

Tulsi ocp

initU15.orainitU15.ora

The Initialization Parameter File

SQL> CONNECT / AS SYSDBA

SQL> STARTUP PFILE=/DISK1/initU15.ora

SQL> CONNECT / AS SYSDBA

SQL> STARTUP PFILE=/DISK1/initU15.ora

Instance

SGA

Redo logbuffer

Data buffercache

Shared pool

Data dict.cache

Librarycache

PMONDBWRSMON LGWRCKPT ARCH

Page 143: 3_day_back_end

Tulsi ocp

Uses of Parameters

Size the System Global Area (SGA).Set database and instance defaults.Set user or process limits.Set limits on database resources.Define various physical attributes of the database, such as the database block size.Specify control files, archived log files, the ALERT file, and trace file locations.

Page 144: 3_day_back_end

Tulsi ocp

Parameter File Example# Initialization Parameter File: initU15.ora

db_name = U15

control_files = (/DISK1/control01.con,

/DISK2/control02.con)

db_block_size = 8192

db_block_buffers = 2048

shared_pool_size = 52428800

log_buffer = 64K

processes = 50

db_files = 1024

log_files = 10

max_dump_file_size = 10240

background_dump_dest = (/home/disk3/user15/BDUMP)

user_dump_dest = (/home/disk3/user15/UDUMP)

core_dump_dest = (/home/disk3/user15/CDUMP)

rollback segments =

Page 145: 3_day_back_end

Tulsi ocp

STARTUP Command

STARTUP PFILE=/DISK1/initU15.oraSTARTUP PFILE=/DISK1/initU15.ora

Start up the instance and open the database:

Page 146: 3_day_back_end

Tulsi ocp

ALTER DATABASE Command

Change the state of the database from NOMOUNT to MOUNT:ALTER DATABASE database MOUNT;ALTER DATABASE database MOUNT;

• Open the database as a read-only database:

ALTER DATABASE database OPEN READ ONLY;ALTER DATABASE database OPEN READ ONLY;

Page 147: 3_day_back_end

Tulsi ocp

Opening a Database in Read-Only Mode

Any database can be opened as a read-only databaseA read-only database can be used to:– Execute queries– Execute disk sorts using locally managed

tablespaces– Take data files offline and online, not

tablespaces– Perform recovery of offline data files and

tablespaces

Page 148: 3_day_back_end

Tulsi ocp

A

x

x

x

x

T

x

x

o

o

I

x

x

x

o

Shutdown Mode

Allow new connections

Wait until current sessions end

Wait until current transactions end

Force a checkpoint and close files

N

x

o

o

o

Shutdown mode: Shutdown mode:

A AbortA Abort I ImmediateI Immediate

T TransactionalT Transactional N NormalN Normal

Shutdown Options

YESYES

NONOx

o

Page 149: 3_day_back_end

Tulsi ocp

ExampleExample

SGA

V$PARAMETERV$PARAMETERV$SGAV$SGAV$OPTIONV$OPTIONV$PROCESSV$PROCESSV$SESSION V$SESSION V$VERSIONV$VERSIONV$INSTANCEV$INSTANCE

Control fileV$THREADV$THREADV$CONTROLFILE V$CONTROLFILE V$DATABASEV$DATABASEV$DATAFILEV$DATAFILEV$DATAFILE_HEADER V$DATAFILE_HEADER V$LOGFILEV$LOGFILE

Page 150: 3_day_back_end

Tulsi ocp

Displaying Current Parameter Values

Use the command:

Query the V$PARAMETER dynamic performance view:

SHOW PARAMETER controlSHOW PARAMETER control

SELECT name FROM v$parameter

WHERE name LIKE ‘%control%’;

SELECT name FROM v$parameter

WHERE name LIKE ‘%control%’;

Page 151: 3_day_back_end

Tulsi ocp

Dynamic Initialization Parameters

ALTER SESSION SET SQL_TRACE=true;ALTER SESSION SET SQL_TRACE=true;

ALTER SYSTEM SET TIMED_STATISTICS=true;ALTER SYSTEM SET TIMED_STATISTICS=true;

ALTER SYSTEM SET SORT_AREA_SIZE=131072 DEFERRED;ALTER SYSTEM SET SORT_AREA_SIZE=131072 DEFERRED;

Some initialization parameters can be modified while an instance is running.

Page 152: 3_day_back_end

-by tulsi ocp

Creating a Database

Page 153: 3_day_back_end

Tulsi ocpDatabase

Control files

Data files

Redo logfiles

Passwordfile

Parameterfile

Tracefiles

ALERTfile

InstanceSGA

Shared pool

Userprocess

Serverprocess

PGA

OverviewOverview

Page 154: 3_day_back_end

Tulsi ocp

Creation Prerequisites

A privileged account authenticated in one of the following ways: – By the operating system – Using a password file

Memory to start the instanceSufficient disk space for the planned database

Page 155: 3_day_back_end

Tulsi ocp

Planning Database File Locations

Keep at least two active copies of a database control file on at least two different devices.Multiplex the redo log files and put group members on different disks.Separate data files whose data:– Will participate in disk resource contention

across different physical disk resources– Have different life spans– Have different administrative characteristics

Page 156: 3_day_back_end

Tulsi ocp

Oracle Software Locations

/oracle_base

/product

/admin/local

/release_number

/8.1.5

/bin/dbs/orainst/sqlplus...

On UNIXOn UNIX

\admin\db_name\admin\v815\oradata\db_name…

\bin\database

\oracle_base

\oracle_home

On Windows NTOn Windows NT

Page 157: 3_day_back_end

Tulsi ocp

Oracle Database Files

/u02/oradata/

db01/

system01.dbfcontrol01.ctlredo0101.rdo...

db02/system01.dbfcontrol01.ctlredo0101.rdo...

/u03/oradata/

db01/

db02/

tools01.dbfcontrol02.ctlredo0102.rdo...

users01.dbfcontrol02.ctlredo0102.rdo...

Page 158: 3_day_back_end

Tulsi ocp

Creating a Database

Created using the Database Configuration AssistantCreated manually using the CREATE DATABASE command

Page 159: 3_day_back_end

Tulsi ocp

Using the Database Configuration Assistant

Page 160: 3_day_back_end

Tulsi ocp

Pretuned Databases

Page 161: 3_day_back_end

Tulsi ocp

Predefined Sample Schemas

Page 162: 3_day_back_end

Tulsi ocp

Finishing Create Database

Page 163: 3_day_back_end

Tulsi ocp

Creating a Database Manually

1. Decide on a unique instance and database name and database character set.

2. Set the operating system variables.3. Prepare the parameter file.4. Create a password file (recommended).5. Start the instance.6. Create the database.7. Run scripts to generate the data dictionary

and accomplish postcreation steps.

Page 164: 3_day_back_end

Tulsi ocp

Operating System Environment

On Windows NT:Set the variable ORACLE_SID to use SQL*Plus.Create the service and the password file with ORADIM.

C:\> ORADIM -NEW -SID u16 -INTPWD password

-STARTMODE auto

-PFILE ORACLE_HOME\DATABASE\initU16.ora

C:\> ORADIM -NEW -SID u16 -INTPWD password

-STARTMODE auto

-PFILE ORACLE_HOME\DATABASE\initU16.ora

Page 165: 3_day_back_end

Tulsi ocp

Starting the InstanceStarting the Instance

1. Connect as SYSDBA.2. Start the instance in NOMOUNT stage.1. Connect as SYSDBA.2. Start the instance in NOMOUNT stage.SQL> STARTUP NOMOUNT PFILE=initU16.ora

ORACLE instance started.

SQL> STARTUP NOMOUNT PFILE=initU16.ora

ORACLE instance started.

Page 166: 3_day_back_end

Tulsi ocp

SPOOL creU16.log

STARTUP NOMOUNT PFILE=initU16.ora

CREATE DATABASE U16

MAXLOGFILES 5

MAXLOGMEMBERS 5

MAXDATAFILES 100

MAXLOGHISTORY 100

LOGFILE

GROUP 1 ('/DISK3/log1a.rdo',/DISK4/log1b.rdo’) SIZE 1 M,

GROUP 2 ('/DISK3/log2a.rdo',/DISK4/log2b.rdo’) SIZE 1 M

DATAFILE

'/DISK1/system01.dbf' size 50M autoextend on

CHARACTER SET WE8ISO8859P1;

SPOOL creU16.log

STARTUP NOMOUNT PFILE=initU16.ora

CREATE DATABASE U16

MAXLOGFILES 5

MAXLOGMEMBERS 5

MAXDATAFILES 100

MAXLOGHISTORY 100

LOGFILE

GROUP 1 ('/DISK3/log1a.rdo',/DISK4/log1b.rdo’) SIZE 1 M,

GROUP 2 ('/DISK3/log2a.rdo',/DISK4/log2b.rdo’) SIZE 1 M

DATAFILE

'/DISK1/system01.dbf' size 50M autoextend on

CHARACTER SET WE8ISO8859P1;

Creating the Database

Page 167: 3_day_back_end

Tulsi ocp

After the Database Is Created

The database contains:Data files that make up the SYSTEM tablespaceControl files and redo log filesThe user SYS with the password CHANGE_ON_INSTALL

The user SYSTEM with the password MANAGER

The rollback segment SYSTEMInternal tables (but no data dictionary views)

Page 168: 3_day_back_end

-by tulsi ocp

Creating Data Dictionary Views and Standard Packages

Page 169: 3_day_back_end

Tulsi ocp

Overview

Other objects created with the database:

Data dictionary– Base tables– Views

Dynamic performance tablesBuilt-in PL/SQL packages

Database event triggers fire automatically during a specific

event, such as a server error.

Otherdatabase

files

Database

Systemtablespace

Page 170: 3_day_back_end

Tulsi ocp

Data Dictionary

Central to every Oracle databaseDescribes the database and its objectsContains read-only tables and viewsUpdated by SQL commands:– DDL– Some DML

Owned by the user SYSStored in the SYSTEM

Otherdatabase

files

Database

Systemtablespace

Page 171: 3_day_back_end

Tulsi ocp

Data Dictionary Contents

The data dictionary provides information about:Logical and physical database structureDefinitions and space allocations of objectsIntegrity constraintsUsersRolesPrivilegesAuditing

Page 172: 3_day_back_end

Tulsi ocp

Base Tables and Data Dictionary Views

The data dictionary contains two parts:Base tables:– Normalized– Created with database using sql.bsq script

Data dictionary views:– Used to simplify the base table information– Accessed through public synonyms– Created with the catalog.sql script

Page 173: 3_day_back_end

Tulsi ocp

How the Data Dictionary Is Used

The data dictionary has three primary uses: The Oracle server uses it to find information about:– Users– Schema objects– Storage structures

The Oracle server modifies it when a DDL statement is executed.Users and DBAs can use it as a read-only reference for information about the database.

Page 174: 3_day_back_end

Tulsi ocp

Data Dictionary View Categories

DBA_xxx

USER_xxx

ALL_xxx

Objects owned by the current user

Objects accessible by the current user

All of the objects in the database

Page 175: 3_day_back_end

Tulsi ocp

Data Dictionary ExamplesGeneral overview– DICTIONARY

Schema objects– DBA_TABLES– DBA_OBJECTS

Space allocation– DBA_ SEGMENTS– DBA_FREE_SPACE

Database structure– DBA_DATA_FILES– DBA_ROLLBACK_SEGS– DBA_TABLESPACES

– DICT_COLUMNS

– DBA_TAB_COLUMNS– DBA_CONSTRAINTS

– DBA_EXTENTS

Page 176: 3_day_back_end

Tulsi ocp

Dynamic Performance Tables

“Virtual” tablesInformation accessed from:– Memory– Control file

Synonyms begin with V$ DBA uses to monitor and tune the databaseListed in V$FIXED_TABLEExample: V$DATAFILE for data file information

Page 177: 3_day_back_end

Tulsi ocp

Stored Program Units

PL/SQL– Oracle’s procedural language extension to

SQL– Stored in the data dictionary

Java– Stored in the data dictionary– To execute, publish its call specification

External procedures– Written in C– Stored in a shared library– To execute, publish the call specification

Page 178: 3_day_back_end

Tulsi ocp

Stored PL/SQL Program Units

A procedure, function, package, or triggerCan accept and return parametersFunctions can be called from SQLA set of SQL and PL/SQL commandsStored in the data dictionaryLoaded into the shared pool

Page 179: 3_day_back_end

Tulsi ocp

Stored PL/SQL Packages

A package:Groups logically related PL/SQL types, items, and subprogramsHas two parts:– A specification describes its components– A body implements the logic

Example: DBMS_SESSION.SET_ROLE– Package: DBMS_SESSION– Procedure: SET_ROLE

Page 180: 3_day_back_end

Tulsi ocp

Script Purpose

catalog.sql Creates commonly used data dictionaryviews and synonyms

catproc.sql Runs scripts required for server-sidePL/SQL

Creating Data Dictionary Views

Page 181: 3_day_back_end

-by tulsi ocp

Maintaining the Control File

Page 182: 3_day_back_end

Tulsi ocp

The Use of the Control File

Small, binary fileRequired:

– At mount– To operate

Linked to a single databaseShould be multiplexedLoss may require recovery

Control files

Data files

Redo logfiles

Database

Page 183: 3_day_back_end

Tulsi ocp

Control File Contents

Database name and identifierDatabase creation dateData file and redo log locationsTablespace namesLog historyBackup information Current log sequence numberCheckpoint information

Page 184: 3_day_back_end

Tulsi ocp

Multiplexing the Control File

control_filescontrol_files=(/DISK1/control01.con,/DISK2/control02.con)=(/DISK1/control01.con,/DISK2/control02.con)

Disk 1Disk 1

control01.con

Disk 2Disk 2

control02.con

Page 185: 3_day_back_end

-by tulsi ocp

Maintaining Redo Log Files

Page 186: 3_day_back_end

Tulsi ocp

Using Redo Log Files

Control files

Data files

Redo logfiles

Database

Page 187: 3_day_back_end

Tulsi ocp

Redo Log Groups and Members

Group 2Group 2 Group 3Group 3Group 1Group 1

Member

Disk 1Disk 1

Disk 2Disk 2Member

Member Member

MemberMember

Page 188: 3_day_back_end

Tulsi ocp

Oracle Architecture

InstanceSGA

Control files

Data files

Redo logfiles

Database

Archived log files

Parameterfile

Passwordfile

CKPTDBWR

Redo logbuffer

Data buffercache

LGWR ARCH

Page 189: 3_day_back_end

Tulsi ocp

Without Archiving

BackupBackup Disk failureDisk failure

101

t1t1 t2t2

Data files Control files

50 51 100

Page 190: 3_day_back_end

Tulsi ocp

With Archiving

Disk failureDisk failure

101

t2t2

100

t1t1

50 51

BackupBackup

Data files Control files

Archived redo logsArchived redo logs

50

99

Page 191: 3_day_back_end

Tulsi ocp

SQL command:

V$DATABASE:– NAME– LOG_MODE

V$INSTANCE:ARCHIVER

Obtaining Information About Archiving

ARCHIVE LOG LIST;ARCHIVE LOG LIST;

Page 192: 3_day_back_end

Tulsi ocp

Obtaining Information About Groups

V$THREAD:GROUPSCURRENT_GROUP#SEQUENCE#

Page 193: 3_day_back_end

Tulsi ocp

Obtaining Information AboutGroups and Members

V$LOG:GROUP#MEMBERSSTATUSSEQUENCE#BYTES

Page 194: 3_day_back_end

Tulsi ocp

Obtaining Information AboutGroups and Members

V$LOGFILE:GROUP#STATUSMEMBER

Page 195: 3_day_back_end

Tulsi ocp

Force log switches with the command:

Control checkpoints with the initialization parameters:– LOG_CHECKPOINT_INTERVAL– LOG_CHECKPOINT_TIMEOUT– FAST_START_IO_TARGET

Log Switches and Checkpoints

ALTER SYSTEM SWITCH LOGFILE;ALTER SYSTEM SWITCH LOGFILE;

Page 196: 3_day_back_end

Tulsi ocp

Adding Online Redo Log Groups

Group 1Group 1 Group 2Group 2 Group 3Group 3

ALTER DATABASE ADD LOGFILE

(‘/DISK3/log3a.rdo’,

‘/DISK4/log3b.rdo’) size 1M;

ALTER DATABASE ADD LOGFILE

(‘/DISK3/log3a.rdo’,

‘/DISK4/log3b.rdo’) size 1M;

log3b.rdolog1b.rdo log2b.rdo

Page 197: 3_day_back_end

Tulsi ocp

Adding Online Redo Log Members

log1b.rdo

ALTER DATABASE ADD LOGFILE MEMBER

‘/DISK4/log1b.rdo’ TO GROUP 1,

‘/DISK4/log2b.rdo’ TO GROUP 2;

ALTER DATABASE ADD LOGFILE MEMBER

‘/DISK4/log1b.rdo’ TO GROUP 1,

‘/DISK4/log2b.rdo’ TO GROUP 2;

Group 1Group 1 Group 2Group 2

log1a.rdo log2b.rdolog2a.rdo

Page 198: 3_day_back_end

Tulsi ocp

How to Relocate or RenameOnline Redo Log Files

How to Relocate or RenameOnline Redo Log Files

1. Copy the online redo log files to the new location.

2. Execute the ALTER DATABASE RENAME FILE command.

Page 199: 3_day_back_end

Tulsi ocp

Dropping Online Redo Log Groups

Group 1Group 1 Group 2Group 2 Group 3Group 3

ALTER DATABASE DROP LOGFILE GROUP 3;ALTER DATABASE DROP LOGFILE GROUP 3;

log1b.rdo log1b.rdolog3a.rdo

log3b.rdolog1b.rdo log2b.rdo

Page 200: 3_day_back_end

Tulsi ocp

Dropping Online Redo Log Members

Group 2Group 2

ALTER DATABASE DROP LOGFILE MEMBER

‘/DISK4/log2b.dbf’;

ALTER DATABASE DROP LOGFILE MEMBER

‘/DISK4/log2b.dbf’;

Group 1Group 1

log1b.rdolog2b.rdo

log1b.rdolog1b.rdo

Page 201: 3_day_back_end

Tulsi ocp

Clearing Online Redo Log Files

ALTER DATABASE CLEAR LOGFILE

‘/DISK3/log2a.rdo’;

ALTER DATABASE CLEAR LOGFILE

‘/DISK3/log2a.rdo’;

Example:Example:

Page 202: 3_day_back_end

Tulsi ocp

Online Redo Log Configuration

Group 1Group 1 Group 2Group 2 Group 3Group 3

Member

Member

Disk 3Disk 3Disk 2Disk 2Disk 1Disk 1

MemberMember

Member

Page 203: 3_day_back_end

Tulsi ocp

Possible LGWR Errors

One member of a group of two or more is not available.All members of the next group are not available.All members of the current group are not available.

Page 204: 3_day_back_end

-by tulsi ocp

Managing Tablespaces and Data Files

Page 205: 3_day_back_end

Tulsi ocp

OverviewOverview

Database

Controlfiles

Redo logfilesData files

Page 206: 3_day_back_end

Tulsi ocp

Database

Logical Physical

Tablespace Data file

OS blockOracleblock

Segment

Extent

Database Storage Hierarchy

Page 207: 3_day_back_end

Tulsi ocp

SYSTEM and Non-SYSTEM Tablespaces

SYSTEM tablespace:– Created with the database– Contains the data dictionary– Contains the SYSTEM rollback segment

Non-SYSTEM tablespaces:– Separate segments– Ease space administration– Control amount of space allocated to a user

Page 208: 3_day_back_end

Tulsi ocp

Creating Tablespaces

CREATE TABLESPACE app_data

DATAFILE '/DISK4/app_data_01.dbf'

SIZE 100M,

'/DISK5/app data_ 02.dbf'

SIZE 100M

MINIMUM EXTENT 500K

DEFAULT STORAGE ( INITIAL 500K

NEXT 500K

MAXEXTENTS 500

PCTINCREASE 0 );

CREATE TABLESPACE app_data

DATAFILE '/DISK4/app_data_01.dbf'

SIZE 100M,

'/DISK5/app data_ 02.dbf'

SIZE 100M

MINIMUM EXTENT 500K

DEFAULT STORAGE ( INITIAL 500K

NEXT 500K

MAXEXTENTS 500

PCTINCREASE 0 );

Page 209: 3_day_back_end

Tulsi ocp

Space Management in Tablespaces

Dictionary-managed tablespaces:– Default technique– Free extents recorded in data dictionary tables

Locally managed tablespaces:– Free extents recorded in bitmap– Each bit corresponds to a block or group of

blocks– Bit value indicates free or used

Page 210: 3_day_back_end

Tulsi ocp

Locally Managed Tablespaces

Reduced recursive space managementReduced contention on data dictionary

tablesNo rollback generatedNo coalescing required

CREATE TABLESPACE user_data

DATAFILE '/DISK2/user_data_01.dbf'

SIZE 500M

EXTENT MANAGEMENT LOCAL

UNIFORM SIZE 10M;

CREATE TABLESPACE user_data

DATAFILE '/DISK2/user_data_01.dbf'

SIZE 500M

EXTENT MANAGEMENT LOCAL

UNIFORM SIZE 10M;

Page 211: 3_day_back_end

Tulsi ocp

Temporary Tablespace

Used for sort operationsCannot contain any permanent objectsLocally managed extents recommendedUNIFORM SIZE = SORT_AREA_SIZE * nCREATE TEMPORARY TABLESPACE temp

TEMPFILE '/DISK2/temp_01.dbf'

SIZE 500M

EXTENT MANAGEMENT LOCAL

UNIFORM SIZE 10M;

CREATE TEMPORARY TABLESPACE temp

TEMPFILE '/DISK2/temp_01.dbf'

SIZE 500M

EXTENT MANAGEMENT LOCAL

UNIFORM SIZE 10M;

Page 212: 3_day_back_end

Tulsi ocp

Changing the Storage Settings

ALTER TABLESPACE app_data

MINIMUM EXTENT 2M;

ALTER TABLESPACE app_data

MINIMUM EXTENT 2M;

ALTER TABLESPACE app_data

DEFAULT STORAGE (

INITIAL 2M

NEXT 2M

MAXEXTENTS 999 );

ALTER TABLESPACE app_data

DEFAULT STORAGE (

INITIAL 2M

NEXT 2M

MAXEXTENTS 999 );

Page 213: 3_day_back_end

Tulsi ocp

Offline Status

Offline tablespace not available for data accessSome tablespaces must be online:– SYSTEM – Tablespaces with active rollback segments

To take a tablespace offline:

To bring a tablespace online:

ALTER TABLESPACE app_data OFFLINE;ALTER TABLESPACE app_data OFFLINE;

ALTER TABLESPACE app_data ONLINE;ALTER TABLESPACE app_data ONLINE;

Page 214: 3_day_back_end

Tulsi ocp

Read-Only Tablespaces

ALTER TABLESPACE app_data READ ONLY; ALTER TABLESPACE app_data READ ONLY;

Tablespace only available for read operationsObjects can be dropped from tablespaceTo create a read-only tablespace on a WORM drive:– ALTER TABLESPACE…READ ONLY;– Move the data file to the WORM drive– ALTER TABLESPACE…RENAME

DATAFILE…;

Page 215: 3_day_back_end

Tulsi ocp

Making a Tablespace Read-Only

The tablespace must be online.In releases prior to Oracle8i, no active transactions are allowed.Oracle8i onwards allows current transactions to complete.The tablespace must not contain active rollback segments.The tablespace must not currently be involved in an online backup.

Page 216: 3_day_back_end

Tulsi ocp

Dropping Tablespaces

DROP TABLESPACE app_data INCLUDING CONTENTS;DROP TABLESPACE app_data INCLUDING CONTENTS;

Tablespace removed from data dictionaryOptionally, contents removed from data dictionaryOS files not deleted

Page 217: 3_day_back_end

Tulsi ocp

Resizing a Tablespace

Change the size of a data file:– Automatically– Manually

Add a data fileTablespaceTablespace APP_DATAAPP_DATA

100M

app_data_02.dbf100M

app_data_01.dbf100M

app_data_03.dbf 200M

Page 218: 3_day_back_end

Tulsi ocp

Enabling Automatic Extension of Data Files

ALTER TABLESPACE app_data

ADD DATAFILE '/DISK6/app_data_04.dbf'

SIZE 200M

AUTOEXTEND ON

NEXT 10M

MAXSIZE 500M;

ALTER TABLESPACE app_data

ADD DATAFILE '/DISK6/app_data_04.dbf'

SIZE 200M

AUTOEXTEND ON

NEXT 10M

MAXSIZE 500M;

TablespaceTablespace APP_DATAAPP_DATA

app_data_02.dbf100M

app_data_01.dbf100M

app_data_04.dbf 200M

app_data_03.dbf200M

Page 219: 3_day_back_end

Tulsi ocp

ALTER DATABASE

DATAFILE

'/DISK5/app_data_02.dbf'

RESIZE 200M;

ALTER DATABASE

DATAFILE

'/DISK5/app_data_02.dbf'

RESIZE 200M;

TablespaceTablespace APP_DATAAPP_DATA

100M

app_data_02.dbf100M

app_data_01.dbf100M

app_data_04.dbf 200M

app_data_03.dbf200M

Changing the Size of Data Files Manually

Page 220: 3_day_back_end

Tulsi ocp

Adding Data Files to a Tablespace

ALTER TABLESPACE app_data

ADD DATAFILE '/DISK5/app_data_03.dbf'

SIZE 200M;

ALTER TABLESPACE app_data

ADD DATAFILE '/DISK5/app_data_03.dbf'

SIZE 200M;

TablespaceTablespace APP_DATAAPP_DATA

app_data_02.dbf100M

app_data_01.dbf100M

app_data_03.dbf 200M

Page 221: 3_day_back_end

Tulsi ocp

Moving Data Files:ALTER TABLESPACE

The tablespace must be offline.The target data files must exist.

ALTER TABLESPACE app_data

RENAME

DATAFILE '/DISK4/app_data_01.dbf'

TO '/DISK5/app_data_01.dbf';

ALTER TABLESPACE app_data

RENAME

DATAFILE '/DISK4/app_data_01.dbf'

TO '/DISK5/app_data_01.dbf';

Page 222: 3_day_back_end

Tulsi ocp

Obtaining Tablespace Information

Tablespace information:– DBA_TABLESPACES– V$TABLESPACE

Data file information:– DBA_DATA_FILES– V$DATAFILE

Tempfile information:– DBA_TEMP_FILES– V$TEMPFILE

Page 223: 3_day_back_end

-by tulsi ocp

Storage Structure and Relationships

Page 224: 3_day_back_end

Tulsi ocp

Database

Logical Physical

Tablespace Data file

OS blockOracleblock

Segment

Extent

OverviewOverview

Page 225: 3_day_back_end

Tulsi ocp

Types of Segments

TableTable

ClusterCluster

Table Table partitionpartition

IndexIndex

Page 226: 3_day_back_end

Tulsi ocp

Types of Segments

IndexIndex--organizedorganizedtabletable Index Index

partitionpartition

RollbackRollbacksegmentsegment TemporaryTemporary

segmentsegment

Page 227: 3_day_back_end

Tulsi ocp

Types of Segments

LOB index LOB index LOBLOBsegmentsegment

BootstrapBootstrapsegmentsegment

Nested tableNested table

Page 228: 3_day_back_end

Tulsi ocp

Storage Clause Precedence

Oracle default

Tablespace

Segment

Page 229: 3_day_back_end

Tulsi ocp

Extent Allocation and Deallocation

Allocated when the segment is:– Created – Extended– Altered

Deallocated when the segment is:– Dropped– Altered– Truncated– Automatically resized (rollback segments only)

Page 230: 3_day_back_end

Tulsi ocp

Used and Free Extents

Data fileData file

Free extentFree extentUsed extentUsed extentFile headerFile header

Page 231: 3_day_back_end

Tulsi ocp

Database Block: Review

Minimum unit of I/OConsists of one or more OS blocksSet by DB_BLOCK_SIZESet at database creation

Page 232: 3_day_back_end

Tulsi ocp

Database Block Contents

HeaderHeader

Free spaceFree space

DataData

Page 233: 3_day_back_end

Tulsi ocp

Block Space Utilization Parameters

INITRANSINITRANS

MAXTRANSMAXTRANS

PCTFREEPCTFREE

PCTUSEDPCTUSED

Page 234: 3_day_back_end

Tulsi ocp

Block Space Usage

InsertsInserts

InsertsInserts

InsertsInserts

InsertsInserts

1 2

3 4

PCTFREE=20PCTFREE=20 PCTUSED=40PCTUSED=40

80%80%

80%80%

40%40%

Page 235: 3_day_back_end

Tulsi ocp

Data Dictionary Views

Tablespaces

DBA_TABLESPACES

Segments

DBA_SEGMENTS

Data files

DBA_DATA_FILES

Free extents

DBA_FREE_SPACE

Used extents

DBA_EXTENTS

Page 236: 3_day_back_end

Tulsi ocp

Querying DBA_SEGMENTS

General information– OWNER– SEGMENT_NAME – SEGMENT_TYPE – TABLESPACE_NAME

Size– EXTENTS– BLOCKS– BYTES

Storage settings– INITIAL_EXTENT– NEXT_EXTENT – MIN_EXTENTS – MAX_EXTENTS – PCT_INCREASE

Other information– Location– Tuning

Page 237: 3_day_back_end

Tulsi ocp

Querying DBA_EXTENTS

Identification– OWNER– SEGMENT_NAME– EXTENT_ID

Size– BLOCKS– BYTES

Location– TABLESPACE_NAME– RELATIVE_FNO– FILE_ID– BLOCK_ID

Page 238: 3_day_back_end

Tulsi ocp

Querying DBA_FREE_SPACE

Location– TABLESPACE_NAME – RELATIVE_FNO – FILE_ID – BLOCK_ID

Size– BYTES– BLOCKS

Page 239: 3_day_back_end

-by tulsi ocp

Managing Rollback Segments

Page 240: 3_day_back_end

Tulsi ocp

Undo/ Rollback Segment

Update transactionUpdate transaction

Old imageOld image

New New imageimage

Rollback segmentRollback segment

TableTable

Page 241: 3_day_back_end

Tulsi ocp

Undo/Rollback Segments: Purpose

Transaction rollbackTransaction rollback

Transaction Transaction recoveryrecovery

Rollback segmentRollback segment Read consistencyRead consistency

Page 242: 3_day_back_end

Tulsi ocp

Read Consistency

Image at start of statementImage at start of statement

New imageNew image

TableTableSELECT * SELECT * FROM tableFROM table

Page 243: 3_day_back_end

Tulsi ocp

Types of Rollback Segments

SYSTEM: Used for objects in the SYSTEM tablespaceNon-SYSTEM: Used for objects in other tablespacesautomode: requires undo tablespacemanual mode:– Private: Acquired by a single instance– Public: Acquired by any instance

Deferred: Used when tablespaces are taken offline with the immediate option

Page 244: 3_day_back_end

Tulsi ocp

AUTOMATIC UNDO MANAGEMENT

Configure two parameters in the initialization file– Undo_management (auto/manual)– Undo_tablespace (undotbs)

Create at least one undo tablespace

Page 245: 3_day_back_end

Tulsi ocp

Transactions and Rollback Segments

Transaction 1Transaction 1

Active extentActive extent Inactive extentInactive extent

4 3

1 2

Transaction 2Transaction 2

Page 246: 3_day_back_end

Tulsi ocp

Growth of Rollback Segments

Active extentActive extent

Inactive extentInactive extent

1 2

4 3

1 2

3

4

5

New extentNew extent

Page 247: 3_day_back_end

Tulsi ocp

Shrinkage of Rollback Segments

Active extentActive extent

Inactive extentInactive extent

1 2

6 3

1

2

34

5

6

OPTIMALOPTIMAL

Page 248: 3_day_back_end

-by tulsi ocp

Managing Tables

Page 249: 3_day_back_end

Tulsi ocp

Storing User Data

RegularRegulartabletable

ClusterCluster

PartitionedPartitionedtabletable

IndexIndex--organizedorganizedtabletable

Page 250: 3_day_back_end

Tulsi ocp

Structure of a Row

Database blockDatabase block

Row headerRow headerColumn lengthColumn length

Column valueColumn value

Page 251: 3_day_back_end

Tulsi ocp

Oracle Data Types

CHAR(N), NCHAR(N)CHAR(N), NCHAR(N)VARCHAR2(N),VARCHAR2(N),NVARCHAR2(N)NVARCHAR2(N)NUMBER(P,S)NUMBER(P,S)DATEDATERAW(N)RAW(N)BLOB, CLOB,BLOB, CLOB,NCLOB, BFILENCLOB, BFILELONG, LONG RAWLONG, LONG RAWROWID, UROWIDROWID, UROWID

VARRAYVARRAY

TABLETABLE

REFREF

Data type

Built-inUser-defined

Scalar RelationshipCollection

Page 252: 3_day_back_end

Tulsi ocp

Data Types for Storing Large Objects

LONG, LONG RAW

Single column per table

Up to 2 gigabytes

SELECT returns data

Data stored in-line

No object type support

Sequential access to chunks

LOB

Multiple columns per table

Up to 4 gigabytes

SELECT returns locator

Data stored in-line or

Supports object types

Random access to chunks

out-of-line

Page 253: 3_day_back_end

Tulsi ocp

ROWID Data Type

OOOOOO BBBBBBFFF RRR

Data object number

Relative file number

Row numberBlock number

ROWID FormatROWID Format

Unique identifier for a row Used to locate a row

Page 254: 3_day_back_end

Tulsi ocp

Restricted ROWIDRestricted ROWID

Can identify rows within a segmentNeeds less spaceCan identify rows within a segmentNeeds less space

BBBBBBBB FFFFRRRR

Block number Row number File number

. .

Page 255: 3_day_back_end

Tulsi ocp

Collections

Collections are objects that contain objects.VARRAYs are ordered sets of elements containing a count and a limit.Nested tables are tables with a column or variable of the TABLE data type.

VARRAYVARRAY NestedNestedtabletable

Page 256: 3_day_back_end

Tulsi ocp

Creating a TableCreating a Table

CREATE TABLE employee(

id NUMBER(7),

last_name VARCHAR2(25),

dept_id NUMBER(7))

PCTFREE 20 PCTUSED 50

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE data;

CREATE TABLE employee(

id NUMBER(7),

last_name VARCHAR2(25),

dept_id NUMBER(7))

PCTFREE 20 PCTUSED 50

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE data;

Page 257: 3_day_back_end

Tulsi ocp

Row Migration and Chaining

Before updateBefore update After updateAfter update

Pointer

Page 258: 3_day_back_end

-by tulsi ocp

Managing Indexes

Page 259: 3_day_back_end

Tulsi ocp

Classification of Indexes

Logical– Single column or concatenated– Unique or nonunique– Function-based

Physical– Partitioned or nonpartitioned– B-tree– Normal or reverse key– Bitmap

Page 260: 3_day_back_end

Tulsi ocp

B-Tree Index

Index entry headerKey column lengthKey column valueROWID

Root

Branch

Leaf

Index entry

Page 261: 3_day_back_end

Tulsi ocp

KEY ROWID

ID (BLOCK# ROW# FILE#)----- -------------------1257 0000000F.0002.00012877 0000000F.0006.00014567 0000000F.0004.00016657 0000000F.0003.00018967 0000000F.0005.00019637 0000000F.0001.00019947 0000000F.0000.0001... ...... ...

Index on EMPLOYEE (ID)Index on EMPLOYEE (ID) EMPLOYEE tableEMPLOYEE table

ID FIRST_NAME JOB----- ---------- --------7499 ALLEN SALESMAN7369 SMITH CLERK7521 WARD SALESMAN7566 JONES MANAGER7654 MARTIN SALESMAN7698 BLAKE MANAGER7782 CLARK MANAGER… ... ... ...... ... ... ...

Reverse Key Index

Page 262: 3_day_back_end

Tulsi ocp

Dramatically improves query performance

Queries using expressions can use the index

Dramatically improves query performance

Queries using expressions can use the index

Creating Function-Based Indexes

CREATE INDEX summit.item_quantity_to_deliver_idx

ON summit.item(quantity - quantity_shipped);

CREATE INDEX summit.item_quantity_to_deliver_idx

ON summit.item(quantity - quantity_shipped);

SELECT ord_id, item_id

FROM ITEM

WHERE (quantity - quantity_shipped) > 0;

SELECT ord_id, item_id

FROM ITEM

WHERE (quantity - quantity_shipped) > 0;

Page 263: 3_day_back_end

Tulsi ocp

Bitmap Index

<Blue, 10.0.3, 12.8.3, 1000100100010010100>

<Green, 10.0.3, 12.8.3, 0001010000100100000>

<Red, 10.0.3, 12.8.3, 0100000011000001001>

<Yellow, 10.0.3, 12.8.3, 0010001000001000010>

keykeystartROWID

endROWID bitmap

Table

Index

Block 10

Block 11

Block 12

File 3

Page 264: 3_day_back_end

Tulsi ocp

Comparing B-Tree and Bitmap Indexes

B-tree

Suitable for high-cardinality columns

Updates on keys relativelyinexpensive

Inefficient for queries using OR predicates

Useful for OLTP

Bitmap

Suitable for low-cardinality columns

Updates to key columns veryexpensive

Efficient for queries using OR predicates

Useful for data warehousing

Page 265: 3_day_back_end

Tulsi ocp

Creating Normal B-Tree Indexes

CREATE INDEX summit.employee_last_name_idx

ON summit.employee(last_name)

PCTFREE 30

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE indx;

CREATE INDEX summit.employee_last_name_idx

ON summit.employee(last_name)

PCTFREE 30

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE indx;

Page 266: 3_day_back_end

Tulsi ocp

Creating Reverse Key Indexes

CREATE UNIQUE INDEX summit.orders_id_idx

ON summit.orders(id) REVERSE

PCTFREE 30

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE indx;

CREATE UNIQUE INDEX summit.orders_id_idx

ON summit.orders(id) REVERSE

PCTFREE 30

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE indx;

Page 267: 3_day_back_end

Tulsi ocp

Creating Bitmap Indexes

CREATE BITMAP INDEX orders_region_id_idx

ON summit.orders(region_id)

PCTFREE 30

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE indx;

CREATE BITMAP INDEX orders_region_id_idx

ON summit.orders(region_id)

PCTFREE 30

STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)

TABLESPACE indx;

Use the parameter CREATE_BITMAP_AREA_SIZE to specify the amount of memory allocated for bitmap creation.

Page 268: 3_day_back_end

Tulsi ocp

Rebuilding Indexes

ALTER INDEX summit.orders_region_id_idx REBUILD

TABLESPACE indx02;

ALTER INDEX summit.orders_region_id_idx REBUILD

TABLESPACE indx02;

Use the ALTER INDEX command to:Move an index to a different tablespaceImprove space utilization by removing deleted entriesChange a reverse key index to a normal B-tree index and vice versa

Page 269: 3_day_back_end

Tulsi ocp

Dropping Indexes

• Drop and re-create an index before bulk loads. • Drop indexes that are infrequently needed and build

them when necessary.• Drop and re-create invalid indexes.

DROP INDEX summit.deptartment_name_idx;DROP INDEX summit.deptartment_name_idx;

Page 270: 3_day_back_end

-by tulsi ocp

Using National Language Support

Using National Language Support

Page 271: 3_day_back_end

Tulsi ocp

NLS Features

Database

•• Language supportLanguage support•• Territory support Territory support •• Character set supportCharacter set support•• Linguistic sortingLinguistic sorting•• Message supportMessage support•• Date and time formatsDate and time formats•• Numeric formats Numeric formats

•• Monetary formatsMonetary formats

Page 272: 3_day_back_end

Tulsi ocp

Different Types of Encoding Schemes

Oracle supports different classes of character encoding schemes:

Single-byte character sets– 7-bit– 8-bit

Varying-width multibyte character setFixed-width multibyte character setUnicode (UTF8, AL24UTFFSS)

Page 273: 3_day_back_end

Tulsi ocp

Character Sets and National Character Sets of a Database

Database Character Sets

Defined at creation timeCannot be changed withoutre-creationStore data columns of typeCHAR, VARCHAR2, CLOB, LONGCan store varying-width character sets

National Character Sets

Defined at creation timeCannot be changed withoutre-creationStore data columns of type NCHAR, NVARCHAR2 and NCLOBCan store fixed-width and varying-width multibytecharacter sets

Page 274: 3_day_back_end

Tulsi ocp

Specifying Language-Dependent Behavior

Initialization parameter

Environment variable

ALTER SESSION command

Page 275: 3_day_back_end

Tulsi ocp

Specifying Language-Dependent Behavior for the Server

NLS_LANGUAGE specifies:- The language for messages- Day and month names- Symbols for A.D, B.C, A.M, P.M.- The default sorting mechanism

NLS_TERRITORY specifies:- Day and week numbering- Default date format, decimal character, group separator, and the default ISO and local currency symbols

Page 276: 3_day_back_end

Tulsi ocp

PARAMETER

NLS_LANGUAGENLS_DATE_LANGUAGENLS_SORT

NLS_TERRITORYNLS_CURRENCYNLS_ISO_CURRENCYNLS_DATE_FORMATNLS_NUMERIC_CHARACTERS

VALUES

AMERICANAMERICANBINARY

AMERICA$AMERICADD-MON-YY,.

Dependent Language and Territory Default Values

Page 277: 3_day_back_end

Tulsi ocp

Specifying Language-Dependent Behavior for the Session

Environment variable: NLS_LANG=<language>_<territory>.<charset>Additional environment variables:

NLS_DATE_FORMATNLS_DATE_LANGUAGE NLS_SORT NLS_NUMERIC_CHARACTERS NLS_CURRENCY NLS_ISO_CURRENCY NLS_CALENDAR

Page 278: 3_day_back_end

Tulsi ocp

Character Sets in Client-Server Architecture

CREATE DATABASE ...

CHARACTER SET <charset>

NATIONAL CHARACTER SET

<ncharset>

...

CREATE DATABASE ...

CHARACTER SET <charset>

NATIONAL CHARACTER SET

<ncharset>

...

NLS_LANG=<language>_<territory>.<charset>

NLS_NCHAR=<ncharset>

NLS_LANG=<language>_<territory>.<charset>

NLS_NCHAR=<ncharset>

Page 279: 3_day_back_end

Tulsi ocp

Specifying Language-Dependent Behavior for the Session

ALTER SESSION SET

NLS_DATE_FORMAT=‘DD.MM.YYYY’;

ALTER SESSION SET

NLS_DATE_FORMAT=‘DD.MM.YYYY’;

DBMS_SESSION.SET_NLS(‘NLS_DATE_FORMAT’,

’’’DD.MM.YYYY’’’) ;

DBMS_SESSION.SET_NLS(‘NLS_DATE_FORMAT’,

’’’DD.MM.YYYY’’’) ;

Page 280: 3_day_back_end

Tulsi ocp

Obtaining Information About Character Sets

NLS_DATABASE_PARAMETERS:NLS_DATABASE_PARAMETERS:• PARAMETER

(NLS_CHARACTERSET,NLS_NCHAR_CHARACTERSET)

• VALUE

Page 281: 3_day_back_end

-by tulsi ocp

Managing Privileges

Page 282: 3_day_back_end

Tulsi ocp

Managing Privileges

Two types of privileges: System: Enables users to perform particular actions in the databaseObject: Enables users to access and manipulate a specific object

Page 283: 3_day_back_end

Tulsi ocp

System Privileges

There are about 126 system privileges.The ANY keyword in the privileges signifies that users have the privilege in every schema.The GRANT command adds a privilege to a user or a group of users. The REVOKE command deletes the privileges.

Page 284: 3_day_back_end

Tulsi ocp

System Privileges: Examples

Category Examples

INDEX CREATE ANY INDEXALTER ANY INDEXDROP ANY INDEX

TABLE CREATE TABLECREATE ANY TABLEALTER ANY TABLEDROP ANY TABLESELECT ANY TABLEUPDATE ANY TABLEDELETE ANY TABLE

SESSION CREATE SESSIONALTER SESSIONRESTRICTED SESSION

TABLESPACE CREATE TABLESPACEALTER TABLESPACEDROP TABLESPACEUNLIMITED TABLESPACE

Page 285: 3_day_back_end

Tulsi ocp

Granting System Privileges

GRANT CREATE SESSION, CREATE TABLE TO managers;GRANT CREATE SESSION, CREATE TABLE TO managers;

GRANT CREATE SESSION TO scott

WITH ADMIN OPTION;

GRANT CREATE SESSION TO scott

WITH ADMIN OPTION;

Page 286: 3_day_back_end

Tulsi ocp

SYSDBA and SYSOPERPrivileges

Category Examples

SYSOPER STARTUPSHUTDOWNALTER DATABASE OPEN | MOUNTALTER DATABASE BACKUP CONTROLFILEALTER TABLESPACE BEGIN/END BACKUP RECOVER DATABASEALTER DATABASE ARCHIVELOGRESTRICTED SESSION

SYSDBA SYSOPER privileges WITH ADMIN OPTIONCREATE DATABASERECOVER DATABASE UNTIL

Page 287: 3_day_back_end

Tulsi ocp

Displaying System Privileges

DBA_SYS_PRIVS

• GRANTEE

• PRIVILEGE

• ADMIN OPTION

SESSION_PRIVS

• PRIVILEGE

Session LevelSession LevelDatabase LevelDatabase Level

Page 288: 3_day_back_end

Tulsi ocp

Revoking System Privileges

REVOKE CREATE TABLE FROM karen;REVOKE CREATE TABLE FROM karen;

REVOKE CREATE SESSION FROM scott;REVOKE CREATE SESSION FROM scott;

Page 289: 3_day_back_end

Tulsi ocp

KARENKAREN SCOTTSCOTT

Revoking System PrivilegesUsing WITH ADMIN OPTION

DBADBA

GRANTGRANT

REVOKEREVOKE

KARENKAREN SCOTTSCOTT

DBADBA

Page 290: 3_day_back_end

Tulsi ocp

RESULTRESULT

Revoking System PrivilegesUsing WITH ADMIN

OPTION

DBADBA KARENKAREN SCOTTSCOTT

Page 291: 3_day_back_end

Tulsi ocp

Object PrivilegesObject PrivilegesObject priv. Table View Sequence Procedure

ALTER √ √

DELETE √ √

EXECUTE √

INDEX √

INSERT √ √

REFERENCES √

SELECT √ √ √

UPDATE √ √

Page 292: 3_day_back_end

Tulsi ocp

Granting Object Privileges

GRANT EXECUTE ON dbms_pipe TO public;GRANT EXECUTE ON dbms_pipe TO public;

GRANT UPDATE(first_name, salary) ON

employee TO karen WITH GRANT OPTION;

GRANT UPDATE(first_name, salary) ON

employee TO karen WITH GRANT OPTION;

Page 293: 3_day_back_end

Tulsi ocp

DBA_TAB_PRIVS

Displaying Object Privileges

DBA_COL_PRIVS

GRANTEEOWNERTABLE_NAMECOLUMN_NAME GRANTORPRIVILEGEGRANTABLE

GRANTEEOWNERTABLE_NAMEGRANTORPRIVILEGEGRANTABLE

Page 294: 3_day_back_end

Tulsi ocp

Revoking Object Privileges

REVOKE execute ON dbms_pipe FROM scott;REVOKE execute ON dbms_pipe FROM scott;

Page 295: 3_day_back_end

Tulsi ocp

GRANTGRANT

REVOKEREVOKE

Revoking Object PrivilegesUsing WITH GRANT OPTION

SCOTTSCOTT

SCOTTSCOTT

USER 1USER 1

USER 1USER 1

USER 2USER 2

USER 2USER 2

Page 296: 3_day_back_end

Tulsi ocp

RESULTRESULT

Revoking Object PrivilegesUsing WITH GRANT

OPTION

SCOTTSCOTT USER 1USER 1 USER 2USER 2

Page 297: 3_day_back_end

Tulsi ocp

Query optimization tips

Page 298: 3_day_back_end

Tulsi ocp

Page 299: 3_day_back_end

Tulsi ocp

Page 300: 3_day_back_end

Tulsi ocp

Page 301: 3_day_back_end

Tulsi ocp

Page 302: 3_day_back_end

Tulsi ocp

Page 303: 3_day_back_end

Tulsi ocp

Oracle NET CONFIGURATION

ORACLE NET CONFIGURATION CLIENT SIDE

ORCLE NET CONFIGURATION SERVER SIDE

Page 304: 3_day_back_end

Tulsi ocp

ORACLE SERVER SIDE CONFIGURATION

SERVER SIDELISTENER PROCESS NEED TO EXIST

LISTENER PROCESS: LISTENS FOR INCOMING CONNECTIONS ON BEHALF OF A DATABASE OR A NUMBER OF DATASES

Page 305: 3_day_back_end

Tulsi ocp

LISTENER PROCESS

A listener process can listen for more than one database

Multiple listeners can listen on behalf of a single database to perform load balancing

The listener can listen for multiple protocolsThe default name of the listener in Oracle

Net is LISTENERThe name of the listener must be unique per

listener.ora file

Page 306: 3_day_back_end

Tulsi ocp

When oracle software is installed the listener.ora file is created for the starter database with the following default settings:

Listener name ListenerPort 1521Protocols tcp/ip and ipcSid name default instanceHostname default hostname

Page 307: 3_day_back_end

Tulsi ocp

LISTENER =(DESCRIPTION_LIST =(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = IPC)(KEY =

EXTPROC0)))(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST =

sprinttechnolog)(PORT = 1521)))

))

Page 308: 3_day_back_end

Tulsi ocp

Listener control utilityLSNRCTL

C:> lsnrctlPrompt syntaxLsnrctl> set current_listener listener2

Page 309: 3_day_back_end

Tulsi ocp

LSNRCTL commands

Use the following commands to control to the listener

Start [lis name]Stop [lis name]

Page 310: 3_day_back_end

Tulsi ocp

Client side configuration

Naming methods are used by a client application to resolve a connect identifier to a connect descriptor when attempting to connect to a database service

Page 311: 3_day_back_end

Tulsi ocp

First configure the naming method using the gui for oracle net configuration

Configure local naming methodFollow the wizard to complete configuration