0% found this document useful (0 votes)
81 views52 pages

INFORMIX Programmer Guide (한글)

INFORMIX Programmer Guide

Uploaded by

hilevel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views52 pages

INFORMIX Programmer Guide (한글)

INFORMIX Programmer Guide

Uploaded by

hilevel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Information Management Software

IBM Informix
Programmer’s Guide

2003. 03.

© 2002 IBM Corporation


Information Management Software

Agenda
ƒ Basic Terminology & Concepts

ƒ ESQL programming highlights

ƒ Concurrency Control

ƒ Query Optimization

ƒ Homepage Supports

2 © 2002 IBM Corporation


Information Management Software

Basic Terminology & Concepts

-Data Types
-SQL New Functions
-IBM Informix Dynamic Server Terminology

© 2002 IBM Corporation


Information Management Software

IBM Informix Data Types


Character char

Numeric Exact varchar

Built-in Data Type Large-object Approximate lvarchar

User-defined Data Type Time byte decimal/numeric

Complex Data Type boolean text money

Opaque Data Type blob integer/int

Distinct Data Type clob smallint

Row Type Named Row Type date int8

Collection Type Unnamed Row Type datetime serial

set interval serial8

list decimal

multiset float

real

4 © 2002 IBM Corporation


Information Management Software

Built-in Data Types


ƒ CHARACTER
• CHAR (n)
• VARCHAR (m,r)
• LVARCHAR

ƒ BOOLEAN

ƒ NUMERIC
• SMALLINT
• INTEGER / INT8
• FLOAT Type 최소 최대 크기
• SMALLFLOAT smallint -(215-1) : -32,767 215-1 : 32,767 2 byte
• DECIMAL (p,s)
• MONEY (p,s) integer -(231-1) 231-1 4 byte
• SERIAL / SERIAL8 : -2,147,483,647 : 2,147,483,647
int8 -(263-1) 263-1 8 byte (64bit)
10 byte (32bit)
smallfloat 최대 8자리 유효자리수 4 byte
float 최대 16자리
16자리 유효자리수 8 byte
decimal precision, scale을
scale을 지정 scale이
scale이
money 최대 32자리
32자리 유효자리수 홀수:
홀수: (p+4)/2
(p+4)/2 byte
money는
money는 화폐기호 ($DBMONEY)
($DBMONEY) 출력 짝수:
짝수 (p+3)/2 byte
: (p+3)/2
기본값 : decimal(16,0), money(16,2)

5 © 2002 IBM Corporation


Information Management Software

Built-in Data Types


ƒ TIME
• DATE
• DATETIME
• INTERVAL

입력값 99.06.04 02.06.04 02.12.31


DBCENTURY 설정에 P 1999.06.04 1902.06.04 1902.12.31
따라 저장된 값
F 2099.06.04 2102.06.04 2002.12.31
※ 오늘날짜 :
2002.06.04 C 1999.06.04 2002.06.04 2002.12.31
R 2099.06.04 2002.06.04 2002.12.31
P : past
F : Future
C : Closest
R : Present (Default)

6 © 2002 IBM Corporation


Information Management Software

Built-in Data Types


ƒ LARGE-OBJECTS
• Simple Large-
Large-Objects
• TEXT
• BYTE
• Smart Large-
Large-Objects
• BLOB
• CLOB

7 © 2002 IBM Corporation


Information Management Software

Complex Data Types / User Defined Data Types


ƒ Complex Data Types
• Collection Data Types
• SET
• MULTISET
• LIST
• Row Data Types
• Named row types
• Unnamed row types

ƒ User-Defined Data Types


• Distinct Types
• Opaque Types

8 © 2002 IBM Corporation


Information Management Software

SQL New Functions


ƒ CASE WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE resultn
END

ƒ NVL(value1, value2)
같은 의미 : CASE value1
WHEN null THEN value2
ELSE value1
END

ƒ DECODE(value1, value2, value3, value4, … valuen)


같은 의미 : CASE value1
WHEN value2 THEN value3

ELSE valuen
END

9 © 2002 IBM Corporation


Information Management Software

SQL New Functions


ƒ TO_DATE(string, [,fmt])
ƒ TO_CHAR(date, [,fmt] )
format 문자 의미
%Y 4자리 연도
%m 월
%B 월 (January, February, March, April, …)
%d 일
%A 요일 (Monday, Tuesday, Wednesday, …)
%R 24시간
24시간::분
%H 24시간
24시간
%M 분
%S 초
%Fn 소수점 이하 n자리 초

10 © 2002 IBM Corporation


Information Management Software

SQL New Functions


ƒ TRIM( { LEADING | TRAILING | BOTH } trim_expr FROM source_expr )
ƒ TRIM(source_expr) = TRIM( TRAILING ‘ ’ FROM source_expr)

ƒ LPAD ( string, length, [,pad] )


ƒ RPAD ( string, length, [,pad] )

ƒ UPPER
ƒ LOWER
ƒ INITCAP

11 © 2002 IBM Corporation


Information Management Software

SQL New Functions


ƒ REPLACE ( string, old [,new] )

ƒ SUBSTR(string,start [,length] )
start : Positive - Counts forward
Negative - Counts backward
0 - equivalent to 1

ƒ SUBSTRING(string FROM start [FOR length] )


Start : Positive - Counts forward
Negative - Counts backward from one position before the first character
0 - counts from one position before the first character

12 © 2002 IBM Corporation


Information Management Software

IBM Informix Dynamic Server Terminology


ƒ Chunk
ƒ Page
ƒ Extent
ƒ Tblspace
ƒ Dbspace
ƒ Blobspace Page Header
ƒ Smart blobspace page_id timestamp num_slots pg_type free_ptr free_cnt
(4) (4) (2) (2) (2) (2)
next prev
(4) (4)
Raw device

Chunk 1
Page

Piece of Raw device Table extent index extent timestamp (4)


Page 0 Page 1 Page 0 Page 1 slot table
Chunk 2 bitmap data bitmap index
Page 2 Page 3 Page 2 Page 3 RowOffset RowSize
Cooked device data data index index (2) (2)
Page 4 Page 5 Page 4 Page 5
Chunk 3 reminder blob index free
Page 6 Page 7 Page 6 Page 7
free free free free

13 © 2002 IBM Corporation


Information Management Software

Logical Concepts / Physical Concepts


ƒ Logical Concepts rootdbs dbspace1 dbspace2
create database example1db;
example1db example2db
create database example2db in dbspace1; second_table
create table first_table ( first_table
tab_id int ,
name char(20) ,
address char(50)
);
create table second_table (
tab_id int ,
name char(20) ,
address char(50)
) in dbspace2 ;

ƒ Physical Concepts
create table first_table (
tab_id int ,
name char(20) ,
address char(50)
) extent size 32 next size 16 ; first_table page
create table second_table (
tab_id int , second_table page
name char(20) ,
other table page
address char(50)
) extent size 16 next size 8 ;
page size = 2k

14 © 2002 IBM Corporation


Information Management Software

Data Page monitoring


ƒ 테이블 생성
CREATE TABLE monitoring (col1 SERIAL, col2 CHAR(2000));
CREATE TABLE dummy (col1 INT);

ƒ 데이터 입력 (8건)
INSERT INTO monitoring VALUES (0,'data');

ƒ 컬럼 추가
ALTER TABLE monitoring ADD col3 INT;

ƒ 데이터 입력 (1건)
INSERT INTO monitoring VALUES (0,'data');

ƒ Monitor
oncheck –pT stores_demo:monitoring

15 © 2002 IBM Corporation


Information Management Software

Index Page
ƒ 인덱스 종류
• Unique
• Duplicate
• Composite
• Cluster
410
394
ƒ 인덱스 생성 기본 구문 391
• CREATE [ UNIQUE ] [ CLUSTER ] INDEX index_name >
387 387
ON table_name ( column_name_list ) [ IN dbspace ] ; 297
> 293
ƒ 인덱스 변경 292 DATA
292
292
• ALTER INDEX index_name TO CLUSTER ; 97
89
• RENAME INDEX old_index_name TO new_index_name ; 95
89
72
ƒ 인덱스 삭제 64
• DROP INDEX index_name ; 23
Root node Branch node Leaf node
ƒ 다음과 같은 이유로 인덱스 키는 작게 만드는 것이 바람직하다.
• 하나의 페이지에 저장되는 인덱스 키가 많아진다 414
• 인덱스 페이지의 노드 레벨이 감소한다 414 378
378 >
292 Splits 292
150 292
+ 150
88 88

16 © 2002 IBM Corporation


Information Management Software

Index Page
ƒ 인덱스 사용의 장점
• 데이터 페이지의 입출력 횟수가 감소한다
• 인덱스 데이터에 대하여 정렬 작업이 생략된다
• 데이터의 유일성을 보장할 수 있다 (Unique index)
• Key-
Key-only 검색으로 데이터 페이지를 읽지 않을 수 있다
데이터에
ƒ 인덱스 소요 비용 Disk Space Costs 대한 포인터 Processing Time Costs
• 디스크 사용 공간 (non-fragment table : 4
• DML 문장 수행시간 Fragment table : 4 + 4 )
data index
data + index

update
Slot(4) delete
인덱스 컬럼 데이터 Delete Flag(1)
ƒ 인덱스 사용 가이드 insert
• 선택적인 필터 컬럼,컬럼, 조인 컬럼에 사용한다 Cost of Indexing
• 정렬에 자주 사용되는 컬럼에 사용한다
• 중복값이 많은 컬럼에는 사용하지 않는다
• 주요 인덱스의 개수를 제한한다
• 키값의 크기를 작게 한다
• Composite 인덱스로 유일성을 증가시킨다
• Cluster 인덱스로 데이터 조회 속도를 증가시킨다
• 대량의 update, delete, insert 작업 전에 미리 인덱스를 disable한다
disable한다

17 © 2002 IBM Corporation


Information Management Software

ESQL/C Programming Highlights

-Overview
-Error Handling
-Prepare, Execute
-Cursor

© 2002 IBM Corporation


Information Management Software

Overview
ƒ ESQL/C
• C 프로그램 내에 sql 구문을 바로 넣어 그 실행 결과를 프로그램에서 다양하게 사용할 수 있도록 제공되는
어플리케이션 개발 tool
• ESQL/C의
ESQL/C의 주된 component는
component는 preprocessor로서
preprocessor로서 ESQL/C code를
code를 C code로
code로 변환하여 C compiler에게
compiler에게
넘겨준다.
넘겨준다.

ƒ ESQL/C프로그램 작성 규칙
• ESQL/C preprocessor가
preprocessor가 다른 C code와
code와 구별할 수 있게 하기 위해 SQL은
SQL은 “$” 혹은 “EXEC SQL”
SQL”으로 시작
• SQL구문의
SQL구문의 끝에는 “;”를 붙임. 붙임.
• SQL 구문 안의 변수(변수(host 변수라 부름)
부름)는 변수 이름 앞에 “:”를 붙임.
붙임.
• 주석은 표준 C의 주석인 “/* */” */”사용

ƒ ESQL/C 프로그램 컴파일


• esql [-e] [preprocessor 옵션]
옵션] [cc
[cc 매개변수]
매개변수] [-
[-o 실행파일]
실행파일] 소스.
소스.ec [링크옵션]
링크옵션]

19 © 2002 IBM Corporation


Information Management Software

Overview
ƒ include 에 지정된 파일을 찾는 순서 myfile.ec
• 현재 디렉토리
• 컴파일시 -I 옵션으로 지정한 디렉토리 # include <stdio.h>
• $INFORMIXDIR/incl
INFORMIXDIR/incl//esql EXEC SQL include pgm_global.h;
• /usr/include
usr/include EXEC SQL “filename”
main ()
ƒ 다음과 같은 preprocessor 구문을 사용할 수 있다 {
• define, undef …
• ifdef,
ifdef, elseif,
elseif, else, endif,
endif, ifndef }
• 예제
EXEC SQL define USERTRANSACTIONS;
EXEC SQL ifdef USERTRANSACTIONS;
EXEC SQL begin work;
pgm_global.h
EXEC SQL endif;
endif;

EXEC SQL include sqlca;


EXEC SQL begin declare section;
int customer_num;
long drop_date;
EXEC SQL end declare section;

20 © 2002 IBM Corporation


Information Management Software

Host variables
ƒ 호스트 변수 : SQL 데이터를 저장하는 C 변수
ƒ 대소문자 구분
ƒ SQL문장안에서 컬럼명과 구분하기 위하여 호스트변수 앞에 :기호 사용
ƒ 선언
• 달러 기호 사용 $ extern short StockNumS ;
$ CHAR *desc
*desc;;
• EXEC SQL 키워드 사용
func1()
EXEC SQL begin declare section;
$ double StockNumS ;
char *desc
*desc;;
EXEC SQL end declare section; ${
ƒ 사용 $ long StockNumS ;
• SQL문
SQL문 내에서 :
EXEC SQL update customer set zipcode = :zipcode
:zipcode ; $}
• C 구문 안에서
gets (dbname
(dbname);
);
EXEC SQL database :dbname
:dbname;;
func2()
{
ƒ external 이나 static으로 선언하지 않은 경우 자동적으로 local 범위 $ insert into stock …
values ($StockNumS);
:
}

21 © 2002 IBM Corporation


Information Management Software

Database Connections
ƒ ESQL/C 구문
• CONNECT TO 데이터베이스명
• DISCONNECT ALL
ƒ CONNECT구문의 옵션
• Connection 이름
• EXEC SQL CONNECT TO ‘stores@munish
stores@munish’’ AS ‘munich_con
munich_con’’ ;
• User 절
• EXEC SQL CONNECT TO ‘stores@munish
stores@munish’’ USER :uid
:uid USING :passwd
:passwd ;
• Default 절 (데이터베이스를 오픈하지 않고 서버에 연결) 연결)
• EXEC SQL CONNECT TO DEFAULT ;
• Default절
Default절 사용 후 다음과 같은 문장이 필요
9 DATABASE
9 CREATE DATABASE
9 START DATABASE
ƒ 연결 전환 (switching)
• 구문
EXEC SQL SET CONNECTION ‘munish_con
munish_con’’ ;
EXEC SQL SET CONNECTION :connect_id ;
EXEC SQL SET CONNECTION DEFAULT;
ƒ 연결 종료 (disconnecting)
• 열린 데이터베이스를 닫고 connection을
connection을 종료한다
EXEC SQL DISCONNECT :connect_id ;
EXEC SQL DISCONNECT CURRENT ;
EXEC SQL DISCONNECT DEFAULT ;
EXEC SQL DISCONNECT ALL ;
• default로
default로 connect했거나
connect했거나 connection이
connection이 하나 일 경우 DEFAULT 사용

22 © 2002 IBM Corporation


Information Management Software

Error Handling
ƒ SQL문을 실행한 후 서버에서 SQLCA라 불리는 영역에 feedback정보를 남긴다
• errors
• performance struct sqlca_s {
• warnings long sqlcode ;
ƒ SQLCODE 는 sqlca.sqlcode 값과 같다 char sqlerrm[72] ;
• SQLCODE < 0 : 에러 코드 값 char sqlerrp[8] ;
• SQLCODE = 0 : 정상적 처리 long sqlerrd[6] ;
• SQLCODE = 100 : SQLNOTFOUND, 찾는 행이 없음 struct sqlcaw_s {
• SQLCODE = 1~99 : Dynamic SQL char sqlwarn0 ;
ƒ 에러 메시지를 얻기 위한 함수 char sqlwarn0 ;
• rgetmsg, char sqlwarn0 ;
rgetmsg, rgetlmsg
char sqlwarn0 ;
ƒ SQL문이 실행되고 다음과 같은 4가지 중 하나의 상태가 된다 char sqlwarn0 ;
• 성공
char sqlwarn0 ;
• 성공,
성공, 찾을 수 있는 데이터는 없음 char sqlwarn0 ;
• 성공,
성공, 경고(
경고(warning) 메시지가 있음 char sqlwarn0 ;
• 실패
} sqlwarn ;
ƒ 성공 외의 나머지 상태에 대한 처리 방법을 exception처리로 제어한다 };
• WHENEVER exception action extern struct sqlca_s sqlca;
• exception : NOT FOUND, SQLWARNING, SQLERROR
• action : GO TO label, CALL function, STOP, CONTINUE
• 디폴트 action은
action은 CONTINUE
ƒ WHENEVER문의 scope는 한 소스 파일에서 global 성격을 가진다

23 © 2002 IBM Corporation


Information Management Software

Error Handling
ƒ GET DIAGNOSTICS 사용
• GET DIAGNOSTICS 문은 여러 개의 SQL exception을
exception을 처리할 수 있고,
있고, ANSI 및 X/OPEN 표준으로 컴파일된다
• SQLCA 는 계속 사용 가능하다
• 다음 세가지 분류로 사용한다
• SQLSTATE
• GET DIAGNOSTICS 문
• GET DIAGNOSTICS EXCEPTION 문
• GET DIAGNOSTICS 의 정보
• MORE : 모든 exception이
exception이 반환되었음을 나타냄
• NUMBER : exception의
exception의 갯수
• ROW_COUNT : SQL에
SQL에 의해 처리된 행 수
• EXCEPTION 의 정보
• RETURNED_SQLSTATE
• SERVER_NAME
• CONNECTION_NAME
• CLASS_ORIGIN 등
SQLSTATE

C C S S S
00 성공
01 성공(경고포함)
subclass code 02 데이터없음
class code >02, IX 에러발생

24 © 2002 IBM Corporation


Information Management Software

Error Handling
ƒ Indicator 사용
• 데이터를 호스트변수에 저장할 때 다음과 같은 Exception이 Exception이 발생할 수 있다
• NULL값을
NULL값을 fetch 하였다
• 컬럼 데이터에 비해 호스트 변수의 크기가 작다
• 사용법
• :host변수
host변수::indicator변수
indicator변수
• $host변수
host변수$$indicator변수
indicator변수
• :host변수
host변수 INDICATOR indicator변수
indicator변수 (ANSI 표준)
표준)

ship_instruct char(40)

NULL

ring bell, kick door loudly


ship_instruct instruct_ind
instruct_ind
NULL -1

ship_instruct instruct_ind
instruct_ind
ring bell, kick 40

25 © 2002 IBM Corporation


Information Management Software

Prepare, Execute
ƒ Prepare / Execute 구문
PREPARE prepare_statement_id FROM { “quoted_string”
quoted_string” | :host_variable } ;
EXECUTE prepare_statement_id [ USING :host_variables ] ;

ƒ 단일 SQL문 처리 예
EXEC SQL insert into customer (customer_num, fname,
fname, lname,
lname, company)
values (0, :fname
:fname,, :lname
:lname,, ‘MPS Corp’
Corp’);
EXEC SQL insert into items values (:itemsrec
(:itemsrec);
);
※ itemsrec 변수는 items테이블의
items테이블의 컬럼 순서로 선언된 structure 형

ƒ PREPARE / EXECUTE 사용
EXEC SQL PREPARE ins_p from
“insert into customer (customer_num, fname,
fname, lname,
lname, company)
values (0,?,?,?)”
(0,?,?,?)” ;
EXEC SQL EXECUTE ins_p using :fname
:fname,, :lname
:lname,, :company;

ƒ PREPARE를 사용하는 이유
• PREPARE 시점에 SQL문장에
SQL문장에 대하여 미리 parsing되고
parsing되고 query plan이
plan이 생성된다
• EXECUTE 시점에는 처리해야 할 값만 넘겨주면 즉시 실행된다
• 하나의 DML문장에서
DML문장에서 여러번 값을 바꿔서 넘겨주어야 할 때 PREPARE에서
PREPARE에서 한 번만 query plan을
plan을 생성하므로
유용하게 사용할 수 있다

26 © 2002 IBM Corporation


Information Management Software

Cursor
ƒ Cursor의 이해
• Cursor 는 select구문에
select구문에 의해 선택된 row들을 row들을 가리키고 있는 일종의 marker라고
marker라고 볼 수 있음.
있음.
• 여러 개의 row를
row를 가져오는 select문의
select문의 결과에 대해 처리하기 위해서 필요함.
필요함.
• Cursor의
Cursor의 종류
• Select cursor
9 Scroll cursor
9 Non-
Non-scroll cursor
9 For update cursor
• Insert cursor

Scroll cursor Non-


Non-Scroll cursor For Update cursor

Previous

Next Next Next

27 © 2002 IBM Corporation


Information Management Software

Scroll Cursor
ƒ 구문
• DECLARE
DECLARE cursor_id SCROLL CURSOR [WITH HOLD] FOR select_stmt ;
• OPEN
OPEN cursor_id ;
• FETCH
FETCH [position] cursor_id [INTO host_variable_list] ;

Position : FIRST, LAST, CURRENT, NEXT, PREVIOUS, ABSOLUTE n, RELATIVE


RELATIVE n

FIRST
NEXT
CURRENT
PREVIOUS
ABSOLUTE 5
LAST RELATIVE +3

• CLOSE
CLOSE cursor_id ;
• FREE
FREE cursor_id ;

28 © 2002 IBM Corporation


Information Management Software

Scroll Cursor
ƒ WITH HOLD 구문
• WITH HOLD구문을
HOLD구문을 사용한 커서는 transaction이
transaction이 종료되어도 close되지
close되지 않는다.
않는다.

ƒ Fetch Buffer Size declare cursor declare cursor with hold


• 환경변수 : export FET_BUF_SIZE=30000 open open
• 전역변수 : EXEC SQL include sqlhdr ; begin work begin work
FetBufSize=30000
FetBufSize=30000 ; : :
commit work; commit work;
fetch fetch
ƒ Deferred Prepare
close close
• 환경변수 : export IFX_DEFERRED_PREPARE=1 (enable)
free free
export IFX_DEFERRED_PREPARE=0 (disable)
• SQL구문
SQL구문 : EXEC SQL set deferred_prepare ;
EXEC SQL set deferred_prepare enabled ;
EXEC SQL set deferred_prepare disabled ;

ƒ Open-Fetch-Close
• 환경변수 : export OPTOFC=1 (enable)
export OPTOFC=0 (disable)

ƒ Autofree
• 환경변수 : export IFX_AUTOFREE=1 (enable)
export IFX_AUTOFREE=0 (disable) EXEC SQL free stmt_id; EXEC SQL set autofree;
• SQL구문
SQL구문 : EXEC SQL set autofree;
autofree; EXEC SQL close cur_id; :
EXEC SQL set autofree enabled ; EXEC SQL free cur_id; EXEC SQL close cur_id;
EXEC SQL set autofree disabled ;

29 © 2002 IBM Corporation


Information Management Software

For Update Cursor


ƒ 구문
• DECLARE
DECLARE cursor_id CURSOR [WITH HOLD] FOR select_stmt FOR UPDATE ;
• OPEN
OPEN cursor_id ;
• FETCH
FETCH cursor_id [INTO host_variable_list] ;
• UPDATE
UPDATE … WHERE CURRENT OF cursor_id ;
• CLOSE
CLOSE cursor_id ;
• FREE
FREE cursor_id ;
decide to change x ,
place an update lock on x
display update display update
fetch row x row x xÆy fetch row x row x xÆy
User1 User1

User2 User2

fetch row x update try to update x Æ z


xÆz but, get a lock error !
No Lock Used Using For Update Cursor

30 © 2002 IBM Corporation


Information Management Software

Insert Cursor
ƒ 구문
• DECLARE
DECLARE cursor_id CURSOR FOR insert_stmt ;
• OPEN
OPEN cursor_id ;
• PUT
PUT cursor_id [ FROM host_variable_list ] ;
• FLUSH
FLUSH cursor_id ;
• CLOSE
CLOSE cursor_id ;
• FREE
FREE cursor_id ;

31 © 2002 IBM Corporation


Information Management Software

Concurrency Control

-Isolation
-Lock

© 2002 IBM Corporation


Information Management Software

Isolation – Read Concurrency Control


ƒ ANSI SQL-92 Transaction Isolation (SET TRANSACTION) - ANSI표준
ANSI표준
• Read Uncommitted - access mode지원
mode지원
• Read Committed - 트랜잭션당 한번만
• Repeatable Read - 트랜잭션이 끝날 때까지 유효
• Serializable Read - 트랜잭션에서만 사용

ƒ Informix Isolation (SET ISOLATION)


• Dirty Read
• Committed Read - non-
non-ANSI
• Cursor Stability - 트랜잭션에서 전환가능
• Repeatable Read - 트랜잭션이 끝나거나 다른 SET ISOLATION구문을
ISOLATION구문을 실행할 때까지 유효
- 로깅모드 데이터베이스에서 언제든 사용 가능
ƒ Access Mode
• SET TRANSACTION READ WRITE ;
• SET TRANSACTION READ ONLY ;

ANSI Levels SET TRANSACTION SET ISOLATION


Read Uncommitted READ UNCOMMITTED DIRTY READ
Read Committed READ COMMITTED COMMITTED READ
N/A N/A CURSOR STABILITY
Repeatable Read REPEATABLE READ REPEATABLE READ
Serializable SERIALIZABLE REPEATABLE READ

33 © 2002 IBM Corporation


Information Management Software

Isolation – Read Concurrency Control


ƒ Read Uncommitted / Dirty Read Dirty Read server
• SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; process
• SET ISOLATION TO DIRTY READ ; 기존의 lock을 check하지 않고
Data 조회.
ƒ Read Committed / Committed Read
• SET TRANSACTION ISOLATION LEVEL READ COMMITTED ; Committed
• SET ISOLATION TO COMMITTED READ ; server
Read
process
ƒ Cursor Stability 자신이 lock을 걸 수 있는지
check하고 조회
• SET ISOLATION TO CURSOR STABILITY ;

Cursor
ƒ Serializable / Repeatable server
Stability
• SET TRANSACTION ISOLATION LEVEL SERIALIZABLE ; process
• SET TRANSACTION ISOLATION LEVEL REPEATABLE READ ; 현재 fetch하고 있는 row에 대해
• SET ISOLATION TO REPEATABLE READ ; Lock을 걸고, 다음row를 fetch할
때 해제
Repeatable
server
Read
process
질의에서 참조하고 있는 모든
row에 대해 lock 발생

34 © 2002 IBM Corporation


Information Management Software

Lock – Update Concurrency Control


ƒ Lock의 적용 단위
• Database 레벨
• Table 레벨
• Page 레벨
• Row 레벨
stores_demo
• Key 레벨
DATABASE stores_demo EXCLUSIVE ;

LOCK TABLE customer IN SHARE MODE; SELECT


customer INSERT
stores_demo DELETE
UPDATE
LOCK TABLE orders IN EXCLUSIVE MODE; orders SELECT

DIRTY READ

row 레벨 page 레벨

35 © 2002 IBM Corporation


Information Management Software

Lock – Update Concurrency Control


ƒ Lock의 종류
• Shared Lock
• Exclusive Lock
• Update Lock

ƒ Lock 모드 설정
• SET LOCK MODE TO NOT WAIT;
• SET LOCK MODE TO WAIT 20;
• SET LOCK MODE TO WAIT;

36 © 2002 IBM Corporation


Information Management Software

Lock – Update Concurrency Control


ƒ Retain Update Lock
• SET ISOLATION TO DIRTY READ RETAIN UPDATE LOCKS;
• SET ISOLATION TO COMMITTED READ RETAIN UPDATE LOCKS;
• SET ISOLATION TO CURSOR STABILITY RETAIN UPDATE LOCKS;
DR, CR, CS
DR,CR,CS RETAIN UPDATE

DR CR CS

U DRU CRU CSU FOR


U UPDATE
U 커서

DR CR CS

ƒ Key value locking


• 인덱스가 있는 데이터를 update,delete,insert 할 때 인덱스 Key에
Key에 locking하는
locking하는 기법

key value rowid delete flag


0 : Not deleted
1 : Deleted

37 © 2002 IBM Corporation


Information Management Software

Query Optimization

-Cost Based Query Optimizer


-Explain
-Directives
-Update Statistics

© 2002 IBM Corporation


Information Management Software

Cost-based Query Optimizer


ƒ Query Plan
• Optimizer가
Optimizer가 선택하는 access plan과
plan과 join plan으로
plan으로 결정
• 조회할 페이지를 줄이고 불필요한 정렬 작업을 최소화하도록 선택

ƒ Access Plan 작성 단계
• 각 필터를 통해 예상되는 데이터 출력 건수 산정 (selectivity)
• 인덱스 사용 가능 여부 검사
- filter 컬럼
- ORDER BY / GROUP BY 컬럼
• 최적의 access 방안 선택
- sequentially
- by an index

ƒ Join Plan 작성 단계
• 테이블간의 join 조합 구성
• 각 조합별로 I/O 및 CPU cost 산정
• 부하가 많은 (cost가
cost가 크다.
크다. expensive) 조합은 plan에서
plan에서 제거

39 © 2002 IBM Corporation


Information Management Software

Explain - Viewing the Query Plan


ƒ Query plan 확인
• SET EXPLAIN { ON | OFF } ;

ƒ EXPLAIN을 ON시키고 SQL구문을 실행하면 query plan을 확인 할 수 있는 텍스트 파일이 생성된다.


• 예상 비용 (estimate cost)
• 테이블 접근 순서
• 임시테이블 사용 정보
• access method / join method

ƒ Explain 파일
• UNIX : ${PWD}/sqexplain
${PWD}/sqexplain.out
.out 또는 ${HOME}/
${HOME}/sqexplain
sqexplain.out
.out
• NT : %INFORMIXDIR%\
%INFORMIXDIR%\sqexpln\
sqexpln\username.out

40 © 2002 IBM Corporation


Information Management Software

Explain - examples
ƒ Sequential Scan with Temporary Table
ƒ Sequential Scan with Filter
ƒ Key-only Index Scan

41 © 2002 IBM Corporation


Information Management Software

Explain - examples
ƒ Index Scan with Lower Index Filter
ƒ Index Scan with Lower and Upper Index Filters

42 © 2002 IBM Corporation


Information Management Software

Explain - examples
ƒ Dynamic Hash Join
ƒ Key-First Index Scan

43 © 2002 IBM Corporation


Information Management Software

Directives
ƒ SQL에 직접적으로 optimizing 방법을 명시하는 구문을 optimizer directives 라고 한다
• Positive Directives
• Negative Directives

ƒ Optimizer Directives의 종류
• Access method directives
• Join order directives
• Join method directives
• Optimization goal directives
• Explain diretivies

ƒ SQL comment 문자 뒤에 + 기호를 붙여서 directives를 나타낸다


• --+
--+ directives 구문
• {+ directives 구문 }
• /*+ directives 구문 */

44 © 2002 IBM Corporation


Information Management Software

Directives
ƒ Access Method Directives
• INDEX
• AVOID_INDEX
• FULL
• AVOID_FULL

INDEX (참조테이블 )

AVOID_INDEX (참조테이블 인덱스명

FULL

AVOID_FULL (참조테이블

※ 참조테이블 : table, synonym, alias

45 © 2002 IBM Corporation


Information Management Software

Directives
ƒ Join Method Directives
• USE_NL
• AVOID_NL
• USE_HASH
• AVOID_HASH
,

USE_NL ( 참조테이블 )

AVOID_NL ,

USE_HASH ( 참조테이블

AVOID_HASH /BUILD

/PROBE

46 © 2002 IBM Corporation


Information Management Software

Directives
ƒ Join Order Directives
• ORDERED

ƒ Optimization Goal Directives


• FIRST_ROWS
• ALL_ROWS (default)

ƒ Explain Directives
• EXPLAIN
• EXPLAIN AVOID_EXECUTE

47 © 2002 IBM Corporation


Information Management Software

Update Statistics
ƒ UPDATE STATISTICS구문을 사용하여 시스템 카타로그 테이블의 통계 정보를 갱신한다

ƒ 구문
• 데이터베이스의 모든 오브젝트에 대하여 수행
UPDATE STATISTICS [ LOW | MEDIUM | HIGH ] ;
• 특정 테이블과 그 테이블에 생성된 인덱스에 대하여 수행
UPDATE STATISTICS [ LOW | MEDIUM | HIGH ] FOR TABLE [ table_name ] ;
• 특정 컬럼에 대하여 수행
UPDATE STATISTICS [ LOW | MEDIUM | HIGH ] FOR TABLE table_name ( column_name ) ;

48 © 2002 IBM Corporation


Information Management Software

Update Statistics Guideline


ƒ 데이터베이스 전체 또는 테이블별로 LOW 모드로 수행하는 것이 일반적
ƒ LOW 모드로 수행하였을 때 만족스럽지 못하다면 다음 단계 수행
• 대용량 테이블의 경우
1. 테이블별로 MEDIUM 모드, 모드, distribution only 옵션으로 수행
2. 인덱스의 첫번째 컬럼에 대하여 HIGH 모드 수행
3. Multi-
Multi-column으로
column으로 생성된 인덱스 고려
4. 기타 컬럼에 대하여 컬럼 단위로 LOW 모드 수행
• 소규모 테이블의 경우
테이블 단위로 HIGH 모드 수행

ƒ 다음과 같은 경우 반드시 UPDATE STATISTICS를 수행해야 한다


• 데이터를 테이블에 대량 로드 한 후
• 데이터 수정이 상당히 많아서 데이터 분포가 변경 되었을 때
• 테이블의 대부분의 행에서 입력 또는 삭제 작업이 일어났을 때
• 인덱스를 추가하거나 삭제 또는 변경하였을 때

49 © 2002 IBM Corporation


Information Management Software

Homepage Supports

© 2002 IBM Corporation


Information Management Software

http://www.ibm.com/kr/informix

51 © 2002 IBM Corporation


Information Management Software

http://www.ibm.com/kr/informix
ƒ 특정 날짜가 몇 월 몇 째주인지 알고 싶을 때 사용할 수 있는 stored procedure.

ƒ PHP와 연동 중 –439에러가 발생하는 원인

ƒ JDBC를 사용한 application의 메모리 증가를 최소화 하기 위한 방안

ƒ 현재 lock을 가지고 있는 테이블 또는 세션을 확인

ƒ dbspace의 사용 상태를 sysmaster query를 통하여 모니터링

ƒ 각 테이블 별 extent 개수 및 사용량

ƒ 청크 안에 저장된 테이블 정보

ƒ unique 컬럼으로 사용할 컬럼에 duplication 데이터 삭제 방법

ƒ 특정일 기준으로 몇 달 전,후 날짜 출력

ƒ 두 시간 차이를 표현 하거나 두 날짜 사이를 일 수로 표현

ƒ 등등…

52 © 2002 IBM Corporation

You might also like