2. Oracle basic administration http://www.ggola.com
1. Overview of Oracle basic architecture
Oracle Components
Oracle은 3개의 Components로 구성된다
- Processes (Background)
- Memory Structures
- Files (datafiles, redo log files, control files, parameter file)
Memory
Processes
Files
jkspark@hanafos.com -2- 장 경상
3. Oracle basic administration http://www.ggola.com
Memory Structures
Oracle Components의 첫번째 부분인 Memory Structures를 SGA라
하는데 Oracle의 memory구조를 칭하는 말이다.
(System Global Area)
- contain data and control information for one Oracle Database
System
- The SGA should always be in non-paged, non-swapped
memory
동시에 여러 사용자가 접속하면 이 메모리구조를 공유하기 때문에
‘Shared Global Area’라고도 한다.
SGA는 3개의 memory 구조를 가지고 있는데 ‘Shared Pool’과
‘Database Buffer Cache’, ‘Redo Log Buffer’로 이루어진다.
<= System Global Area =>
- Shared Pool - - Database Buffer Cache - - Redo log Buffer -
Libarary Cache
Data Dictionary Cache
Shared Pool : Library Cache, Data Dictionary Cache로 구성
1. Shared SQL Area (referred to as the library cache)
. SQL Statement 를 위치시키고 관련 information을 저장한다.
. SQL문은 여기서 4가지 단계를 거친다
parsing -> binding -> execution -> fetch(fetch는 select only)
. 동일한 SQL문의 실행요청을 대비 parsing된 information을 저
장한다.
2. The Data Dictionary Cache
. database의 dictionary를 저장한다.
(tables, views, column information, privileges ….)
Size 결정 parameter : Shared_Pool_Size = ?
jkspark@hanafos.com -3- 장 경상
4. Oracle basic administration http://www.ggola.com
The Database Buffer Cache : holds copies of data blocks read
from disk. (연결된 모든 users는 buffer cache를 공유한다)
1. A Cache miss : 처음으로 data를 read할 때 buffer에 없으므로
disk에서 read하여 buffer cache에 위치시킨다. (physical read)
2. A Cache hit : 원하는 data가 이미 buffer에 있으므로 memory 에
서 directly read 한다. (logical read)
Loaded Data BLOCK 빈 BLOCK
DISK
Cache miss (physical read)
Cache hit (logical read)
USER
여러 사용자가 동일한 data를 원하는 경우 cache hit를 통해 보
다 빠르게 return 할 수 있다.
그러한 read의 비율을 Hit ratio라 하는데 70~80%를 적정선으
로 본다. (현재 2006년 데이터베이스의 대용량화가 진행되면서
점점 더 이 비율은 의미가 없어지고 있다. 97%와 98%는 엄청난
성능의 차이를 보일 수도 있는 것이 현실이다. 즉, SGA size와
HIT Ratio를 종합적으로 판단해야지 hit ratio 비율만 보는 것은
그다지 옳은 판단기준이 아니다.)
Size 결정 parameter : DB_BLOCK_SIZE = ?K (SIZE)
DB_BLOCK_BUFFER = ? (개수)
그러므로 buffer 크기는 둘간의 곱으로 계산된다.
The Redo Log Buffer : a circular buffer containing about changes
made to the database. (Database에 반영될 변경된 내용을 저장)
1. Database에 반영될 모든 변경사항을 저장한다.
(즉, Disk의 Database File에 반영되어야 할 사항은 먼저 여기에
기록된다)
2. Unrecoverable keyword나 Create Table, Create Index 등으로 인
한 변경사항은 Redo Log Buffer를 bypass 한다.
(Oracle SQL*Loader를 사용할 때도 경우에 따라 bypass 한다)
Page 54 참조
Size 결정 parameter : LOG_BUFFER = ?
jkspark@hanafos.com -4- 장 경상
5. Oracle basic administration http://www.ggola.com
Background Processes
Oracle Components의 두번째 부분인 Processes를 Background
Processes라 하는데 default로 항상 필요한 Processes가 있고 경우
에 따라 띄우는 Processes가 있다.
Default Process
DBWR LGWR PMON SMON
CKPT RECO
System Global Area
ARCH LCKn
SNPn Dnnn Pnnn Snnn
Optional
Mandatory(Default) Processes
1. PMON : Process Monitor
(비정상 종료된 user process관련 transaction recovery)
. cleans up abnormally terminated connections
. rollback uncommitted transactions
. release locks held by a terminated process
. frees SGA resources allocated to the failed process
. restarts failed shared server and dispatcher processes(MTS시)
2. SMON : System Monitor
(비정상 종료된 instance 관련 recovery)
. performs automatic instance recovery
. reclaims space used by temporary segments no longer in use
. merges contiguous areas of free space in the
datafiles(automatic coalescing)
3. DBWR, LGWR : Database Writer, Log Writer
(file에 write하는 process)
. Datafile 에 변경된 data write – DBWR
. Online Redo Log File 에 변경된 data write - LGWR
위 4개의 Processes는 default processes로 initial parameter를
이용한 control이 불가능하며 이중 하나라도 fail될 경우
instance는 crash되고 restart해야 한다.
jkspark@hanafos.com -5- 장 경상
6. Oracle basic administration http://www.ggola.com
Optional Processes
1.RECO : Recover
. resolves failures involving a distributed transaction
(Oracle에 Distributed Option이 추가되는 경우)
2.LCKn : Lock
. performs interinstance locking in a parallel server system
(Oracle Parallel Server System으로 사용시 instance간 locking 관
리)
3.Pnnn : Parallel Query
. provides parallel query(, index) creation, parallel data loading,
parallel ‘create table as select’ capabilities
(Oracle에 Parallel Query Option이 추가되는 경우)
4.SNPn : Snapshot Refresh
. performs automatic refreshes of snapshots(read-only replicated
tables) (server job queues and replication queues와 관련)
(Oracle에 Procedural Option이 추가되는 경우)
(Replication 사용시 Replication Option 추가)
Other Processes (Parameter Setting에 dependent한 processes)
1. CKPT : Checkpoint
. ensure that all modified database buffers are written to the
database files.(LGWR을 대신해 all datafiles의 header
information update : LGWR역할 분담)
(Parameter에 CHECKPOINT_PROCESS = TRUE로 Setting이 되
어 있어야 하며 default는 FALSE다)
2. ARCH : Archiver
. copies online redo log files to a designated storage device once
LGWR switches to a new group
(Oracle Server가 ARCHIVELOG MODE로 운영중인 경우만 해
당)
3. Snnn : Shared Server Processes
. MTS(multi-thread-server)로 운영할 경우만 생성
(Parameter에 process수 설정
mts_servers=5
mts_max_servers=15)
4. Dnnn : Dispatcher Processes
. MTS(multi-thread-server)로 운영할 경우만 생성
(Parameter에 process수 설정
mts_dispatchers="tcp,7"
mts_max_dispatchers=15)
jkspark@hanafos.com -6- 장 경상
7. Oracle basic administration http://www.ggola.com
User Process 와 Server Process
1. User Process : Application Program이 run될 때
. runs client side application program
. SQL statement를 server process에 pass하고 그 result를 receive
한다.
2. Server Process : User Process에 대한 Server작업을 대행하는
Process로 User Process가 Client Side에 가깝다면 Server Process
는 User Process와 interface하는 Server Side의 Process라 할 수
있다.
. SGA내 shared memory를 사용하여 User Process로 부터 넘겨받
은 SQL을 처리한다.
. disk로 부터 database buffer cache로 place and read data
. SQL Statement Result를 User Process에 return 한다.
. SQL 처리 :
parse – syntax check, semantics check (object존재등 확인) ,
execution plan 설정
binding – parameter and value 처리 (값넘기기등)
execute – parsed SQL 실행
fetch – select인 경우 data passes
An Oracle Instance
is the combination of the SGA an the database background processes.
즉, Oracle Instance 라 함은 SGA 라는 memory 와 background processes 를 말한다.
따라서 Instance 가 시작되면 SGA memory 가 allocated 되고 background processes 가 start
된다.
Database 와 Instance 의 차이는 instance 가 시작되면 instance 에 의해서 database(datafiles)
가 mount 된다는 점이다.
(주의 : user process 와 server process 는 oracle instance 부분으로 define 되지 않는다)
jkspark@hanafos.com -7- 장 경상
8. Oracle basic administration http://www.ggola.com
Files
Oracle Database 는 3개의 File components를 갖는다.
Datafiles, Control files, Redo log files로 나누는데 Oracle Server가
open 되기 위한 각종 parameter 를 기록해 놓은 parameter file 과
기록을 남기는 alert file, trace file도 일종의 관련요소로 포함 시킬
수 있다.
Datafiles
System.dbf A_data.dbf
Roll_back.dbf A_index.dbf
xxxx.dbf xxxx.dbf
xxxx.dbf xxxx.dbf
xxxx.dbf xxxx.dbf
. contains all of the database data
(tables, indexes …등 data dictionary data and user data)
. data를 physical하게 기록하는 OS 상에 존재하는 File로 확장자는
일반적으로 .dbf를 사용한다.
Control Files
control01.ctl control02.ctl control03.ctl
. a small binary file that describes the structure of the database
. database files, log files 정보 및 database name 저장
. database내 table 정보, CKPT정보 등을 포함하여 Database 의
Start관련정보(mount, open, ascess), Recovery 필요정보를 저장한다
. DB 전반에 관한 내용을 physical하게 기록하는 OS 상에 존재하는
File로 확장자는 일반적으로 .ctl을 사용한다.
<동일한 control file들을 다른 Disk에 저장 하여 Disk Failure에 따
른 Oracle Start 및 Recovery 문제를 방지할 수 있다>
Control file을 정의하는 parameter : control_files = ?
jkspark@hanafos.com -8- 장 경상
9. Oracle basic administration http://www.ggola.com
Redo Log Files
== Multiplexed Redo Log Files ==
Group 1 Group 2 Group 3
Log_File_1A.log Log_File_2A.log Log_File_3A.log
(Member A) (Member A) (Member A)
Disk #1
Disk #2
Log_File_1B.log Log_File_2B.log Log_File_3B.log
(Member B) (Member B) (Member B)
. record all changes made to the database, and are used for data
recovery. (Recovery를 위한 모든 data 변경사항을 저장)
. 위 그림처럼 Multiplexed로 Redo Log File이 만들어지면 같은
Group내에 있는 모든 Log File(Members)들은 동시에 동일한
information을 update하며 Size도 같게 된다. (mirroring)
. 적어도 2개 이상의 Log Group을 가져야 한다. (member의 default
size는 500K 이다)
. 변경된 내용을 physical하게 기록하는 OS 상에 존재하는 File로 확
장자는 일반적으로 .log를 사용한다.
. log file 1개가 다차면 다음 log file로 이동하면서 순환된다.
(이를 switch라 한다)
<각각의 Log member들은 다른 Disk에 저장 함으로서 Disk Failure
에 따른 Oracle Recovery 문제를 방지할 수 있다>
Parameter File
. a text file containing a list of instance configuration parameters
. SGA memory sizing, control file location and name, back ground
processes information등 각종 Oracle Instance 시작시 setting될
value를 지정한다.
. physical하게 기록되는 OS 상에 존재하는 Text File로 확장자는 일
반적으로 .ora를 사용한다.
일반적으로 다음의 위치에 존재하며 init.ora 가 default다
/$ORACLE_HOME/dbs/init$SID.ora
jkspark@hanafos.com -9- 장 경상
10. Oracle basic administration http://www.ggola.com
Alert File
. Oracle Instance가 작동중인 동안 error가 발생하면 alert file에 그
message를 남기고 만일 server process나 background process에 의
해 detect되면 trace file로 dump된다.
. Oracle 이 스스로 기록을 남기는 OS 상에 존재하는 Text File로 확
장자는 (alert_).log
일반적으로 다음의 위치에 존재하며 parameter file에 지정된
background_dump_dest = /……./ parameter의 위치에 기록된
다.
Trace File
Server process 가 trace file . internal error 가 server process나 background process에 의해
을 만들게 하려면 : detect되면 관련된 trace file에 그 message를 남기게 된다.
. Server Process가 스스로 기록을 남기는 OS 상에 존재하는 Text
1. parameter : sql_trace=true File의 확장자는 (ora_) (process_no) .trc 이고 background process가
2. command : alter session set 생성시키는 trace file은 process 이름 no_.trc로 사용한다.
sql_trace = true
background process에 의해 감지되면 parameter file에 지정된
cf) background process 의 background_dump_dest = /……./ parameter의 위치에 기록된
trace file 은 관계없다. 다.
server process에 의해 감지되면 parameter file에 지정된
user_dump_dest = /……./ parameter의 위치에 기록된다.
Oracle Architecture Oracle Instance
PMON SMON DBWR LGWR
CKPT Pnnn
SGA
Dnnn Shared Pool Database Buffer Cache Redo Log Buffer RECO
Data Dictionary Area
Shared SQL Area
Snnn LCKn
ARCH SNPn
Parameter File
Server Process User Process
Control File Datafile1 Datafile3 LogfileA1 LogfileB1
Control File Datafile2 Datafile n LogfileA2 LogfileB2
Database (Files)
jkspark@hanafos.com - 10 - 장 경상
11. Oracle basic administration http://www.ggola.com
2. Starting up and Shutting down an Instance
Authentication Methods
OS상에서 DBA작업을 수행하는 최초의 일과 마지막 일은 Database
를 startup 하고 shutdown 하는 것이다.
일반적으로 Server Manager라는 utility를 사용하는데 이는 최초
Instance를 start하고 down시키기 위한 방법중의 하나다.
OS에 Login 후 Server Manger를 Invoke하는 방법은 OS의 인증에
따라 username/password 없이 하는 것과 직접
username/password를 입력하는 방법이 있다.
Connect internal
Sys user로만 instance를 start and down할 수 있지만 다른 user에
게도 그런 권한을 주려면 ‘sysdba’ or ‘sysrole’ 권한을 주어야 한다.
. sys user인 경우
[oracle]> svrmgrl
connect sys/password
Connected.
SVRMGR>
. 타 user인 경우
[oracle]> svrmgrl
connect user/password as sysdba ;
Connected.
SVRMGR>
OS 인증으로 user/password 없이 invoke하기 위해선 password
file 없이 parameter remote_login_passwordfile = NONE 으로 해야
하고 그렇지 않으면 ORAPWD utility를 이용하여 password file을
만들고 parameter remote_login_passwordfile = EXCLUSIVE 로 해
야 한다. 위 경우는 password file을 만들고 invoke하는 경우고 일반
적으로 parameter remote_login_passwordfile = NONE 으로 하여
OS 인증을 통해 invoke 한다.
. 일반적인 경우 (당연히 sys user로 login 된다)
[oracle]> svrmgrl
connect internal
Connected.
SVRMGR>
jkspark@hanafos.com - 11 - 장 경상
12. Oracle basic administration http://www.ggola.com
Startup Instance
Instance 를 start시키고 database를 open하는데는 3단계의 과정을
거친다.
nomount
. Database를 Creation 하는데 사용한다.
. Parameter file init$SID.ora 를 read하여 instance start.
mount
. started instance로 control file을 open.
(alter file structure and modify control file flags)
. control file과 disk status등을 확인하여 문제가 생기는 경우
starting recovery, DB관리를 위한 renaming log or datafiles 등을
위한 절차이다.
. mount option : (OPS Server 사용시)
- exclusive : 단지 현재의 한 instance만 access
- parallel : multiple instance사용 가능 (Begin OPS)
- shared : is a synonym for parallel ( = parallel)
- option ‘retry’ : 5초 간격으로 start되지 못한 OPS의 instance를
계속적으로 start
open
. makes the database available to all users.
. All files opened as described by the control file for this instance.
(open datafiles, log files..)
. open option :
- noresetlogs : 보통 Database open시 log file을 건들지 않는경우
에 해당
- resetlogs : Database open시 log file을 reset한다. 즉, log file을
초기화 시켜서 open하는 경우로 일부 data를 lost할 수 있다
SGA는 parameter file에 지정된 대로 redo log buffers,
database buffers가 생기고 Fixed size에 일반적인 database
and instance 정보를 저장한다.(no user data) 그리고 variable
size는 shared pool, sort areas등 user관련 data가 사용한다.
jkspark@hanafos.com - 12 - 장 경상
13. Oracle basic administration http://www.ggola.com
Database Starting
. startup : svrmgrl에서 startup 하면 nomount, mount, open의 과정
을 일시에 수행한다.
. startup nomount -> alter database mount -> alter database open
(한단계씩 실행하면서 적절한 작업을 수행하는 경우에 이용)
. startup option :
- force : 이미 start된 instance를 restart
- restricted : restricted privilege를 가진 user만 database에
connect 할 수 있도록 start.
- PFILE = filename : 특정 file을 parameter file로 start.
Instance가 start되면 Oracle Server는 read parameter file,
allocates the SGA, starts the background processes, opens
trace and alert files.
Connect internal후 Database를 startup하기전에 session에 대
한 제한을 줄 수 있다.
Alter system enable restricted session ;
Alter system disable restricted session ;
Shutdown Instance
Instance 를 down 시키는데는 3가지 option이 있다.
nomal (일반적인 경우로 생략되어 default로 적용된다)
. waits for all currently connected users to terminate their sessions
normally.
immediate
. terminates currently executing SQL statements and rolls back
uncommitted transactions.
abort (즉각적인 Shutdown Database)
. does not wait for calls to complete or users to disconnect.
(It dose not roll back uncommitted transactions.)
. does not close or dismount the database , but does shut down the
instance. (The next startup will require instance recovery
automatically)
Shutdown : close -> dismount -> down
jkspark@hanafos.com - 13 - 장 경상
14. Oracle basic administration http://www.ggola.com
3. Creating a Database
Create a Database Tasks
Database를 Creation하기 위해서는 다음과 같은 선행작업을 필요로
한다.
Managing and organizing a database system
. organizing the contents of the database through tablespaces
. database 구조를 디자인 to reduce contention and fragmentation
. OS environment 준비, parameter file setting, starting the instance
. Create Database SQL command를 수행
. redo log files and control files를 multiplexed로 생성하여
Database Safety를 높인다.
. 필요한 경우 password file생성
. database monitor를 위한 data dictionary tables and views 결정
Determining Tablespaces
Tablespace는 Oracle의 가장큰 저장단위
. 개개의 tablespace는 하나이상의 OS상의 Files로 구성된다.
. database가 running일 때 tablespaces can be brought online
. system영역인 system tablespace는 offline될 수 없지만 그 밖의
tablespace는 offline될 수 있다. (database가 running 이어도)
단, active rollback segments를 가지고 있는 tablespace는 offline 될
수 없다.
. object는 하나의 tablespace에만 존재할 수 있다. (Oracle8 이전)
. SYSTEM tablespace외에 일반적으로 TEMP(sorting),
RBS(rollback), TOOLS(Oracle Server Tools)를 기본적으로 필요로
하며 그 다음은 설계에 맞도록 Application Data and Index를 위한
tablespaces를 적절히 생성하게 된다.
Tablespace를 적절하게 구성하기 위해선 저장될 data의 특성
을 고려하여 다음의 사항을 주의한다.
– minimize fragmentation
– minimize disk contetion
– separate segments
jkspark@hanafos.com - 14 - 장 경상
15. Oracle basic administration http://www.ggola.com
Minimizing Fragmentation
. fragmentation의 propensity에 따라 비슷한 빈도를 나타내는
object를 적절한 tablespace에 따라 분류한다.
(extent의 alloc, dealloc의 빈도에 따라 fragmentation propensity가
결정된다)
. 일반적인 fragmentation은 segment의 종류에따라 달라지는데 요
약하면 다음과 같다.
Segment Type Fragmentation Characteristics
Data dictionary segments Zero fragmentation
Application data segments (data) A low fragmentation
Application interim segments (index) A moderate fragmentation
Rollback segments A moderate fragmentation
Temporary segments A high fragmentation
. Data dictionary는 일반적으로 고정된 정보를 가지므로 extent의
alloc, dealloc이 드물다.
. data의 경우 삭제가 많이 일어나지 않는다면 많지않은
fragmentation이 일어날 것이다.
. index의 경우 새로 만들거나 없어지는 경우가 생기므로 일정정도
의 alloc, dealloc이 일어날 것이다.
. rollback segments의 경우 alloc, dealloc이 비교적 빈번히 일어나겠
지만 순환적으로 사용하므로 심하지않은 fragmentation이 일어날
것이다.
. temporary segments의 경우 sorting작업이 빈번하므로 지속적인
fragmentation이 일어나겠지만 주로 재 사용을 하므로 큰 부담을
주지는 않을 것이다.
Minimizing Contention
. Performance 향상에 있어서 disk contention을 줄이는 것은 중요한
부분의 하나가 된다.
. 위에서 열거했듯이 각 segment별 성격이 다르므로 각각의
segment별 disk를 나누어서 생성하는 것이 가장 좋을 것이다.
. 물론 경우에 따라 Large segments가 필요하다면 Small segments
와 disk를 달리 사용하는 것이 좋을 것이고 data와 index는 대부분
동시에 변경을 가져오므로 필히 disk를 나누어 사용하는 것이 좋다.
. 단, 동시에 사용하는 관련있는 table과 index는 나누어야 겠지만
서로 관련성이 떨어지는 table과 index가 있다면 예를들어 A업무의
table이 #1 disk , index가 #2 disk라면 B업무는 #1 disk에 index를
#2 disk에 table로 나누는 것이 좋은 분류가 될 것이다. (중요한것은
업무성격별 분류가 된다)
jkspark@hanafos.com - 15 - 장 경상
16. Oracle basic administration http://www.ggola.com
Separating Segments
. 그렇다면 어떤 방식으로 segments를 나눌 것인가!
. different backup needs, access requirement, day-to-day uses, life
span
(1) Backup and Recovery관점에서
다른 종류의 application data들을 나누어두면 advantages가 있
다. 만일 read-only tablespaces를 가지고 있다면 backup이 훨씬
더 빨라질 것이다.
(2) Sizing관점에서
Data growth의 measure and forecast가 쉬워진다.
(3) Security
보안차원에서 user database privileges를 separating groups별
로 관리하기가 훨씬 쉬워진다.
(4) Cleanup
project별로 나누어져 있으면 archiving or cleanup하기가 훨씬
쉬워진다. (종료된 project관련 segment는 간단하게 삭제를 해도
다른 project에 영향을 주지 않을 것이다)
Storing Database Files
. 각종 database file은 어떻게 저장하는 것이 performance와 안정성
을 높일 수 있는가!
. 적어도 two different physical devices에 control file을 나눔으로써
control file의 media failure에 대비한다.
. multiplex the redo log files and put group members on different
disks (control file을 나누는 이유와 같다)
. disk를 striping해서 tablespace separating을 통한 data를 보관함
으로써 disk resource contention을 줄임으로 performance를 향상한
다.
jkspark@hanafos.com - 16 - 장 경상
17. Oracle basic administration http://www.ggola.com
Creating a Database
Creating an Oracle Database 준비를 위한 과정별로 살펴본다.
Process for Creating a Database
. Database를 생성하기 위한 기본 요소
- unique instance name, database name, block size, database
character set, maximum number of database files, and maximum
number of lock files
. copy and edit the parameter file (init.ora : Oracle은 기본적인
parameter file을 제공함으로 그것을 copy하여 project성격에 맞게
설정한다)
. set up the appropriate operating variables
. invoke server manager and connect
(SVRMGRL> CONNECT INTERNAL (/ as sysdba or sysoper)
. start the instance (SVRMGRL> STARTUP NOMOUNT)
. create the database (Oracle은 기본적인 database creation
statement를 제공한다. 사용하고자 하는 system에 맞도록 조정하여
사용한다)
Determining the Instance Name, Copying and Editing the pfiles
. Decide unique instance name
. instance name은 parameter file의 name에 default로 만들어지며
pfile directory에 생성되어 $ORACLE_HOME/dbs 밑에 Symbolic
link 된다. (예: instance name 이 CENTER이면 initCENTER.ora로)
. instance의 running 여부는 O/S dependent하게 check된다. 예를
들면 UNIX machine에서 ps – ef 와 같은 명령어로 관련 instance의
background processes의 활성화 여부를 check한다.
. parameter file을 product system 환경에 맞게 수정한다. pfile은
only read file 이므로 수정이 있으면 반드시 instance restart를 해야
적용된다.
. 주요 parameter attribute : (That should be specified)
db_name, control_files, db_block_size, shared_pool_size,
backupground_dump_dest, user_dump_dest, db_block_buffers,
compatible
(이중 db_name and db_block_size parameter는 creating database
시점에만 적용된다. 당연히, 이후 수정작업은 instance restart와 상
관없이 영향을 끼치지 못한다. 즉, db_name parameter의 이름을 바
꾼다 하여도 DB name이 변경되는 것은 아니다. 왜냐하면 이 이름은
control file에 저장되기 때문이다. Block Size도 마찬가지이다.)
(Always specify at least two control filenames in the parameter file,
placing them on separate disks if possible)
jkspark@hanafos.com - 17 - 장 경상
18. Oracle basic administration http://www.ggola.com
. setting 된 parameter attribute 확인은 v$parameter table이나
sever manager상에서 show parameter ?? command로 확인이 가능
하다. (기타 : v$sga, show sga)
Setting the system identifier and ora_nls
. System Identifier(SID) is an environment variable used by the
Oracle Server to determine to which instance a user will connect.
(ORACLE_SID=CENTER;export ORACLE_SID)
. Before starting up instance, verify that the SID is set correctly.
. ORA_NLS is the PATH to the language object files. 이
environment variable 은 database creation전에 setting한다.
(ORA_NLS=
/app/oracle/product/733/ocommon/nls/admin/data; export
ORA_NLS)
. NLS setting check : sys.v$nls_valid_values (should be set for
version 7.2 or higher)
Procedure
. connecting to the database
SVRMGRL> connect internal ( / as sysdba)
. staring the instance : read parameter file and background
processes will be started.
SVRMGRL> startup nomount
. creating the database
SVRMGRL> create databse CENTER
datafile ‘/…/system.dbf’ size 10?M
logfile group 1 ‘/…/redoCENTER1a.rdo’ size 10?K,
group 2 ‘/…/redoCENTER2a.rdo’ size 10?K ;
(그외 내용은 oracle default script crdb@SID.sql 참조)
. adding a control file : database creation시 default control file은 1
개 이므로 instance shutdown후 기존 control file은 다른 이름으로
가능한 다른 disk에 copy하고 parameter file의 control_files= 에 추
가한다)
. adding a redo log member : database creation시 default log group
은 2개이고 1개의 member를 갖는다. group당 member를 추가한다.
SVRMGRL> alter database add
logfile member ‘/…/redoCENTER1b.rdo’ to group 1 ;
(size는 기존 member와 동일하게 생성되고, v$log와 v$parameter
view를 참조한다)
. Data Dictionary Views : oracle운영에 필요한 view생성 script
catalog.sql : creates commonly used data dictionary views
catproc.sql : runs all scripts required for PL/SQL on the server
jkspark@hanafos.com - 18 - 장 경상
19. Oracle basic administration http://www.ggola.com
. Data Dictionary Users : Database administrators, Database users,
Applications, The Oracle Server (Never use DML such as INSERT,
UPDATE and DELETE to update the base data dictionary tables
directly.)
. Catagories :
user_xxx, all_xxx, dba_xxx
all data dictionary tables and vies are owned by sys.
jkspark@hanafos.com - 19 - 장 경상
20. Oracle basic administration http://www.ggola.com
4. Accessing and Updating Data
개요
Overview
1. SQL statements are processed by the Server process.
2. Identical SQL statements use shared SQL pool.
3. The database buffer cache keep before images of modified data
in rollback blocks and after images of modified data in data
blocks
4. The database writer (DBWR) writes all changed buffers to disk.
Database buffer cache
. Data blocks : data가 buffer에 없으면 disk에서 read하여 Database
buffer cache내에 저장하고 user가 modify시 change한다 => after
image
. Rollback blocks : read된 original data를 저장한다. user가 rollback
을 원하면 이 block data information을 사용 rolled back 한다. =>
before image
Copy Original version of data (before image 가 된다)
Data block 빈 BLOCK
(after image)
DISK
Cache miss (physical read)
Rollback block
(before image) Cache hit (logical read)
USER
. Redo log buffer : During the transaction processing , Sever process
는 위의 before and after image를 redo log buffer에 기록하며 이후
recovery에 사용된다.
. The database buffer cache is organized in two lists: The dirty list
and the least recently used(LRU) list. The dirty list contains
modified buffers that have not been written to disk.
Free buffers : 수정되지 않은 사용 가능한 buffers
Pinned buffers : 현재 currently accessed buffers
Dirty buffers : disk로 쓰여질 필요가 있는 수정된 buffers
jkspark@hanafos.com - 20 - 장 경상
21. Oracle basic administration http://www.ggola.com
Server Process
. All SQL statements are processed by the Server process. And
Server process는 parse, execute, fetch를 담당한다. (PGA사용)
Server process는 disk에서 read a data하기 위해 다음과 같은 작업
을 수행한다.
– Searches the LRU list.
– Looks for a free buffer
- Moves dirty buffers to the dirty list
작업중 free buffer를 찾거나 찾지 못한 상태에서 지정된 크기의 범
위를 벗어나면 server process는 searching을 중단한다.
. PGA는 server process에 위치시키는 memory이지만 MTS환경에
서는 session정보를 가지지 않는다.(SGA로 올라간다)
Statement processing
Processing SQL statement
1. parsing : syntax check => semantics check ( statement내 object 존
재 유무 check , security(grant) check from data dictionary =>
execution plan 설정 (rule base or cost base or choose..)
2. binding : parameter and value 처리 (값 넘겨주기)
3. execution : 실행 (S, I, U, D)
4. fetch : select statement only
. 동일한 SQL statement 요청을 대비 parsing된 information은
shared pool에 보존된다. (procedure를 사용하는 이유중 하나)
Select operation
. logical read(cache hit) or physical read(cache miss)를 통해 read
. 관련parameter :
DB_FILE_MULTIBLOCK_READ_COUNT = ?
(동시에 access 가능한 즉, I/O readable block수 : Full table scan에
유용)
DB_FILE_SIMULTANEOUS_WRITE = ?
(DBWR가 동시에 write 가능한 file수)
Update operation
1. acquire data block and rollback block from database buffer cache
2. exclusive row lock
3. before and after images copy to redo log buffer
jkspark@hanafos.com - 21 - 장 경상
22. Oracle basic administration http://www.ggola.com
4. 위에서 확보한 rollback block에 rollback data copy
5. 변경된 내용을 data block에 적용
DBWR 구동
. DBWR는 무엇을 하는가 :
writes all changed buffers to disk,
uses a LRU algorithm to keep most recently used blocks in
memory,
defers writes for I/O optimization (buffer에 있는 내용을 disk로 내
려쓰므로 그 사이에 system failure시 commit이 되었다 할 지라도
commit결과가 반영되지 않을 수 있다. 이런 경우 redo log file이
recovery에 반영된다. 그렇기 때문에 before and after image가 redo
log buffer로 copy 된다)
. commit시점에서 LGWR가 redo log buffer를 모두 redo log file에
적용하므로 commit이 안된 transaction 의 buffer도 모두 redo log
file에 반영된다 => piggyback write)
. DBWR가 disk에 dirty buffer를 언제 쓰는가 :
dirty list가 다 찬 경우,
free buffer를 찾지 못하고 LRU list의 정해진 a specified number of
buffers를 넘어선 경우,
time-out 시,
checkpoint 발생시
jkspark@hanafos.com - 22 - 장 경상
23. Oracle basic administration http://www.ggola.com
5. Manage Transaction Concurrency and Consistency
Transactions
Transaction commit
1. commit command after DML
2. DDL command 발생
3. 정상적 log out from Oracle Server
Transaction abort
1. rollback
2. user-requested termination
3. abnormal exit
4. process or disk failure
. DDL은 implicit commit
1. Update
2. Insert
3. DDL command issued
4. Delete
5. Rollback
이 경우 1, 2는 commit이 발생하고 단지 4만이 rollback된다
Database commits procedure
1. A user issues a COMMIT
2. LGWR flushes redo log buffer to current log group.
3. Commit result is returned to the user
4. Resources and locks are released on data and rollback blocks.
5. DBWR will eventually write database blocks to disk.
jkspark@hanafos.com - 23 - 장 경상
24. Oracle basic administration http://www.ggola.com
LGWR, Checkpoint, ARCH….
LGWR
. LGWR 구동시점
1. a commit occurs
2. redo log buffer의 1/3이상 찰 때
3. time-out시
4. every three seconds
5. DBWR이 checkpoint발생으로 인해 database buffer cache를
clean할 경우
. redo log file이 다차면 switch가 발생되어 다른 log file에 sequence
# 가 부여되고 그 log file이 current하게 된다. (current log sequence
number는 control file에 기록된다)
. alter system switch logfile ; command로 강제 log switch가능
Checkpoints
. 발생시점 :
1. log switch 시
2. time-out 시 : LOG_CHECKPOINT_TIMEOUT = ?
3. disk에 write한 block수가 일정부분에 도달시 :
LOG_CHECKPOINT_INTERVAL = ?
4. abort를 제외한 instance shutdown시
5. DBA의 강제 : alter system checkpoint ; command 시
6. Tablespace offline시 먼저 checkpoint발생 후 offline된다
7. Online backup 시 해당 file에 대해서
. 동기화정보 (synchronization information)
- checkpoint발생시 고유의 checkpoint number가 생기고 이것은
각 datafile의 header와 control file에 update된다.
– 따라서 control file의 checkpoint number는 각 datafile의 그것과
동일하다. (read only tablespace 제외)
(8i에서는 fast_start_io_target도 영향을 미침)
jkspark@hanafos.com - 24 - 장 경상
25. Oracle basic administration http://www.ggola.com
CKPT Process
- parameter CHECKPOINT_PROCESS = TRUE 인경우 활성화
- CKPT가 활성화 되면 LGWR의 작업량중 위 동기화정보를 update
하는 작업을 인수받아 대신 해주므로 LGWR의 부담을 덜어준다.
– datafile header and control file에 기록되는 checkpoint number는
맨 마지막 것이다. (system change number)
- 빈번한 checkpoint발생은 recovery시 시간을 줄여 줄 수 있으나
전체적인 performance는 expense를 요구한다.
– CKPT process의 활성화는 LGWR의 부담을 줄여주므로 database
performance를 향상 시켜준다.
ARCH
. Archiver process는 redo log files을 다른 media로(tape or disk...)
copy한다.
(for only media failure recovery)
. log switch 가 발생할 때만 작업한다.
. instance가 archivelog mode로 운영중일때 활성화된다.
jkspark@hanafos.com - 25 - 장 경상
26. Oracle basic administration http://www.ggola.com
6. Manage the Database Structure
Object Definition
Database, File, Tablespace, Segment, Extent, Block
Database
Tablespace
Tablespace
Tablespace
Segment
Extent
File #3
File #2 Block
File #1
한 segment는 다른 tablespace에 걸쳐서 존재 할 수 없다.
Logical Database Structure
. Tablespace : is sum of some datafiles maped.
can be offline, execpt SYSTEM tablespace and a tablespace
with an active rollback segment, leaving DB is running
. Tablespace uses performing partial backup and partial recovery
operations.
System tablespace : create database시 생성된다.
contains data dictionary information, procedure-package-
triggers….
contains system rollback segment.
can contain user data (때에따라 default tablespace를 정하
지 않은 경우 data 저장장소가 명확치 않으므로 system
tablespace에 기록되는 bad action이 가능하다)
Non-system tablespace : consists of rollback segments,
temporary segments, application data-indexes, user space….
추가되는 tablespace.
Physical Database Structure : data files on O/S
jkspark@hanafos.com - 26 - 장 경상
27. Oracle basic administration http://www.ggola.com
Creating a Tablespace
. Create tablespace rb_tbs datafile ‘/u01/…./rb_tbs.dbf’ size 10M
default storage ( initial 50K next 50K
minextents 10 maxextents 121
pctincrease 0) ;
. 위 default storage는 생성된 rb_tbs라는 tablespace에 생성될
segment의 create segment 문법에서 storage를 정하지 않았을 경우
위 default storage를 사용하게 된다. 만일 tablespace 생성시에도
default storage를 정하지 않는다면 system default storage를 적용시
킨다.
system default : initial 10 next 10 minextents 1 maxextents 10
pctincrease 50
dropping : drop tablespace rb_tbs including contents [cascade
constraints]
tablespace attribute : create tablespace문에서 마지막에 option의
사용으로 tablespace의 속성을 정의할 수 있다.
default : create tablespace …………….. permanent ;
this tablespace는 object를 가질 수 있다.
optional : create tablespace …………… temporary ;
this tablespace는 object를 가질 수 없으며 단지, implicit sorts
에 사용된다. : v$sort_segments
※ rollback segment tablespace도 object를 가지지 않는다. rollback
용으로 사용되는 공간일 뿐이다.
tablespace의 종류 : read-only, read-write
alter tablespace tbs_name read only ;
alter tablespace tbs_name read write ;
Segments
. Rollback : holds rollback data for rollback, read-consistency,
recovery
. Data : holds all of the data for a table or a cluster
. Index : holds all of the data for a specific index
. Temporary : holds data belonging to temporary objects
. Bootstrap : Server open시 server가 주관하는 일종의 cache
segment로 DBA와 무관한 것으로 user access불가(sys user 소유로
system tablespace에 유지)
jkspark@hanafos.com - 27 - 장 경상
28. Oracle basic administration http://www.ggola.com
7. Manage Storage Allocation
Controlling Extent Allocation
Storage parameters
Initial, next, minextents, maxextents, pctincrease, optimal(rollback
segment용), freelists, freelist groups(OPS간의 즉, instance간
freelist의 정보 교환을 위해)
. initial, mixextents 수정 불가
Segment
1 2 3
block
Initial extent Next extent
첫번째 block (segment header block) :
- extents정보
- free list정보(비어있는 block정보)
Set storage parameters on
Tables, clusters, indexes, rollback segments, tablespaces
. Storage 적용 우선순위 :
segment specific storage default storage system default
. The OPTIMAL command is only specified for rollback segments.
. FREELISTS and FREELIST GROUPS parameters cannot be
specified for tablespace defaults
Effects of changing PCTINCREASE
pctincrease 50 이라면….
Next = next * (1 + new pctincrease / 100) rounded up to the next
Oracle block
ex) pctincrease 50인 경우 initial 10K next 10K일 때 처음 next가 발
생하면….
Next = 10 ; total = 10 + 10 = 20
두번째 next가 발생하면
Next = 10 * ( 1 + 50/100) = 15 ; total = 15 + 15 = 30
세번째 next가 발생하면 …
Next = 15 * (1 + 50/100) = 22.5 ; total = 22.5 + 30 = 52.5
위는 round up을 생략한 계산
jkspark@hanafos.com - 28 - 장 경상
29. Oracle basic administration http://www.ggola.com
Database blocks
An Oracle data block is the smallest unit of storage used by
database.
Properties of Database blocks
. DB creation시 db_block_size parameter로 결정되고 all datafiles에
적용된다
. 위 size로 SGA내 database buffer도 결정
. db_block_size는 최초 변경후 수정이 불가하다
. block size의 default value는 depends on operating system
. ALL I/O는 block level로 수행되고, Oracle Server는 row level로
locking을 유지, 관리한다.
Block 정보 : row pointer
Common and Variable Header transaction entry
Table Directory Cluster Only
Row Directory Row 정보 : requires 2 bytes
of overhead per row
Free Space
PCTFREE
Row Data
PCTUSED
Controlling Space Usage
- PCTFREE : 추후 Update를 위해 block에 남겨둘 free space %
(default : 10 %)
- PCTUSED : 추후 일어날 Insert를 대비하기 위해 사용되는
Blcok의 제한 space (default : 40 %)]
따라서 PCTFREE + PCTUSED 는 100 이하여야 한다.
Update가 자주 일어나는 table의 경우 pctfree를 높임으로서
block 이동을 막을 수 있다. (update로 인한 한 row의 data가 한
block의 free space에 채워지지 않으면 그 row가 통째로 다른 block
으로 이동하기 때문에 migration)
Insert가 자주 일어나는 table의 경우는 pctused를 줄인다
(freelist정보에 대한 access를 줄이기 위해서)
위 parameters를 잘 조정하여 row data의 chaining and
migration을 줄일 수 있도록한다.
(왜냐하면 한 row는 가능한 한 block에 존재하려고 하므로 공간이
조금만 부족해도 그 row전체는 다른 block으로 이동하기 때문이
다.)
jkspark@hanafos.com - 29 - 장 경상
30. Oracle basic administration http://www.ggola.com
- INITRANS : each block header에 initially로 allocate할
transaction entries 수를 지정 (1-255, default value는 1로
setting되며 가능한 바꾸지 않는다)
- MAXTRANS : concurrently로 block을 access할 수 있는 the
maximum number of transactions를 지정(1-255, default value
는 block size와 관계되어 설정되며 바꾸어서는 안된다)
- Migration : pctfree의 지정크기 보다 더 큰 update가 발생할 수
있는데 그렇게 되면 update 작업을 동일 block에 완료할 수 없
기 때문에 그 전체 row를 다른 block으로 이동한다. 이 경우 현
block에는 이동된 row의 block을 알 수 있도록 불필요하게 공
간을 차지하는 row pointer를 기억해야 한다. 따라서 그 data를
access시 이전 존재했던 block을 access 하여 row pointer를 찾
아 옮겨진 block을 찾아가야 하는 불필요 작업이 필요하며, 경
우에 따라 계속 옮겨지면 row pointer를 따라 몇 block씩 read
하는 경우도 있을 수 있다.
Migration을 줄이기 위해선 PCTFREE설정을 고려하고 이미
migration이 일어난 경우에는 export drop import의 작업으로
row pointer를 정리할 수 있다.
- Chaining : 일반적으로 large row에서 발생하는데 1 row가 1
block에 다 들어갈 수 없는 경우 다른 block에 걸쳐서 chained되는
경우를 말한다.
Extent and Segment 관련 dictionary
USER/DBA_EXTENTS, USER/DBA_FREE_SPACE
USER/DBA_SEGMENTS,
DBA_TABLESPACE, DBA_DATA_FILES
Unused space 관리
. HWM (High water mark) : segment에서 원하는 data를 찾기 위해
서는 필요로 하는 extent 전체를 read해야 하므로 그 불필요성을 없
애기 위해 가장 마지막 extent의 사용된 마지막에 HWM을 표시하
여 read unit을 줄일 수 있다. 그러나 HWM은 data의 delete등으로
중간에 빈 space가 생겨도 내려오지 않는다.
. De-allocation
alter table tab_name deallocate unused ;
이 명령으로 사용되지 않는 space를 de-allocation이 가능하지만
HWM이상의 공간에서만 사용이 가능하다.
. Coalescing free space
alter tablespace tbs_name coalesce ;
이웃하고 있는 빈 space를 하나로 만들어 큰 공간을 만들어 주는
명령어 즉, 연속된 free space의 fragment를 없앤다.
SMON이 주기적으로 비어있는 contiguous extent의 coalescing 작
jkspark@hanafos.com - 30 - 장 경상
31. Oracle basic administration http://www.ggola.com
업을 하지만 pctincrease가 0보다 큰 tablespace에만 작업을 진행한
다.
jkspark@hanafos.com - 31 - 장 경상
32. Oracle basic administration http://www.ggola.com
8. Manage Rollback Segments
Rollback Segments
Characteristics (written in a circular fashion)
. rollback for transaction (or to savepoint)
. read consistency
. database recovery
. record data changed except SYSTEM rollback segment
(SYSTEM Tablespace의 rollback segment는 SYSTEM이라 명명되어
있고, 적어도 그 외의 Rollback segment를 1개 이상을 가지고 있어
야 한다)
Properties
. transaction 크기나 시간에 따라 커질 수 있다.
. alter rollback segment rbs_name shrink to <size> ;
이 명령으로 크기를 줄일 수 있다.
. automatically shrink를 위해선 optimal option을 사용한다.
. set transaction use rollback segment rbs_name ;
이 명령으로 rollback segment를 지정해서 사용할 수 있는데 한번만
유효하므로 여러 transaction을 요하는 경우에는 매번 이 명령을 사
용해야 한다.
Parameters
INITIAL, NEXT, MINEXTENTS, MAXEXTENTS, OPTIMAL
. Optimal option을 지정하면 rollback segment가 커지면 de-
allocate를 통해 이 optimal size만큼 유지하려한다.
. pctincrease를 지정할 수 없으므로 항상 0이다.
. minextents는 적어도 2개 이상을 유지한다.
. maxextents는 unlimited를 지정할 수 없고 available한 disk space
를 모두 사용한다.
Type
. PRIVATE : system이 인지할 수 있도록 parameter file에
ROLLBACK_SEGMENTS = … 로 명시한다 (DBA가 생성)
. PUBLIC : OPS의 경우 instance별로 지정해서 사용할 수 있도록 하
는데 사용하지만 OPS라 할지라도 일반적으로는 private이 추천된
다.
. DEFERRED : tablespace가 offline되는 경우에 immediately하게
rollback이 될 수 없는 경우 system tablespace에 만들어져서
recovery시에 적용된다.
jkspark@hanafos.com - 32 - 장 경상
33. Oracle basic administration http://www.ggola.com
create rollback segment rbs_name tablespace rbs storage
(initial .. .. optimal ??K) ;
alter rollback segment rbs_name online ;
v$rollname and v$rollstat view를 사용하여 rollback segment의
wait율을 구할수 있는데 만일, wait율이 1%보다크면 일반적으로 이
경우에 segment를 추가하거나 set 명령으로 수정한다.
일반적으로 50개 이하의 RBS사용을 추천하는데 다음을
recommand 한다.
transaction : 1 ~ 16 RBS 4개
17 ~ 32 RBS 8개
32 이상 / 4 계산결과 개수의 RBS
drop rollback segment rbs_name ;
jkspark@hanafos.com - 33 - 장 경상
34. Oracle basic administration http://www.ggola.com
9. Manage Table and Index Segments
Segment Features
Data : contain data (table, index cluster, hash cluster)
Index : Provides an efficient structure to locate specific rows in tables
Tables
Features
. holds user data
. holds system data (data dictionary)
. create table statement로 만들어진다.
. header block은 free list와 object extent information을 갖고있다.
. parallel query option 사용시 parallel로 table creation이 가능.
create table tab_name as select …….. parallel … ;
. redo log buffer를 bypass하는 unrecoverable option도 사용가능.
create table tab_name as select ….. unrecoverable ;
create table tab_name (column.. type ….), storage (….)
tablespace tbs_name ;
alter table tab_name - (column .. type..)
- add constraint …...;
drop table tab_name (cascade constraints : reference key drop) ;
truncate table tab_name ;
- Row
. row length는 제한이 없다.
. row는 multi block에 span될 수 있으므로 row chaining의 원인이
된다.
. null column의 column length는 0이다
Index
Index는 B*-Tree concept을 사용한다. (설명생략)
Features
. Independent of table or cluster
. Index만의 storage and tablespace를 갖는다.
. parallel로 creation이 가능하며, 보통 해당 table보다 작다.
. unrecoverable 사용이 가능하다.
. data segment와 다른 tablespace를 사용하는 것이 좋다.
jkspark@hanafos.com - 34 - 장 경상
35. Oracle basic administration http://www.ggola.com
. single or composite / unique or non-unique index 모두 가능하다.
Bitmap Indexing
. tables이 매우 큰 경우 (수백만 rows 이상)
. 중복된 값이 매우 많은 data ( [ex] sex, age, marital status, postal
code ..)
create [unique/bitmap] index ind_name on tab_name (column)
tablespace ind_tbs_name storage (……) pctfree 0;
- performance trade-off : index는 table retrieve speed를 올려주는
대신 table update speed의 저하를 감수해야 한다.
(table data가 바뀌면 관련 index data도 동시에 바꾸어야 하므로)
– index는 일반적으로 column data의 중복성이 5 ~ 20% 이내인 경
우에 효과적이다.
– pctused 는 index storage에 사용하지 않는다.
– pctfree 는 insert가 많이 일어날 경우 high, insert가 거의 이루어지
지 않는 경우 low하게 잡는다.
– index는 delete 작업이 이루어 지지 않으므로 지속적인 변경이 오
는 table의 index size는 계속해서 커질 수 있다. 이런 경우 index를
drop하고 다시 만들면 되지만 DB가 running 중인 경우에는 index
를 생성하는 동안 그 index를 사용할 수 없으므로 rebuild option을
사용해서 재생성 하면 가능하고 또한 recreation 보다 더 낳은
performance를 제공한다. alter index ind_name rebuild
[tablespace tbs_name] ;
drop index ind_name ;
jkspark@hanafos.com - 35 - 장 경상
36. Oracle basic administration http://www.ggola.com
10. Manage Cluster Segments
Segment Features
Index cluster : contains rows from one or more tables stored together
based on the value in a column of the tables
Hash cluster : contains rows from a table stored by way of a hashing
algorithm
Clusters는 storage structure 를 정의하고 각 cluster는 하나 이상의
table definition을 가지고 있다.
Hash clusters may contain more than one table but this is rare.
Clustered table은 마치 standalone table처럼 user에게 access된다.
Index cluster
특징
. I/O performance를 증가시킨다.
. storage overhead를 감소시킨다.
. clustered table은 Key를 공유한다.
. The cluster index is an index created on the cluster key columns
. cluster key의 최대 columns 제한은 16개로 정해지지만 실질적인
개수는 data block size에 의존적이고 대략 data block size의 1/3을
넘지 못한다.
clustered table들은 공통 column을 가지며 보통 함께 사용되고
동일한 data blokcs에 저장된다.
Advantage
. same data blocks을 사용함으로 disk I/O 감소
. clustered tabes간의 동일 data영역에 대한 storage 중복제거
. clustered tables에 대한 join시 access times 향상
. indexes를 위한 저장용량 감소
. clustered table의 join query시 상당한 performance향상
. join된 table의 key column 수정이 빠름
Disadvantage
. 일반적인 update, delete, insert가 느리다.
. 하나 이상의 tables로 만들어진 clustered table에 대한 full table
scan은 느리다.
jkspark@hanafos.com - 36 - 장 경상
37. Oracle basic administration http://www.ggola.com
Guideline
. update가 잘 일어나지 않는 query가 중심적인 tables로서 보통
join으로 query가 이루어지는 table간에 clustered table을 만든다.
. cluster key는 LONG이나 LON RAW를 갖는 column을 사용할 수
없다.
. cluster index는 cluster key column에 대한 index로서 unique 하면
안된다.
Creating cluster
1. cluster만들기 : table을 만들기 전에 먼저 만든다.
create cluster cluster_ct1_ct2 ( key_column type)
size 400
tablespace clt_data
storage ( ….. ) ;
2. index 생성
create index idx_ct1_ct2 on cluster cluster_ct1_ct2
tablespace clt_index ;
3. 첫번째 cluster table
create table ct1 ( column1, column2 ….. key_column)
cluster cluseter_ct1_ct2 (key_column) ;
4. 두번째 cluster table
create table ct2 ( column1, column2 ….. key_column)
cluster cluseter_ct1_ct2 (key_column) ;
먼저 clustering할 table에 대한 definition을 생각하고 cluster를
만든다. 그리고 index를 생성하고 난후 clustering될 table을 하나씩
생성한다.
alter command로 수정
drop cluster 하는 방법 두가지
1. drop cluster cluster_ct1_ct2 including tables ;
2. drop table ct1 ;
drop table ct2 ;
drop cluster cluster_ct1_ct2 ;
Hashing
Hashing은 data retrieval의 performance을 향상 시키기위한 일종
의 table data를 저장하는 optional 방식이다.
jkspark@hanafos.com - 37 - 장 경상
38. Oracle basic administration http://www.ggola.com
Hashing Applications
. apply a hash function to the columns of table
. store rows according to the result of the hash function
. reduce the number of I/Os typically needed to retrieve a data
block
table에 대한 hash는 먼저 cluster되어야 한다.
Creating hash cluster
1. cluster 생성 :
create cluster clt_emp ( emp_number number(4))
tablespace clt_data
hashkeys 1000
hash is emp_number
size 500 ;
2. table 생성 :
create table emp_comp (empno number(4), column2, column3
…)
cluster clt_emp (empno) ;
3. user-defined hash functions를 만드는 경우 home area code가
cluster key인 경우의 생성예:
hash is mod ( (home_area_code + home_prefix), 101)
alter command로 수정하지만 hash cluster는 alter command로
size, hashkeys, hash is를 변경할 수 없다.
drop cluster clt_emp including tables ;
jkspark@hanafos.com - 38 - 장 경상
39. Oracle basic administration http://www.ggola.com
11. Manage Constraints
Constraints
Constraint type
Not null
Unique
Check
Primary key
Foreign key
Integrity constraints
. Null value의 허용과 불허 정의
. unique value 확인
. table row의 primary identifying value 확인
. referenced table에서 column value의 적절성 확인
Data 일관성 보장
Foreign key check, application code check, database trigger check
Advantage
. easy to declare
. centralized rules
. easy to modify
. immediate user feedback
. flexible(enable, disable)
. improved performance
. documented in data dictionary
Defining constraints
- foreign key 생성시 on delete cascade : master가 delete되면
child도 함께 delete하는 option
- 보통 references table에서 column name을 지정하지만 만일,
primary key를 지정하는 경우 생략해도 된다.
Constraint names
. constraints name은 owner에게 unique 해야하고
. constraint clause의 constraint option 형식에서 지정하며
. 잘못된 경우 생성시 message로 나타나고 (미리 알 수 없다)
jkspark@hanafos.com - 39 - 장 경상
40. Oracle basic administration http://www.ggola.com
. data dictionary에 입력되고
. constraint name을 이용하여 enable, disable, drop을 쉽게할 수 있
다.
. constraint생성시 name을 지정하지 않으면 Oracle은 SYS_C00n 이
라는 형식으로 name을 만든다.
.일반적으로 Oracle이 recommend하는 naming rule은
TableName_ConstraintType_ColumnName
예) emp table의 primary key : emp_pk_empno
Creating constraints
Not null constraints
create table tab_name (
col1 number(6) constraint tab_nn_col1 not null ….) ;
. not null constraint는 null인지 not null인지를 check하는 check
constraint의 일종으로 constraint type은 check constraint와 동일한
‘C’이다. (이후의 constraints관련 view참조)
Unique constraints
create table tab_name (
col1 number(6) constraint tab_nn_col1 not null
constraint tab_uk_col1 unique
using index tablespace idx_ts
storage (….),
….) ;
. unique constraint 생성시 index를 지정하지 않으면 Oracle이 제공
하는 rule에 따라 naming된 index가 자동으로 생성
. not null을 지정하지 않으면 null unique constraint생성
(위 처럼 지정하면 not null unique constraint 생성)
Check constraints
create table tab_name (
…
col1 number(6) constraint tab_ck_col1
check ( col1 not in ( 0 ),
col2 varchar2(3) constraint tab_ck_col2
check ( col2 in (‘ALL’, ‘NOT’,’ONE’)),
…..
…..
….) ;
jkspark@hanafos.com - 40 - 장 경상