Oracle
오라클 함수
0like ~와 같은<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” />
like WHERE name LIKE ‘홍%’;
WHERE jubun LIKE ‘______1%’ OR jubun LIKE ‘______3%’;
->사원테이블에서 남자만 검색하는법..
order by 와 단일행 함수 nvl,nvl2,coalesce
order by sal*12+nvl(comm,0) desc;
drder by 2,5 desc;
두번째 컬럼에 오름차순 5번째 컬럼에 내림차순
lower,upper,inticap
select ‘orAcLE’,lower(‘orAcLE’),upper(‘orAcLE’),
initcap(‘orAcLE’)
from dual;
->lower-> 전부다 소문자
upper-> 전부다 대문자
initcap->첫글자만 대문자 나머지는 소문자
ex1)emp 테이블에서 직종명이 salesman 인 사원의 모든정보를 나타내세요.
소문자로 전부 변환 where lower(job)로하고 소문자로 검색한다…
select job,lower(job)
from emp
where lower(job)=’salesman’;
concat 함수와 파이프 함수
ex2)SMITH’s 급여는 이고 직종은 이다
select ename||’”s’||’급여는’||sal||’이고’||’직종은은’||job||’이다’;
concat 함수는 오로지 2개의 문자 컬럼만 연결시켜준다
select concat(ename,job) from emp; 된다
select concat(ename,’직종은’,job) from emp; 오류가 난다.
select concat(ename||’직종은’,job) from emp;이렇게 써야한다
SUBSTR 함수
SUBSTR(‘KH정보교육원’,3,2), -3번째 글자에서 2글자만 표시해라
length 함수
-글자수 알려주기 lengthb –바이트 수알려주기
SELECT LENGTH(‘안녕하세요’), LENGTHB(‘안녕하세요’) FROM dual
=> 결과값 5 10
reverse 함수
->문자열을 거꾸로 보여주는 함수
INSTR함수
==>명명된 문자의 위치를 구함
ex1)
select
instr(‘KH정보교육원 KH은행’,'KH’,1,2),
=>해당문자열에 첫글자부터 두번째로 KH글자가 나오는위치 결과값 =>9
instr(‘KH정보교육원 KH은행’,'KH’,2,1),
=>해당문자열에 두번째글자부터 첫번째로나오는 kh위치 결과값 =>9
instr(‘KH정보교육원 KH은행’,'KH’,1),
=>안썼을 경우 앞에 1이 생략 1,1 와 같다. 결과값 =>1
from dual;
LPAD,RPAD 함수
pad->채우다
select ‘JAVA’,'오라클’,
LPAD(‘JAVA’,10,’*'), 결과값=> ******JAVA
RPAD(‘오라클’,10,’*'), 결과값=> 오라클****
–10(byte)를 잡아주고 JAVA(4yte)를 쓰고 남는부분을 별로 채워라
LTRIM,RTRIM
LTRIM(arg1,arg2) –arg1에서 왼쪽부터arg2문자열이 동일문장을 삭제한다
RTRIM(arg1,arg2) –arg1에서 오른쪽부터arg2문자열이 동일문장을 삭제한다
SELECT ‘홍 ‘||’길동’,
RTRIM(‘홍 ‘)||’길동’,
생략시에는 공백으로 인정한다…
‘홍’||’ 길동’,
‘홍’|| LTRIM(‘ 길동’)
FROM dual;
*보통 공백을 지우기 위해서 사용한다
TRANSLATE 함수
TRANSL:ATE( , , )(바꾸어 준다)
SELECT TRANSLATE
(‘이육삼팔-열일여일’, 여기 적혀 있는 문자를
‘영일이삼사오육칠팔구’, 여기와 아래 숫자를 1:1대입해서 바꾸어준다
’0123456789′)
from dual;
REPLACE 함수
Replace( arg1,arg2 ,arg3 ) arg1에 문장중 arg2가나오면 arg3으로 변경해라
SELECT ‘오라클서버 이리오라 오라미’,
REPLACE(‘오라클서버 이리오라 오라미’,'오라’,'ORA’)
첫번째 글자중에 두번재글자는 새번째글자로 바꾸어라
FROM dual;
ROUND 함수
->반올림 함수
select 50.546,
ROUND(50.546),ROUND(50.546,0),
ROUND(50.546,1),ROUND(50.546,2),
ROUND(50.546,-1),ROUND(50.546,-2)
FROM dual
TRUNC 함수
->절삭 함수
select 50.546,
TRUNC (50.546),TRUNC (50.546,0),
TRUNC (50.546,1),TRUNC (50.546,2),
TRUNC (50.546,-1),TRUNC (50.546,-2)
FROM dual;
MOD(모디파이),CEIL(천장),FLOOR(바닥) 함수
-나머지를 구함
select 5/2,
mod(5,2), 나머지값을 구한다
ceil(5/2), 가장 가까운 큰정수
floor(5/2) 가장 가까운 작은 정수
from dual;
POWER함수
거듭제곱 (~승)
selecct ’2의 5승은’ || POWER(2,5)|| ‘이다’
from daul
결과값=> 2의 5승은32이다
SQRT 함수
제곱근(루트)
select SQRT(2),SQRT(3)
from dual;
SIN,COS,TAN 함수
-양수,음수,0인지를 구분
select sin(200),cos(200),tan(200),
asin(-0.9),asos(0.2),atan(0.99)
from dual;
LOG 함수
SELECT LOG(10,100) =>LOG10에 100
from dual;
select 20-15,
SIGN(20-15) ,SIGN(20-20) ,SIGN(15-20)
값이양수면 1 ,0이명 0 , 음수면 -1
from dual;
MONTHS_BETWEEN 함수
=>개월수에 차이를 구한다….
select months_between(sysdate,’2008-03-20′) 값=>6.40900873655914
개월수기준이다보니 소수점으로표기된다
from dual;
ADD_MONTHS 함수
select add_months(sysdate,3) 3개월 뒤
add_months(sysdate,-3) 3개월 전
from dual;
NEXT_DAY 함수
select sysdate,
next_day(sysdate,’금’), 앞에 날자이후로 가장먼저 돌아오는 금요일에 날자
next_day(sysdate,’월’) 앞에 날자이후로 가장먼저 돌아오는 월요일에 날자
from dual;
LAST_DAY 함수
SELECT LAST_DAY(sysdate)
from dual;
그달에 마지막 날수 구하기
변환 함수
number ——> char ——–> date
to_char to_date
date ——-> char ———–>number
to_char to_number
TO_CHAR ->숫자를 문자로
select ename, sal,
LTRIM (to_char(sal,’$9,999.99′))
첨에 콤마…뒤에 소수점 표시..
LTRIM (to_char(sal,’L9,999.99′))
from emp;
TO_CHAR ->날짜를 문자로
select sysdate,
to_char(sysdate,’yyyy’), 현재 날자에 년도
to_char(sysdate,’mm’), 현재 날자에 월
to_char(sysdate,’dd’), 현재 날자에 일수
to_char(sysdate,’hh’), 현재 시간에 시간
to_char(sysdate,’hh am’), 현재 시간에 시간 을 pm,am으로 표시 pm4
to_char(sysdate,’hh pm’), 현재 시간에 시간 을 pm,am으로 표시 pm4
to_char(sysdate,’hh24′), 현재 시간에 시간 24시로 표현 16시
to_char(sysdate,’mi’), 현재 시간에 분
to_char(sysdate,’ss’), 현재 시간에 초
to_char(sysdate,’sssss’) -이날 0시 0분부터 지금까지 초
from dual;
SELECT SYSDATE,
TO_CHAR(SYSDATE,’yy’), —문자형식
TO_CHAR(SYSDATE,’mm’), —문자형식
TO_CHAR(SYSDATE,’dd’), —문자형식
EXTRACT(year FROM sysdate), –숫자형식
EXTRACT(month FROM sysdate), –숫자형식
EXTRACT(day FROM sysdate) –숫자형식
FROM dual;
SELECT SYSDATE,
TO_CHAR(SYSDATE,’YEAR’), TWO THOUSAND EIGHT
TO_CHAR(SYSDATE,’MONTH’), 10월
TO_CHAR(SYSDATE,’DAY’), 수요일
TO_CHAR(SYSDATE,’DY’) 수
FROM DUAL;
TO_NUMBER –> 문자형의 숫자로 변환
SELECT TO_CHAR(SYSDATE,’DD’),
TO_NUMBER(TO_CHAR(SYSDATE,’DD’))
FROM DUAL;
TO_DATE –>문자를 날짜로 변환
SELECT SYSDATE-TO_DATE(’2008-09-20′)
FROM DUAL;
SELECT TO_DATE(’200809′,’YYYY-MM’)
원래는 뒤에 YYYY-MM-DD이것이 생략되어 있는것이다..
FROM DUAL;
CASE WHEN THEN ELSE END 연산자
Ex1)SELECT case 5-2
when 2 then ’5-2=2 입니다’ ->이것이 참이면 이것만 실행하고끝 거짓이면 아래로
when 3 then ’5-2=2 입니다’ ->참이면 ’5-2=2입니다’출력하고 끝 거짓이면 아래로
else ’5-2=난 몰라요’ -> 위에가 다거짓이면 else 값을 보낸다
end
from dual;
ex2)SELECT
case when 5<2 then’2는5보다 큽니다’’이것이 참이면 이것만 출력 거짓이면 아래로
WHEN 5>2 then ’5는 2보다 큽니다’ 이것이 참이면 이것만 출력 거짓이면 아래로
ELSE ’5와 2는 비교할수없네요’
END
FROM DUAL;
Ex3)SELECT case 5-2
when 3 then ’5-2+3 입니다’
SELECT case WHEN 5-2 IN(2,3.0) –in은 둘중에 하나만 만족하면 참입니다.
THEN ’5-2=3 입니다.’
ELSE ‘몰라요’
END
FROM dual;
TO_YMINTERVAL, TO_DSINTERVAL 함수
SELECT SYSDATE +TO_YMINTERVAL(’1-2′) + TO_DSINTERVAL(’3 4:5:6′)
–Y(년도) M(달) D(일)S(시,분,초)
FROM dual;
현재일로 부터 1년 2개월 3시간 4분 5초뒤를 구하자.
SELECT ADD_MONTHS(SYSDATE,14)+3+4/24+5/(24*60)+6/(24*60*60)
FROM dual;
RANK() over 함수와,DENSE_RANK() over
SELECT ename 사원명,sal 급여,
RANK() over(ORDER BY sal desc) “급여순위”,
DENSE_RANK() over(ORDER BY sal desc) “급여서열”
FROM EMP;
뷰테이블 기본 예제
SELECT T.ename 사원명,
T.job 직종,
T.sal 급여,
T.등수
FROM
(
SELECT ename,job,sal,
RANK() over(ORDER BY sal desc) “등수”
FROM EMP
) T
WHERE T. “등수” <=5;
그룹 함수와 group by 전 기본 개념 잡자
SELECT SUM(comm),AVG(comm),COUNT(comm).max(comm),min(comm)
합계 평균 행의갯수 최대값 최소값
FROM EMP;
SELECT VARIANCE(sal),STDDEV(sal),
POWER(STDDEV(sal),2),avg(sal)
FROM EMP;
Oracle Technical Note-오라클 옵티마이저의 기본 원리
0관계형 DBMS와 옵티마이저
21세기에 들어서도 여전히 관계형 DBMS가 데이타베이스 시장을 지배하고 있다.
그리고, 관계형 DBMS에서 사용되는 핵심 언어는 SQL(Structured Query
Language)이다. 이 SQL 언어의 가장 큰 특징은 사용자가 데이타베이스에서 자신
이 원하는 데이타(What)만 지정하면, 그 데이타를 어떻게 구하는가(How)는
DBMS가 자동적으로 결정해서 처리해 준다는 점이다.
이런 면에서 SQL을 선언적(declarative) 언어(주 1)라고 부르며, 사용자는 데이타
베이스의 물리적 구조의 변경에 상관 없이 항상 원하는 정확한 결과 데이타를 구할
수 있다. 이러한 물리적 데이타 독립성(physical data independence)이 관계형
DBMS를 상업적 성공으로 이끈 가장 큰 이유 중의 하나이다.
아무리 SQL이 이와 같은 장점을 갖고 있더라도, DBMS가 내부적으로 질의를 처리
하는 방식이 비효율적이라면 관계형 DBMS는 누구도 사용하지 않을 것이다. 다행히
도 현재의 모든 관계형 DBMS는 사용자의 SQL 질의를 효율적으로 수행하는 방법
을 찾아내는 옵티마이저(Query Optimizer : 혹자는‘질의 최적화기’라고도 부르는
데 이 글에서는‘옵티마이저’라 부르겠다.)를 제공하고 있다.
예를 들어, 다음과 같은 간단한 SQL 문을 보자.
Q1 : select ename, sal
from emp e, dept d
where e.deptno = d.deptno and d.loc = ‘SEOUL’
emp와 dept는 각각 deptno와 loc 칼럼에 대해 B 트리 인덱스가 있다고 가정한다.
이 같은 단순한 질의 Q1의 경우에도 질의 결과를 구하는 방법, 즉 실행 계획
(execution plan)은 다양할 수 있다.
< 그림 1 >은 두 가지 실행 계획 P1과 P2를 보여주고 있다. P1은 우선 loc =
‘SEOUL’조건을 만족하는 dept 레코드를 인덱스를 이용해서 찾고, 각 dept 레코
드에 대해 deptno 값이 일치하는 emp의 레코드를 인덱스를 이용해서 찾아 값을 출
력한다(Nested Loop 조인 방법 이용).

한편, P2는 emp/dept 테이블을 Full Table Scan해서 이들을 Sort Merge 조인
방식으로 조인해서 질의 처리를 수행한다. 주목할 점은, 이 두 실행 계획 모두 정확
한 질의 결과를 구하지만, 두 방식의 수행 시간에는 차이가 많이 날 수도 있다는 점
이다. 예를 들어, P1 방식은 1초에 원하는 결과를 구하는 반면, P2 방식은 1시간이
걸릴 수도 있다.
P1, P2 이외에도 질의 Q1을 수행할 수 있는 많은 실행 계획이 있을 수 있다. 실행
계획이란, 여러 개 테이블들의 조인에 대해, 특정한 1) 조인 순서(join ordering),
2) 조인 방법(join method), 그리고 3) 테이블 액세스 방법(access method)을 선
택하는 것이다.
옵티마이저는 가능한 실행 계획들을 모두 검토하고, 이 중에서 가장 효과적으로, 즉
가장 빨리, Q1의 결과를 구할 수 있는 실행 계획을 결정한다. 이 글에서는, 옵티마
이저가 최적의 실행 계획을 찾는 과정을‘질의 최적화(Query Optimization)’또
는 단순히‘최적화’라고 부르겠다.
관계형 DBMS 옵티마이저의 핵심 기능
관계형 DBMS 옵티마이저의 핵심 기능은 다음과 같다.
• 실행 계획 탐색(Search Space Enumeration) : 주어진 SQL 질의를 처
리할 수 있는 실행 계획들을 나열(P1, .., Pn) ?
• 비용 산정(Cost Estimation) : 각 실행 계획의 예상 비용을 계산
많은 실행 계획들 중에서 최종적으로 가장 비용이 적게 드는 실행 계획 Pi를 선택해
서 SQL을 실행하고 결과를 사용자에게 보여 준다.
실행 계획 탐색
예를 들어, 3개의 테이블, T1, T2, T3에 대해 조인을 수행하는 SQL 문이 있다고
가정하자. 그럼 이 질의를 수행할 수 있는 가능한 실행 계획은 몇 가지일까? 우리는
앞에서 조인 순서, 조인 방법, 그리고 테이블 액세스 방법에 따라 서로 다른 실행
계획이 만들어진다고 했다. 그렇다면, 3개의 테이블 T1, T2, T3에 대한 조인 순서
는 3!, 즉 6개의 조인 순서가 있다.
(T1§_T2)§_T3, (T1§_T3)§_T2, (T2§_T1)§_T3, (T2§_T3)§_T1, (T3§_T1)§_T2,
(T3§_T2)§_T1
그리고, 하나의 조인 순서에는 2개의 조인을 포함하는데, 이용 가능한 조인 방법이
Nested Loop, Sort Merge, Hash Join의 세 가지가 있다면, 각 조인 순서에 대
해 총 32, 즉 9개의 조합이 가능하다. 그리고, 이 각각의 경우 테이블을 접근하는
액세스 방법이 Full Table Scan과 Index Scan의 두 가지가 있다면 23, 즉 8개의
서로 다른 조합이 가능하다.
따라서, 3! x 32 x 23 = 432가지의 실행 계획이 가능하다. 그런데, 옵티마이저가
고려해야 할 실행 계획의 개수는 SQL에 포함된 테이블의 개수가 증가함에 따라 기
하급수적으로 늘어나게 된다. 만일 from 절의 테이블의 개수가 5개인 경우, 5! x
35 x 25 = 933,120개가 가능해진다.
<주 1> 엄밀하게는 SQL은 절차적(procedural) 언어의 요소를 포함하고 있다. SQL은 이론적으로 관계
대수(relational algebra)와 관계 해석(relational calculus)의 두 요소를 모두 포함하고 있고, 관계
대수는 절차적 언어이다. 따라서, SQL은‘상대적으로(relatively)’선언적 언어라 불러야 한다고 본
다.
그리고, 여기서 각 실행 계획의 예상 비용을 계산하는 데 걸리는 시간이 0.01초라고
가정했을 때, 모든 실행 계획의 예상 비용을 구하는 데 약 9,300초(약 2시간 36분)
이 걸린다. 만일 테이블의 개수가 10개라고 가정하면, 아마도 모든 실행 계획의 예
상 비용을 계산하는 데만도 몇 년이 걸릴지도 모른다.
21세기 IT 환경에서는 하나의 SQL 문에 5 ~ 10개 정도의 테이블이 포함되는 경우
가 일반적이다. 그런데, 옵티마이저가 실행 계획을 선정하는 데 걸리는 시간이 이와
같다면, 옵티마이저는 차라리 없는 것이 더 나을지도 모른다.
따라서, 옵티마이저는 모든 가능한 실행 계획을 다 고려할 수는 없다. 즉, 질의 최
적화에 걸리는 시간을 줄이기 위해 어떤 실행 계획들은 아예 비용 계산에서 제외해
야 할 필요도 있다. 옵티마이저는 모든 가능한 실행 계획 조합들을 탐색하는 방법 -
즉 어떤 실행 계획을 먼저 고려하고, 어떤 순서로 다음 실행 계획을 찾고, 어떤 실
행 계획은 제외할 것인가? – 을 갖고 있어야 한다.
비용 산정
앞의 실행 계획 탐색 단계에서 만들어내는 각각의 실행 계획에 대해, 그 실행 계획
을 실제로 수행할 때 비용 – 단순하게는 시간이 얼마나 걸릴지? – 을 예측해서, 가장
비용이 적은 실행 계획을 선택해야 한다.
이를 위해서 옵티마이저는 데이타베이스 내의 데이타들에 대해 갖고 있는 통계정보
와 비용을 예측하는 다양한 모델을 사용해서 각 실행 계획의 비용을 계산할 수 있어
야 한다.
여기서 주목할 점은, 옵티마이저가 실행 계획들을 비교할 때 사용하는 기준은‘예상
비용’이라는 점이다. 앞의 예에서 P1과 P2 방법을 실제로 수행해 보고 더 좋은 방
법을 결정하는 것이 아니라, 옵티마이저가 갖고 있는 통계정보를 활용해서 P1과 P2
로 수행했을 때 어느 실행 계획의 예상 비용이 작은가를 보고서 이를 실제로 수행하
게 되는 것이다.
Selinger 스타일의 옵티마이저
필자가 아는 한에서, 현재의 모든 상용 관계형 DBMS의 옵티마이저는 IBM DB2의
모태인 System-R 프로토타입 시스템을 개발할 당시에 고안된 아키텍처에 기반하고
있다<참고자료 4>. 이 아키텍처를 주도적으로 제안한 IBM의 여성 전산학자 Pat.
Selinger의 이름을 따서, ‘Selinger 스타일 옵티마이저’라 부른다.
참고로 Pat. Selinger의 논문은 아직까지도 데이타베이스 분야에서 가장 많이 인용
되는 논문 중의 하나이고, Pat. Selinger는 이 한 편의 논문으로 데이타베이스 연
구 분야에서 슈퍼스타의 반열에 올라섰다.
이 Selinger 스타일 옵티마이저 아키텍처의 가장 큰 두 가지 특징은 1) 동적 프로그
래밍 기반에 의한 실행 계획 탐색(Search Space Pruning based on Dynamic
Programming)과 2) 비용 기반 최적화(Cost-Based Optimization)인데, 각각 위
에서 나열한 옵티마이저 핵심 기능의 첫째, 둘째 기능에 해당된다.
옵티마이저의 이상과 현실
가장 이상적인 옵티마이저는, 모든 질의에 대해 옵티마이저가 선택한 실행 계획이
실제로 수행될 때도 가장 좋은 수행 속도를 보장하는 경우이다.
그러나, 현재의 옵티마이저는 비록 대부분의 경우에 상대적으로 아주 좋은 실행 계
획<주 2>을 선택하지만, 실제로는 아주 나쁜 실행 계획을 선택하는 경우도 있다. 현
재의 옵티마이저의 한계, 원인 그리고 앞으로의 개선 방향에 대해서는 뒤에서 자세
히 설명하겠다.
옵티마이저는 30년 이상 축적된 기술을 포함하고 있는, 인간의 지능이 가장 많이 녹
아 있는 복잡한 소프트웨어이다. 이 세상의 어떤 누구도 상용 관계형 DBMS 옵티
마이저의 복잡한 내부 동작 원리를 완전히 이해하고 있는 사람은 없다고 단언할 수
있다.
실제로 필자도 이 글에서 주로 설명할 오라클 옵티마이저에 대해서 어쩌면 기본적인
지식밖에 없다고 할 것이다. 다만, 많은 오라클 개발자나 관리자들이 현대의 옵티마
이저의 가장 기본적인 동작 원리를 쉽게 이해했으면 하는 마음으로 이 글을 썼다.
옵티마이저의 아키텍쳐
이제까지는 현재 보편적으로 사용되고 있는 관계형 DBMS 옵티마이저의 기능, 간단
한 역사적 배경, 그리고 동작 원리에 대해 간략히 알아보았다. 이제부터는 이러한
배경 지식을 바탕으로 Oracle DBMS의 옵티마이저의 기본 구조와 동작 원리에 대
해 알아보겠다.
오라클은 RBO(Rule-Based Optimization : 규칙기반 최적화)와 CBO(Cost-
Based Optimization : 비용기반 최적화)를 모두 지원하고 있다. CBO의 경우,
1992년 Oracle 버전 7부터 도입되었는데, 향후 이 글에서 오라클 옵티마이저라 함
은 CBO를 지칭하는 것이다. RBO는 간단한 규칙 위주로 최적화를 수행하는 방법으
로, 앞으로는 널리 사용되지 않을 것이며, 오라클도 공식적으로 CBO 사용을 권장하
고 있다.
| 그림 2 |는 오라클 옵티마이저의 아키텍처를 보여주고 있는데, 사용자의 SQL 질
의는 크게 다음 4단계를 거쳐서 수행된다.
1. 파싱(Parser)
2. 옵티마이저(Query Optimizer)
3. 로우소스 생성(Row Source Generator)
4. SQL 실행(SQL Execution Engine)
파싱(Parser) 단계는 SQL은 구문(syntax)과 의미(semantics) 검사를 수행한다.
예를 들어, SQL 구문이 정확한지를 검사하고, 참조된 테이블에 대해 사용자의 접근
권한 등을 검사한다. 이 단계가 끝나면, SQL 문은 파싱 트리(parsed tree) 형태로
변형되어 옵티마이저에게 넘겨진다.
<주 2> 어떤 실험에서는 80% 정도의 경우, 옵티마이저가 선택하는 실행 계획이 실제 수행했을 때도
결과가 가장 좋았다. 나머지 20%의 경우에, 옵티마이저가 선택한 실행 계획은 평균적으로 세 번째로
시간이 많이 걸렸다. 이 실험 전체에 걸쳐서 가장 빠른 실행 계획과 옵티마이저가 선택한 실행 계획의
수행 시간은 1.33배 정도였다.
옵티마이저(Query Optimizer) 단계는 앞에서 넘겨받은 파싱 트리를 이용해서 최
적의 실행 계획을 고른다.
| 그림 2 |에서 점선 형태의 사각형으로 표시된 부분이 옵티마이저의 주요 구성 요
소를 보여주고 있는데, 뒤에서 각 구성 요소의 역할에 대해 자세히 설명하겠다.

획을 내부적으로 처리하는 자세한 방법을 생성하는 단계이다. ‘로우 소스’란 실행
계획을 실제로 구현하는 인터페이스 각각을 지칭하는 말로, 테이블 액세스 방법, 조
인 방법, 그리고 정렬(sorting) 등을 위한 다양한 로우 소스가 제공된다. 따라서,
이 단계에서는 실행 계획에 해당하는 트리 구조의 로우 소스들이 생성된다.
마지막으로, SQL 실행(SQL Execution Engine) 단계는 위에서 생성된 로우 소스
를 SQL 수행 엔진에서 수행해서 결과를 사용자에게 돌려주는 과정이다.
여기서 한 가지 주목할 점은, 소프트 파싱(soft parsing)과 하드 파싱(hard
parsing)은 크게 옵티마이저 단계의 포함 여부에 따른 차이이다. 즉, 소프트 파싱은
이미 최적화를 한 번 수행한 SQL 질의에 대해 옵티마이저 단계와 로우 소스 생성
단계를 생략하는 것이고, 하드 파싱은 이 두 단계를 새로 수행하는 것이다. 따라서,
하드 파싱은 통계정보 접근과 실행 계획 탐색 때문에 시간이 많이 걸린다. 이 차이
가 주로 SQL 튜닝 전문가들이 가급적이면 하드 파싱을 피하라고 권하는 이유이다.
오라클 옵티마이저의 동작 원리
이제부터는 오라클 옵티마이저의 각 구성 요소의 기능에 대해 좀 더 자세히 알아
보자. | 그림 2 |에서 보듯이, 오라클 옵티마이저는 크게 다음 3가지 모듈로 구
성된다.
• 질의 변환(Query Rewriter)
• 실행 계획 생성(Plan Generator)
• 비용 산정(Estimator)
질의 변환(Query Rewriter 또는 Transformer) 단계는 파싱 트리(parsed tree)
를 받아들여서 질의 변환을 수행한다. 이 변환 과정을 통해서 의미적으로 같은 결과
를 수행하지만, 더 나은 실행 계획을 찾을 수 있는 SQL 문으로 변환함으로써 질의
의 수행 처리 속도를 높이는 데 그 목적이 있다. 오라클 옵티마이저가 수행하는 질
의 변환은 크게 다음 두 종류로 구분할 수 있다.
• 휴리스틱(Heuristic based) 질의 변환 : 이 변환의 종류로는 크게 View
Merging, Subquery Unnesting, Predicate Push Down, Partition
Pruning 등이 있는데, 이들 변환은 가능한 경우에 항상 질의 변환을 수행
한다. 왜냐하면, 이와 같은 변환은 경험적으로 거의 항상 원래 질의보다
더 빠른 수행 속도를 보장하기 때문이다.
• 비용 기반(Cost based) 질의 변환 : 이 변환의 예로는, MV Rewrite,
Star Query Transformation, OR-expansion 등을 들 수 있다. 그런
데, 이 방법을 사용해서 변환된 SQL 문이 원래 SQL 문보다 속도가 더
빠르다는 보장이 없다. 따라서, 변환 전/후의 두 SQL 문에 대해 각각 최
선의 실행 계획을 구하고, 이들의 비용을 비교해서 더 효율적인 실행 계획
을 최종적으로 선택한다.
오라클의 질의 변환 모듈에서 지원하는 다양한 변환의 종류와 내용에 대해서는 <참
고자료 2, 3>을 참고하기 바란다.
질의 변환 단계가 끝나면, 오라클 옵티마이저는 실행 계획 생성과 비용 산정 모듈을
수행하기 앞서, 질의에서 사용된 모든 테이블들과 각 테이블에 정의된 인덱스들에
관한 기본적인 통계정보들(예를 들어, 테이블의 블록 개수, 로우 평균 길이, 인덱스
의 높이, 인덱스 리프 블록의 개수 등)과 각 테이블에 대한 다양한 액세스 경로(예
를 들어, Full Table Scan, Index Scan 등)에 대한 비용 정보를 미리 구해 둔다.
실행 계획 생성 모듈
이 모듈은 옵티마이저가 새로운 실행 계획을 만드는 것이다. 오라클 옵티마이저는
제일 먼저 각 테이블의 레코드 수를 기준으로 오름차순으로 결정한다. 예를 들어,
SQL 질의의 from 절에서 T1, T2, T3 순서로 참조한 경우, 각 테이블의 카디널러
티(cardinality : 테이블의 튜플 수)가 T1 > T2 > T3 순이라면 제일 처음 고려하
는 조인 순서는 (T3§_T2)§_T1 이 된다. 이 조인 순서에 대해서 다음 단계인 비용
산정 모듈을 호출해서 이 조인 순서에 따르는 실행 계획들과 각 실행 계획의 비용을
구한다.
그리고, 더 이상의 새로운 조인 순서가 없을 때까지 계속 새로운 조인 순서를 만들
어서 비용을 계산한다. 이 모듈은 지금까지 찾아낸 가장 좋은 실행 계획과 그 비용
을 저장하고 있다. 이 단계는 최종적으로 구해진 최적의 실행 계획을 | 그림 2 |의
로우 소스 생성 단계에 넘겨준다.

에는 모든 조인 순서에 대해 고려하지만, 테이블 개수가 이 값을 넘어서면 where
절에 명시적으로 조인 조건이 테이블들을 앞에 포함하는 조인 순서만 고려한다. 예
를 들어, 6개의 테이블 T1, T2, … , T6에 대한 조인을 수행하는 SQL 문에서 조
인 조건이 T1, T2, T5, T6에 대해서만 주어졌다면, T1, T2, T5, T6가 먼저 조인
되고, T3, T4는 항상 나중에 조인되는 조인 순서만 고려한다.
그런데, 이런 경우에도, 앞에서 언급한 것처럼, 테이블의 개수가 많으면 가능한 조
인 순서의 조합이 기하급수적으로 늘어나게 된다. 이렇게 되면 옵티마이저 시간이
너무 많이 걸리기 때문에, 옵티마이저는 일정한 수(디폴트로는 최대 80,000)의 조인
순서에 대해서만 비용을 계산하고, 이 중에서 가장 최선의 실행 계획을 찾게 된다.
즉, 모든 가능한 조인 순서 조합들 중에서 일부분만 비용을 계산하고, 나머지는 고
려하지 않는 것이다. 이를 실행 계획 탐색에 대한‘가지치기(pruning)’또는‘컷오
프(cutoff)’라 부른다.
그런데, 고려되지 않은 조인 순서 중에서 실제로 최선의 실행 계획이 포함되어 있을
차순 순서로 정하는 이유는 경험적으로 이 순서 근처에 실제로 최적의 실행 계획이
존재하기 때문이다. 이와 같이 초기 조인 순서를 선택하는 휴리스틱(heuristic)을
사용함으로써 임의로 조인 순서를 시작했을 때 최적의 좋은 실행 계획이 컷오프되는
것을 막을 수 있다.
오라클 옵티마이저 실행 계획 생성 모듈(Oracle9i부터 도입된)의 또 다른 특징은,
조인 순서를 바꾸어가면서 지금까지 구한 최적의 실행 계획의 예상 비용이 그리 크
지 않은 경우, 최적화 단계를 일찍 끝내버린다.
예를 들어, 어떤 질의에 대해 10초 동안 최적화를 수행해서 찾은 최적 실행 계획의
예상 수행 시간이 1분이면, 남은 조인 순서가 더 있더라도 옵티마이저 단계를 종료
한다. 반면에, 지금까지 구한 최적 예상 수행 시간이 2시간이면, 더 나은 실행 계획
을 찾기 위해 새로운 조인 순서에 대해 계속 탐색할 필요가 있다. 이를‘적응적 탐
색 전략(adaptive search strategy)’이라 부른다.
비용 산정 모듈
자, 그럼 다음으로 비용 산정 모듈에 대해 알아보자. 실행 계획 생성 모듈에서 넘겨
받은 특정 조인 순서의 각 조인에 대해 Nested Loop, Sort Merge, Hash Join
방식과 각 테이블의 다양한 액세스 방법을 반복 적용하면서 각 단계별로 비용을 계
산해서 궁극적으로 해당 조인 순서에서 찾을 수 있는 최선의 실행 계획과 그 예상
비용을 구해서 실행 계획 생성 모듈에게 넘겨 준다.
현재의 조인 순서에 대해 중간 단계까지의 수행 비용이 실행 계획 생성 모듈에서 지
금까지 구한 최선의 예상 비용보다 더 크다면, 해당 조인 순서에 대해서는 더 이상
비용 산정을 수행하지 않고 끝낸다. 예를 들어, T1, T2, T3에 대해 (T1§_T2)§_T3
순서에 대해 비용이 1000이었는데, (T§_T3)§_T2 순서의 (T1§_T3) 비용이 1200이
었다면 더 이상 비용을 계산할 필요가 없다.
| 그림 2 |에 나와 있는 것처럼, 옵티마이저는 실행 계획의 비용을 계산하기 위한
비용 모델(Cost Model)을 갖고 있고, 이 비용 모델은 Oracle Data Dictionary에
서 관리하는 다양한 통계정보를 기반으로 크게 다음과 같은 세 가지 값(measure)의
예상치를 계산한다.

• 선택도(Selectivity) : Where 절에 있는 다양한 조건들의 선택도 계산
• 카디널러티(Cardinality) : 실행 계획상의 각각의 연산의 결과 카디널러
티 수 계산
• 비용(Cost) : 실행 계획상의 각각의 연산을 수행하는 데 소요되는 시간 비
용 계산
이 비용 산정을 위한 통계정보를 저장하는 Data Dictionary 테이블들은
DBA_TABLES, DBA_INDEXES, DBA_TAB_COL_STATISTICS, DBA_
HISTOGRAMS 등이다. 이 통계정보는 앞에서 언급한 테이블의 액세스 경로의 비
용 정보를 결정하는 데도 사용된다.
이들 테이블의 정보는 사용자가 ANALYZE 명령어나 DBMS_STATS 패키지를 이
용해서 관리하게 되는데, 이들 테이블에서 관리하는 통계정보의 종류와 통계정보를
수집/관리하고, 통계정보를 확인하는 자세한 방법은 이 글에서는 설명하지 않겠다<
참고자료 5>.
만일에 테이블과 인덱스에 대한 통계정보가 존재하지 않는 경우, 옵티마이저는 해당
테이블과 인덱스에 대해 디폴트로 가정하는 값들이 있다<참고자료 5>.
• 선택도
우선 선택도(selectivity)의 개념을 예로 들자. 앞에서 예로 든 질의 Q1에서 d.loc
= ‘SEOUL’이라는 조건의 선택도는 dept 테이블 전체 중에서 loc의 값이
‘SEOUL’인 레코드의 비율을 일컫는다. 옵티마이저는 선택도 계산을 통해서 해당
조건을 만족하는 레코드가 몇 건 정도가 되는지를 예측하게 된다.
옵티마이저는 만일 DBA_TABLES에 dept 테이블의 loc 칼럼의 distinct column
values가 10이라면 옵티마이저는 선택도가 0.1이라고 판단하게 된다. 이때 선택도
를 이와 같이 정하는 이유는 dept 테이블이 loc 칼럼들에 골고루 분포되어 있다고
가정할 때 성립한다. 그러나, 실제로 loc 칼럼의 값들이 skew되어서 분포할 수도
있다.
예를 들어, 전체 레코드의 50%가 loc 값으로‘SEOUL’을 갖는다면 잘못된 선택도
값을 얻게 된다. 이와 같이 데이타 분포가 skew되어 있는 경우, 해당 칼럼에 대한
히스토그램 정보를 DBA_HISTOGRAM 테이블에 만들어 주어야 정확한 선택도 값
을 계산할 수 있다(이 경우는 0.5). 오라클 옵티마이저는 다양한 조건식의 종류에
대해 선택도를 통계정보에 기반해서 계산하는 수식을 내부적으로 갖고 있다.
그렇지만, 만일 dept 테이블이 아직 분석되지 않아서 통계정보가 없는 경우, 옵티마
이저는 내부적으로 갖고 있는 디폴트 값을 선택도로 지정한다(예를 들어, 0.01).
• 카디널러티
앞의 dept 테이블의 전체 레코드 건수가 1000일 때, 앞에서 설명한 loc =
‘SEOUL’의 선택도가 0.1로 계산되었을 때, 조건을 만족하는 레코드 건수는 1000
x 0.1, 즉 100개로 예상할 수 있다. 이와 같이 어떤 연산을 수행한 결과로 나오는
레코드 건수를‘카디널러티(cardinality)’라 하는데, 정확한 카디널러티를 계산하는
것은 좋은 실행 계획을 만드는 데 굉장히 중요하다.
인할 때 어떤 조인 방법을 선택하는 것이 좋을지를 결정하기 위해서는 (T1§_T2)의
크기를 정확하게 알아야 한다. 이를 위해서는 (T1§_T2) 조인의 결과 레코드가 몇
개인지를 예상할 수 있어야 한다.
이를 위해 오라클 옵티마이저는 다양한 연산의 결과 레코드의 카디널러티를 통계정
보와 수식에 의해서 계산한다. T1과 T2의 조인 조건이 T1.c1 = T2.c2(이를‘P’라
표기)라 했을 때, 앞에서 설명한 선택도 계산 공식에 의해 이 조건식의 선택도
Sel(P)를 먼저 계산한 후, 이 조인의 결과 카디널러티는 Card(T1) x Card(T2) x
Sel(P)가 된다.
예를 들어, T1, T2의 튜플 수가 각각 1000, 5000이고 Sel(P)가 0.01이면, 조인의
결과로 생기는 튜플 수는 1000 x 5000 x 0.01 = 5000이 된다. 그런데, Sel(P)가
조금이라도 틀리면 이후의 전체적인 비용 산정이 잘못되게 된다. 오라클 옵티마이저
는 다양한 종류의 연산에 대해 내부 공식을 사용해 카디널러티를 계산한다.
• 비용
비용(cost)은 테이블 액세스, 조인 등을 수행하는 데 걸리는 시간을 의미하는데, 시
간은 주로 디스크 I/O 수와 CPU 사용시간을 고려한다. 비용은 앞에서 계산한 통계
정보와 내부 계산식에 의해 계산된다.
예를 들어, T1§_T2를 Nested Loop 방식으로 조인할 경우 조인비용은 (T1의 데이
타 블록수) + ((T1의 레코드 건수)*(T2의 액세스 비용))이 된다. 이처럼 오라클 옵
티마이저는 모든 연산에 대해 소요되는 비용을 계산하는 수식을 갖고 있다.
오라클 옵티마이저는 이 세 가지 예상 값(measure)을 기반으로, 현재의 실행 계획
의 예상 비용을 구한다.
오라클 옵티마이저와 관련한 몇 가지 유용한 기능
이상에서 오라클 옵티마이저의 내부 동작 원리를 살펴보았다. 옵티마이저와 관련해
서 오라클에서 제공하는 몇 가지 유용한 기능들에 대해서 간단히 알아보자(이들 기
능에 대한 자세한 설명은 <참고자료 3>을 보기 바란다).
이 기능들은 크게 두 가지 – 즉, 옵티마이저가 사용할 통계정보를 수집/관리하는 기
능과 옵티마이저의 활동을 자세히 추적할 수 있는 기능 – 로 구분할 수 있다.
먼저, 통계정보 수집/관리 기능으로는 ANALYZE 명령과 DBMS_ STATS 패키지
를 들 수 있다. 비용 계산이 최적의 실행 계획을 구하는 데 중요한 역할을 하기 때
문에, 이 기능을 사용해서 1) 어떤 테이블이나 칼럼에 변경사항이 많이 발생해서 새
로 통계정보를 분석해야 하는지, 2) 어떤 칼럼에 대해 히스토그램을 만들어야 하는
지에 대한 도움을 받을 수 있다.
다음으로 옵티마이저의 활동 추적과 관련해서, 1) 주어진 질의에 대해서 어떠한 최
적화 과정을 거쳤는지, 2) 최종적으로 어떤 실행 계획을 선택했는지, 그리고, 선택
된 실행 계획대로 수행했을 때 걸리는 시간과 자원이 얼마나 소요되었는지를 확인하
는 기능들이 제공된다. 우선 옵티마이저의 최적화 과정을 확인하려면, ‘Event
10053’을 이용하면 된다. 이를 위해서는 SQL*Plus에서 다음 alter 명령을 수행하
면 된다.SQL> alter session set events ‘10053 trace name context
forever’;
이 명령을 수행하고 나면, 현재 세션에서 수행하는 모든 질의에 대해 옵티마이저의
최적화 과정의 모든 정보가 $ora_home/admin/udump /xxx.trc 파일에 기록된
다. 이 트레이스 파일은 오라클 옵티마이저가 고려한 모든 조인 순서, 조인 방법,
테이블 액세스 방법, 선택도, 카디널러티, 비용 정보 등을 포함하고 있다.
다음으로, 단순히 옵티마이저가 최종적으로 선택한 실행 계획만 확인하고 싶으면,
EXPLAIN 명령어나 SQL*Plus에서 제공되는 Autotrace 기능을 이용하면 된다.
그리고, 옵티마이저가 선택해서 수행한 실행 계획의 자세한 성능 정보를 알고 싶으
면, SQL Trace, TKPROF 등의 기능을 이용하면 된다.
오라클 옵티마이저의 한계와 그 원인
오라클 옵티마이저를 포함한 현재의 관계형 DBMS의 옵티마이저는 항상 최적의 실
행 계획을 고르지는 못한다. 옵티마이저의 한계는 실행 계획 생성 모듈과 비용 산정
모듈의 동작 원리에 그 원인이 숨어 있다.
실행 계획 생성 모듈의 제약
우선, 실행 계획 생성 모듈에서 최적화를 위해 사용할 수 있는 시간이 제한적이라는
점이다. 앞서 살펴보았지만, 10개 이상의 테이블 조인을 포함하는 질의의 경우 최적
의 실행 계획을 구하기 위해 옵티마이저가 고려해야 할 탐색 공간이 너무 많기 때문
에 다양한 형태의 컷오프를 수행한다. 이 과정에서 실제로 최적의 실행 계획이 고려
되지 않고 잘려나갈 수 있다.
비용 산정 모듈의 불완전성
비용 산정 모듈에서는 특정 실행 계획의 비용을 통계정보와 내부적인 비용 산정 모
델을 사용해서 계산한다. 그런데, 옵티마이저에서 사용하는 통계정보와 비용 산정
모델이 불완전하다. 따라서, 옵티마이저는 불완전한 정보를 바탕으로 일종의 추측
(또는 가정)을 하는 것이다.
예를 들어, d.loc = ‘SEOUL’의 선택도를 구하는 과정을 보자. d.loc에 대한 히스
토그램 통계정보가 없으면, 옵티마이저는‘모든 값들이 골고루 분포되어 있다’는 가
정하에 d.loc 칼럼의 distinct value 개수(이를 NDV라 하자)를 기준으로 해당 조
건의 선택도를 1/NDV로 계산한다. 그러나, 실제로는 d.loc에 대해 skew된 분포를
보이면 옵티마이저의 실행 계획 비용 산정이 틀려지게 된다.
비용 산정 모듈이 한계를 갖게 되는 또 다른 예로, SQL에서 바인드 변수(bind
variables)의 사용을 들 수 있다. 질의 Q1에서 d.loc = ‘SEOUL’대신에 d.loc =
:loc_name 조건이 사용되었으면, 데이타베이스에 loc 칼럼에 아무리 정확한 통계치
를 갖고 있어도 선택도에 대해서는 일정한 비율을 가정할 수밖에 없다.
다른 예로서, 다음 질의를 살펴보자.
Q2: select *
from emp
where job_title = ‘vice_president’and salary < 40000
데이타베이스에는 job_title, salary 칼럼 모두에 대해 정확한 히스토그램 정보를 유
지하고 있고, job_title = ‘vice_president’의 선택도가 0.05이고, salary < 40000
의 선택도는 0.4였다. 이때 옵티마이저는 emp 테이블에서 where 절의 조건의 전
체 선택도를 0.05 x 0.4, 즉 0.02로 계산한다. 이는‘각 칼럼의 값들의 분포는 서
로 독립적이다’는 가정에 기반하다.
그러나, 부사장이면서 연봉이 40,000 이하인 경우는 거의 없기 때문에 실제 선택도
는 0에 가까울 것이다. 결국 앞의 가정은 이와 같이 서로 밀접한 상관관계가 있는
두 칼럼에 대한 선택도를 구할 때 문제가 되는 것이다.
마지막 예로, 조인 연산에 대한 비용을 예측할 때, 이 조인을 수행할 수 있는 메모
리 공간을 고정 크기로 가정하고, Nested Loop, Sort Merge, Hash Join의 비용
을 산정한다. 그러나, 질의를 수행할 때 실제 비용은 이용 가능한 메모리의 양에 따
라 크게 차이가 날 수 있다.
결론적으로, 옵티마이저의 정확도는 비용 계산의 정확도에 따라 좌우되는데, 참고하
는 통계정보가 부족하거나 계산 과정의 몇 가지 가정들이 실제 데이타 분포와 실행
계획의 런타임 환경과 차이가 있기 때문에 정확도에 문제가 발생하는 것이다.
힌트 기능을 이용한 옵티마이저 동작 제어
이와 같은 현재의 옵티마이저의 한계를 보완하기 위해, 오라클에서는 SQL에 힌트
(hint)를 추가해서 사용자가 옵티마이저가 선택하는 실행 계획에 영향을 줄 수 있도
록 하고 있다.
옵티마이저가 최선이 아니 차선의 실행 계획을 선택하는 경우, 사용자가 SQL에 힌트
를 주어서 실행 계획을 베스트 플랜으로 만들도록 하는 것이 목적이다. 힌트를 제공
하는 것이 옵티마이저의 기능이 떨어지는 것을 의미하는 것은 아니다. 어떤 DBMS의
옵티마이저도 완전할 수는 없기 때문에, 힌트 기능의 제공은 반드시 필요하다.
옵티마이저의 실행 계획은 결국 조인 순서, 조인 방법, 테이블 액세스 경로를 결정
하는 것이기 때문에, 힌트의 종류도 크게 이 세 가지를 제어하는 것으로 구분할 수
있다.
다음 예는 Q1에 대해 힌트를 사용한 예를 보여주고 있는데, 처음 ‘ordered’는
from 절에 나와 있는 순서대로 조인 순서를 정하는 것이고, ‘use_nl’의 경우 dept
테이블을 inner table로 사용할 때 Nested Loop 방식만을 사용하도록 지정하고,
full(e)는 emp 테이블은 항상 Full Table Scan을 통해서 액세스하도록 지정하는
것이다.
오라클에서 제공하는 다양한 힌트의 종류와 자세한 의미에 대한 설명은 <참고자료
5>를 보기 바란다.
Q1 : select /*+ ordered use_nl(d) full(e) */ ename, sal : Oracle 힌트 기
능 사용 예
from emp e, dept d
where e.deptno = d.deptno and d.loc = ‘SEOUL’
오라클 SQL에서 힌트를 제공하는 또 다른 목적은, 사용자가 다양한 실행 계획을 수
행해 봄으로써 어떤 데이타 액세스 경로가 도움이 되는지를 테스트해 볼 수도 있다.
힌트의 사용은 아주 불가결한 경우 말고는 사용을 조심해야 한다. 실제로 이 힌트
기능이 남용되는 경우가 많다.
힌트를 사용하게 됨으로써 데이타베이스 환경의 변화(예를 들어, 테이블의 크기 변
화, 인덱스의 추가/삭제)가 발생할 때 옵티마이저가 더 나은 실행 계획을 선택하는
것을 방해할 수도 있다. 실제로 Oracle E-Business Suite 11i의 경우 포함된 27만
개의 SQL 중에서 0.3%만이 힌트를 포함하고 있다고 한다.
SQL 튜닝과 옵티마이저의 관계
SQL 튜닝은 특정 SQL 질의의 수행 시간을 단축하기 위해 사용자가 취하는 다양한
방법을 통칭한다. SQL 튜닝의 범위는 굉장히 포괄적인데, 옵티마이저와 관련한 방
법으로는 SQL 재작성, 힌트 사용, 새로운 인덱스 추가, 통계 데이타의 추가/갱신
등을 통해서 옵티마이저가 더욱더 효율적인 실행 계획을 생성하도록 하는 것이다.
• SQL 재작성
사용자가 원하는 데이타를 질의하는 방법은 실제로 매우 다양할 수 있다. 극단적인
예로, C. J. Date는 한 SQL 문을 50가지 이상의 다른 SQL 문으로 표현이 가능함
을 보여 준다(http://www.dbpd.com/vault/9807xtra.htm 참조). SQL 재작성
을 통한 SQL 튜닝은 원래의 SQL 문을, 같은 결과를 내지만, 옵티마이저가 더 효과
적인 실행 계획을 생성할 수 있는 SQL 문으로 바꾸는 방법이다.
• 힌트 사용
앞에서 언급한 것처럼, 힌트 기능을 사용해서 옵티마이저가 선택하는 실행 계획을
바꾸는 방법이다.
• 새로운 인덱스 추가
SQL 문의 효율적인 처리를 위해서는 특정 테이블의 특정 칼럼 값을 이용해서 해당
데이타를 빨리 찾아야 하는데, 인덱스가 없기 때문에 옵티마이저가 어떤 실행 계획
을 선택하더라도 그 SQL 문은 느릴 수밖에 없는 경우가 있다. 이와 같은 상황에서
는 새로운 인덱스 생성을 통해서 옵티마이저가 해당 인덱스를 이용하는 새로운 실행
계획을 선택하도록 할 수 있다.
• 통계 데이타의 추가/갱신
앞에서 설명한 것처럼, 오라클 옵티마이저의 비용 산정 모듈에서는 테이블, 칼럼,
인덱스 등에 대한 통계정보를 이용해서 선택도, 카디널러티 등을 구하고 이를 통해
서 궁극적으로 실행 계획의 비용을 계산한다.
그런데, 만일 특정 테이블/칼럼에 대한 통계정보가 없거나, 오래 전에 만들어진 경
우는 비용 계산이 부정확하게 되고, 따라서 옵티마이저가 선택하는 실행 계획이 실
제로는 안 좋은 실행 계획일 수가 있다.
이를 해결하기 위해서는 특정 통계정보를 추가하거나 새로 갱신해 주어서 옵티마이
저가 정확한 비용 산정을 통해서 더 나은 실행 계획을 선택하도록 해주는 방법이다.
옵티마이저 기술의 발달은 궁극적으로 SQL 튜닝 관련 직종을 없앨 수도 있다. 그
러나, 다행인지 불행인지 몰라도, 향후 10년 사이에 이런 일이 벌어지지는 않을
것 같다.
향후 옵티마이저의 기술의 발전 방향
비록 옵티마이저 기술은 지난 30년간 꾸준히 발전해오면서 인간이 만든 가장 지능적
인 소프트웨어이지만, 앞으로도 끊임없이 기술 발전이 필요한 분야이다.
사용자가 사용하는 SQL 질의가 점점 더 복잡해지고, 데이타베이스에서 다루는 데이
타 양이 엄청난 속도로 늘어나고, 새로운 데이타의 종류를 데이타베이스에서 다루어
야 하기 때문에, 옵티마이저 기술의 중요성은 더욱 더 커질 것이다.
향후 옵티마이저 기술의 주요 발전 방향은 다음의 분야가 될 것이다. 여기서 나열한
분야는 주로 학계에서 연구가 활발히 진행중이거나 많은 진전이 있는 분야를 중심으
로 판단한 필자의 개인적인 의견이다.
• 질의 변환
오라클 옵티마이저와 관련해서 간략히 설명했지만, 현재의 옵티마이저가 처리하는
질의변환의 형태는 상대적으로 정형화되고 단순한 형태의 질의 변환만을 주로 수행
한다. 단일 SQL 블록(Select-From-Where)에 대한 질의변환 이외에, 복잡한 중첩
질의(nested query)를 단일 질의로 변환하는 방법, 중첩질의 내의 각 SQL 블록을
결합한 효과적인 실행 계획 생성이 가능해질 것이다.
• 비용 산정을 위한 정확한 통계정보 관리
실행 계획에 대한 정확한 비용 산정이 옵티마이저 기술의 핵심이다. 따라서, 지금
옵티마이저가 참고하는 통계정보보다 더 정교하고 복잡한 통계정보의 관리/유지 기
법들이 도입될 것이다.
예를 들어, 애트리뷰트 값들의 분포가 서로 독립적이라는 가정 대신에 상호 연관성
이 깊은 칼럼들에 대한 히스토그램 정보를 효과적으로 수집/활용하는 기술이 도입될
수도 있다.
• 런타임시 동적 질의 최적화
현재의 옵티마이저 기술은, 질의 수행 환경에 상관없이 옵티마이저가 선택한 실행
계획을 그대로 실행한다는 측면에서 정적(static) 질의 최적화 방법이다. 앞으로는
고정된 실행 계획을 그대로 수행하는 것이 아니라, SQL 실행 단계의 상황에 따라
실행 계획을 융통성 있게 바꾸는 기술이 개발될 것이다. 실제로 Oracle9i의 경우 초
보적인 형태의 동적 질의 최적화 기능을 제공하고 있다.
• 학습하는 옵티마이저
현재의 옵티마이저 기술은 통계정보의 변화나 사용자의 힌트가 없다면, 같은 SQL
질의에 대해서는 항상 똑같은 실행 계획을 선택할 것이다. 옵티마이저가 특정 질의
에 대해 생성한 실행 계획을 실제 수행했을 때, 예상과 달리 좋지 않은 성능을 보이
면, 옵티마이저가 다음 번에 최적화를 수행할 때는 이전의 실행 계획을 제외한 다른
대안을 찾게 되는 것이다.
참고자료
1. Ken Jacobs, Query Optimization, Oracle Magazine 2002 July/August
(http://www.oracle.com/oramag/oracle/02-jul /o42dba.html)
2. Oracle Corp., Query Optimization in Oracle9i, Technical White Paper
(http://otn.oracle.com/products/bi/pdf/o9i_optimization_twp.pdf)
3. Oracle Corp., Oracle9i Performance Tuning Guide and Reference Release 2(9.2)
(http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/server.920/a96533/toc.htm)
4. Patricia Selinger 외 다수, Access Path Selection in a Relational Database System, ACM SIGMOD 1979
5. Surajit Chaudhuri, An Overview of Query Optimization in Relational Systems, AMM PODS Tutorial 1998v
6. Yannis E. Ioannidis, Query Optimization, Handbook for Computer Science(Chapter 45), CRC Press
7. Hector Garcia-Molina, Jeffrey D. Ullman, Jennifer Widom, Database Systems: The Complete Book,
Prentice Hall, 2001
8. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems(2nd Edition), McGraw-Hill,
1999
9. Abraham Silberschatz, Henry F. Korth and S. Sudarshan, Database System Concepts(4th edition),
McGraw-Hill, 2001
SELECT 연습…날짜 함수…
0테이블 생성…반드시 실행 후 아래 예제 볼것…
/** 날짜 함수 **/
– GETDATE() 현재 날짜, 시간 가져오기
SELECT GETDATE()
– 현재 날짜에 12년을 더하라..
SELECT DATEADD(YY, 12, GETDATE())
– 현재 날짜에 23개월을 더하라..
SELECT DATEADD(MM, 23, GETDATE())
– 현재까지 몇일을 살았는지 출력하라..(자신의 생년월일을 기준)
SELECT DATEDIFF(DD, ’1974-11-15′, GETDATE())
– 이 날짜가 무슨 요일이냐…
SELECT DATENAME(DW, ’2004-12-24′) – 문자반환
SELECT DATEPART(DW, ’2004-12-24′) – 숫자반환
SELECT DATENAME(YY, GETDATE()) + ‘년’ – 문자 반환이므로 연결 연산이 된다.
SELECT DATEPART(YY, GETDATE()) + ‘년’ – 숫자 반환이므로 에러 발생..
SELECT YEAR(GETDATE()); – 년도 반환
SELECT MONTH(GETDATE()); – 월 반환
SELECT DAY(GETDATE()); – 일 반환
– 사원 테이블에서 입사일이 3200일 이상 근무한 직원들만 급여의 20%를 인상하여 출력하라..
/*
사원명 직위 입사일 근무일수 인상급여
——————————————————–
엄정화 사원 1995년12월12일 10111일 1200000
*/
SELECT
SANAME ‘사원명’,
SAJOB ‘직위’,
DATENAME(YY, SAHIRE) + ‘년’ + DATENAME(MM, SAHIRE) + ‘월’ + DATENAME(DD, SAHIRE) + ‘일’ AS ‘입사일’,
STR(DATEDIFF(DD, SAHIRE, GETDATE())) + ‘ 일’ AS ‘근무일수’,
CONVERT(INT, SAPAY*1.2) ‘인상급여’
FROM
SAWON
WHERE
DATEDIFF(DD, SAHIRE, GETDATE()) >= 3200
– 사원 테이블에서 입사요일이 일요일에 입사한 직원을 출력하라..
/*
사원 직위 입사일 입사요일
————————————–
*/
SELECT
SANAME ‘사원’,
SAJOB ‘직위’,
SAHIRE ‘입사일’,
DATENAME(DW, SAHIRE) ‘입사요일’
FROM
SAWON
WHERE
DATENAME(DW, SAHIRE) = ‘일요일’
– 직원중에 입사월이 12월달에 입사한 직원의 모든 정보를 출력하라.
SELECT
*
FROM
SAWON
WHERE
MONTH(SAHIRE) = 12;
– 직원중에 1995년에서 1999년 사이에 입사한 직원의 정보를 모두 출력하라
SELECT
*
FROM
SAWON
WHERE
YEAR(SAHIRE) >= 1995 AND YEAR(SAHIRE) <= 1999;
– SAHIRE >= ’1995-01-01′ AND SAHIRE <= ’1999-01-01′; 데이타 가공이 없으므로 더 빠르다…
– 우리 회사는 입사일로 25년 이후에 정년퇴직이다..모든 직원의 정년 퇴직일을 출력하라
/*
이름 직위 입사일 정년퇴직일 정년퇴직요일
———————————————————–
엄정화 사원 2002년12월12일 2027년12월12일 월요일
*/
SELECT
SANAME ‘이름’,
SAJOB ‘직위’,
DATENAME(YY, SAHIRE) + ‘년’ + DATENAME(MM, SAHIRE) + ‘월’ + DATENAME(DD, SAHIRE) + ‘일’ AS ‘입사일’,
DATENAME(YY, DATEADD(YY, 25, SAHIRE)) + ‘년’ + DATENAME(MM, DATEADD(YY, 25, SAHIRE)) + ‘월’ + DATENAME(DD, DATEADD(YY, 25, SAHIRE)) + ‘일’ AS 정년퇴직일,
DATENAME(DW, DATEADD(YY, 25, SAHIRE)) AS ‘정년퇴직요일’
FROM
SAWON;
Installing Oracle Database 10g on Linux x86
0Installing Oracle Database 10g on Linux x86
by John Smiley
Learn the basics of installing Oracle Database 10g on RHEL 2.1, RHEL 3, or SLES-8, from the bare metal up (for evaluation only)
Overview
Part I: Installing Linux
RHEL 2.1
RHEL 3
SLES-8
Part II: Configuring Linux for Oracle
Verify System Requirements
Create Directories
Create the Oracle Groups and User Account
Configure Linux Kernel Parameters
Set Shell Limits for the oracle User
Avoid the Bug! (SLES-8 Only)
Environment Variables for the oracle User
Part III: Installing Oracle
Install the Software
Part IV: Configuring Storage
Filesystems
Automatic Storage Management
Conclusion
Appendix
This is the first in a series of guides that provide all the steps for installing the major components of Oracle 10g software on Linux. All three of the certified English-language distributions of Linux are covered in detail (Asianux is not covered), and the articles assume that inexpensive Intel x86 hardware is being used. The articles walk through the process of installation and configuration on commodity hardware for the purpose of evaluating the major Oracle 10g products.
The ultimate goal of this series is to walk through installing and configuring all of the components of a 10g Grid. Along the way, you will see how to install and configure a single instance Oracle 10g database (this article), a two-node Oracle RAC 10g database, all the major components of Oracle Application Server 10g and Oracle Enterprise Manager 10g Grid Control.
This series will take the approach of offering the easiest paths, with the fewest number of steps, for accomplishing a task. This approach often means making configuration choices that would be inappropriate for anything other than an evaluation. For that reason, this series is not appropriate for building production-quality environments, nor does it reflect best practices.
The three Linux distributions certified for Oracle 10g covered in these articles are:
- Red Hat Enterprise Linux 2.1
- Red Hat Enterprise Linux 3
- Novell SUSE Linux Enterprise Server 8
This article is divided into four parts: Part I covers the installation of the Linux operating system, Part II covers configuring Linux for Oracle, Part III discusses the essentials of installing the Oracle Database, and Part IV covers creating additional filesystems and introduces Automatic Storage Management (ASM)—a terrific new feature in Oracle Database 10g that greatly simplifies storage administration and management. The Appendix provides information to help you get started using your new database including how to access the database interactively and how to stop and start the database and related services.
This guide assumes a server with the following hardware:
- Two 800MHz Pentium III CPUs
- 512MB of RAM
- Two SCSI host adapters (Ultra SCSI 160)
- Eight SCSI disk drives (2 x 9GB + 6 x 36GB)
- One 100Base-T Ethernet adapter
- One 1000Base-T Ethernet adapter
The disks are configured so that each SCSI host adapter is connected to one 9GB disk and three 36GB disks.
Note that although this is far from a “beefy” setup, much of what this guide covers can be accomplished with even less horsepower. All that is necessary for a basic database install is a single CPU, 512MB of RAM, and one disk drive (IDE, SCSI, or FireWire) with at least 6.5GB of free space.
Now, let’s walk through the process of installing the Linux operating system on a server. The instructions assume a fresh install of Linux (as opposed to an upgrade), that the server will be dedicated to Oracle, and that no other operating systems or data are on the server.
Oracle 10g is certified to run on Red Hat Enterprise Linux 2.1 (Advanced Server and Enterprise Server) with Update 3 or higher. Updates are available from the Red Hat Network (RHN) and can be downloaded as ISO files for creating CDs or as individual package updates.
The easiest and fastest way to apply the updates for a fresh install of Linux is to perform the install by using the update CDs. If Linux is already installed or you don’t have the updates on CDs, they can be applied through RHN. Because this guide is designed for a fresh Linux install, you’ll use the update CDs.
- Boot the server using the first CD in the set of update CDs.
- You may need to change your BIOS settings to allow booting from the CD.
- The boot screen appears with the boot: prompt at the bottom of the screen.
- Select Enter to continue with a graphical install on the console. (For other installation methods and options, refer to the Red Hat Installation Guide.)
- The installer scans your hardware, briefly displays the Red Hat splash screen, and then begins a series of screen prompts.
- Language Selection
- Accept the default.
- Keyboard Configuration
- Accept the default.
- Mouse Configuration
- Accept the default.
- Installation Type
- Accept the default.
- Disk Partitioning Setup
- A thorough treatment of disk partitioning is beyond the scope of this article, which assumes that you are familiar with disk partitioning methods.
(WARNING: Improperly partitioning a disk is one of the surest and fastest ways to wipe out everything on your hard disk. If you are unsure how to proceed, stop and get help, or you will risk losing data!)
This article uses the following partitioning scheme, with ext3 for each filesystem:
The 9GB disk on the first controller (/dev/sda) will hold all Linux and Oracle software and contains the following partitions:
- 100MB /boot partition (50MB is the minimum for RHEL 2.1)
-1,500MB swap partition—Set this to at least twice the amount of RAM in the system but to no more than 2GB (32-bit systems do not support swap files larger than 2GB). If you need more than 2GB of swap space, create multiple swap partitions.
-7,150MB root partition—This partition will be used for everything, including /usr, /tmp, /var, /opt, /home, and more. This was done purely to simplify installation for the purposes of this guide. A more robust partitioning scheme would separate these directories onto separate filesystems.
- A thorough treatment of disk partitioning is beyond the scope of this article, which assumes that you are familiar with disk partitioning methods.
- Boot Loader Configuration
- Accept the default.
- Boot Loader Password Configuration
- If you would like to use a password for GRUB, enter it here. For an evaluation system, just leave this unset.
- Network Configuration
- It is usually best to configure database servers with a static IP address. To do so, uncheck Configure using DHCP and enter the network configuration for the server. Be sure you’ve entered a host name and that Activate on boot is checked.
- Firewall Configuration
- For the purposes of this walk-through, no firewall is configured. Select No firewall (security administrators, flame away).
- Additional Language Support
- Accept the default.
- Time Zone Selection
- Choose the time settings that are appropriate for your area. Setting the system clock to UTC is usually a good practice for servers. To do so, click on System clock uses UTC.
- Account Configuration
- Choose a password for root, and enter it in the fields provided. Create an account for yourself. (Do not create the oracle account at this time; that happens later.)
- Package Group Selection
- Choose either Gnome of KDE (or both) of the graphical user interfaces (Gnome being the default). Note: Both GUIs are very popular, with Gnome being more prevalent in the U.S. I personally prefer KDE, because the terminal emulator provides for easy cut and paste and offers the ability to duplicate input to multiple connections (this saves typing when you are configuring RAC on multiple nodes, for example).
- Select Software Development
- Unresolved Dependencies
- If you see this screen, simply select Install packages to satisfy dependencies (the default) and proceed.
- Graphical Interface (X) Configuration
- Accept the defaults unless the installer does not recognize your video card. If your video card is not recognized, you will not be able to continue.
- Preparing to install
- Click on Next
- Installing packages
- Software will be copied to the hard disk and installed. Change disks as prompted, and click on Next when the installation is complete.
- Boot disk creation
- Create a boot disk if you like, or select Skip boot disk creation.
- Monitor Configuration
- Accept the default if the installer correctly identifies your monitor. Otherwise, select a compatible monitor from the list.
- Congratulations
- Remove the installation media from the system, and click on Next.
Verifying Your Installation
If you’ve completed the steps above, you should have all the packages and updates required for Oracle 10g. However, you can take the steps below to verify your installation.
Required kernel version: 2.4.9-e.25 (or later)
Check your kernel version by running the following command:
uname -rOther required package versions (or later):Ex:
# uname -r
2.4.9-e.27smp
- gcc-2.96-124
- make-3.79
- binutils-2.11
- openmotif-2.1.30-11
- glibc-2.2.4-31
rpm -q gcc make binutils openmotif glibcIf any of the package versions on your system are missing or the versions are earlier than those specified above, you can download and install the updates from the Red Hat Network.Ex:
# rpm -q gcc make binutils openmotif glibc
gcc-2.96-118.7.2
make-3.79.1-8
binutils-2.11.90.0.8-12
openmotif-2.1.30-11
glibc-2.2.4-32.8
Oracle 10g is certified to run the base release of Red Hat Enterprise Linux 3 (Advanced Server and Enterprise Server) without updates. If you have update CDs, you can use the boot CD from the update instead of the boot CD from the base release to automatically apply all updates during the installation. All updates from Red Hat are supported by Oracle.
- Boot the server using the first CD.
- You may need to change your BIOS settings to allow booting from the CD.
- The boot screen appears with the boot: prompt at the bottom of the screen.
- Select Enter to continue with a graphical install on the console. (For other installation methods and options, refer to the Red Hat Installation Guide.)
- The installer scans your hardware, briefly displays the Red Hat splash screen, and then begins a series of screen prompts.
- Language Selection
- Accept the default.
- Keyboard Configuration
- Accept the default.
- Welcome Screen
- Click on Next.
- Mouse Configuration
- Accept the default.
- Installation Type
- Select Custom.
- Disk Partitioning Setup
- A thorough treatment of disk partitioning is beyond the scope of this article, which assumes that you are familiar with disk partitioning methods.
(WARNING: Improperly partitioning a disk is one of the surest and fastest ways to wipe out everything on your hard disk. If you are unsure how to proceed, stop and get help, or you will risk losing data!)
This article uses the following partitioning scheme, with ext3 for each filesystem:
The 9GB disk on the first controller (/dev/sda) will hold all Linux and Oracle software and contains the following partitions:
- 100MB /boot partition
-1,500MB swap partition—Set this to at least twice the amount of RAM in the system but to no more than 2GB (32-bit systems do not support swap files larger than 2GB). If you need more than 2GB of swap space, create multiple swap partitions.
-7,150MB root partition— This partition will be used for everything, including /usr, /tmp, /var, /opt, /home, and more. This was done purely to simplify installation for the purposes of this guide. A more robust partitioning scheme would separate these directories onto separate filesystems.
- A thorough treatment of disk partitioning is beyond the scope of this article, which assumes that you are familiar with disk partitioning methods.
- Boot Loader Configuration
- Accept the default.
- Network Configuration
- It is usually best to configure database servers with a static IP address. To do so, click on Edit.
- A pop-up window appears. Uncheck the Configure using DHCP box, and enter the IP Address and Netmask for the server. Be sure that Activate on boot is checked, and click on OK.
- In the Hostname box, select manually and enter the hostname.
- In the Miscellaneous Settings box, enter the remaining network settings.
- Firewall Configuration
- For the purposes of this walk-through, no firewall is configured. Select No firewall.
- Additional Language Support
- Accept the default.
- Time Zone Selection
- Choose the time settings that are appropriate for your area. Setting the system clock to UTC is usually a good practice for servers. To do so, click on System clock uses UTC.
- Set Root Password
- Enter a password for root, and enter it again to confirm.
- Package Group Selection
- Select only the package sets shown here. Leave all others unselected.
- Desktop
- X Window System
- Gnome
- KDE
- See my comments in the RHES 2.1 section regarding choice of GUI.
- Applications
- Editors
- Graphical Internet
- Servers
- Do not select anything in this group.
- Development
- Development Tools
- System
- Administration Tools
- Red Hat Enterprise Linux
- Do not select anything in this group.
- Miscellaneous
- Legacy Software Development
- Click on Next to proceed.
- About to Install
- Click on Next.
- Installing Packages
- Software will be copied to the hard disk and installed. Change disks as prompted, and click on Next when the installation is complete.
- Graphical Interface (X) Configuration
- Accept the defaults unless the installer does not recognize your video card. If your video card is not recognized, you will not be able to continue.
- Monitor Configuration
- Accept the default if the installer correctly identifies your monitor. Otherwise, select a compatible monitor from the list.
- Customize Graphical Configuration
- Accept the defaults.
- Congratulations
- Remove the installation media from the system, and click on Next.
- The system automatically reboots and presents a new welcome screen.
- Click on Next.
- License Agreement
- Read the license agreement. If you agree to the terms, select Yes, I agree to the License Agreement and click on Next.
- Date and Time
- Set the Date and Time.
- If you want to use an NTP server (recommended), select Enable Network Time Protocol and enter the name of the NTP server.
- User Account
- Create an account for yourself.
- Do not create an account for oracle at this time. Creating the oracle account is covered later in this section.
- Red Hat Network
- If you want to use or activate your Red Hat Network account now, accept the default, click on Next, and follow the product activation instructions that accompanied your Red Hat product.
- Additional CDs
- Click on Next.
- Finish Setup
- Click on Next.
- A graphical login screen appears.
- Congratulations! Your Linux software is now installed.
If you’ve completed the steps above, you should have all the packages and updates required for Oracle 10g. However, you can take the steps below to verify your installation.
Required kernel version: 2.4.21-4.EL (This is the kernel version shipped with the base release of RHEL 3. This kernel, or any of the kernels supplied in updates, works with Oracle 10g.)
Check your kernel version by running the following command:
uname -rOther required package versions (or later):Ex:
# uname -r
2.4.21-4.0.1.ELsmp
- gcc-3.2.3-2
- make-3.79
- binutils-2.11
- openmotif-2.2.2-16
- setarch-1.3-1
- compat-gcc-7.3-2.96.122
- compat-gcc-c++-7.3-2.96.122
- compat-libstdc++-7.3-2.96.122
- compat-libstdc++-devel-7.3-2.96.122
- compat-db-4.0.14.5 (listed in the Oracle 10g Database Installation Guide as required but not needed here)
rpm -q gcc make binutils openmotif setarch compat-db compat-gcc \Note that the compat-db package is not installed. This package is not available from any of the package groups available during installation and must be installed in a separate step. If any of the other package versions on your system are missing or the versions are earlier than those specified above (other than compat-db), you can download and install the updates from the Red Hat Network.
compat-gcc-c++ compat-libstdc++ compat-libstdc++-develEx:
# rpm -q gcc make binutils openmotif setarch compat-db compat-gcc \
> openmotif compat-gcc-c++ compat-libstdc++ compat-libstdc++-devel
gcc-3.2.3-20
make-3.79.1-17
binutils-2.14.90.0.4-26
openmotif-2.2.2-16
setarch-1.3-1
package compat-db is not installed
compat-gcc-7.3-2.96.122
compat-gcc-c++-7.3-2.96.122
compat-libstdc++-7.3-2.96.122
compat-libstdc++-devel-7.3-2.96.122
Installing compat-db
Insert CD2 of the original Red Hat Enterprise Linux media. (This package has not been updated as of Update 2 and is found only on the original media.)
The CD mounts automatically.
Run the following command as root:
rpm -ivh /mnt/cdrom/RedHat/RPMS/compat-db-4.0.14-5.i386.rpmEx:
# rpm -ivh /mnt/cdrom/RedHat/RPMS/compat-db-4.0.14-5.i386.rpm
Preparing… ########################################### [100%]
1:compat-db ########################################### [100%]
SUSE Linux Enterprise Server 8
Oracle 10g is certified to run on Novell SUSE Linux Enterprise Server (SLES) 8 and SLES-9. Service Packs and package updates are available from Novell, either on CDs or online via its support portal. In this guide, we will install on SLES-8 with Service Pack 3 from CDs.
- Boot the server, using the SLES-8 CD.
- You may need to change your BIOS settings to allow booting from the CD.
- The SUSE Linux Enterprise Server installation screen appears.
- Select Installation.
- The installer scans your hardware and presents the YaST interface.
- Language Selection
- Accept the license agreement.
- Accept the default, English (US).
- Installation Settings
- Select New Installation.
- Partitioning
- A thorough treatment of disk partitioning is beyond the scope of this article, which assumes that you are familiar with disk partitioning methods.
(WARNING: Improperly partitioning a disk is one of the surest and fastest ways to wipe out everything on your hard disk. If you are unsure how to proceed, stop and get help, or you will risk losing data!)
This article uses the following partitioning scheme, with ext3 for each filesystem:
The 9GB disk on the first controller (/dev/sda) will hold all Linux and Oracle software and contains the following partitions:
- 100MB /boot partition
-1,500MB swap partition—Set this to at least twice the amount of RAM in the system but to no more than 2GB (32-bit systems do not support swap files larger than 2GB). If you need more than 2GB of swap space, create multiple swap partitions.
-7,150MB root partition—this partition will be used for everything, including /usr, /tmp, /var, /opt, /home, and more. This was done purely to simplify installation for the purposes of this guide. A more robust partitioning scheme would separate these directories onto separate filesystems.
- A thorough treatment of disk partitioning is beyond the scope of this article, which assumes that you are familiar with disk partitioning methods.
- Software
- Click on the link for Software.
- The Software Selection screen appears.
- Click on Detailed Selection.
- The left-hand window displays a list of software selections. Click on the box next to each selection to select/deselect it.
- Select the following software (this is the recommended set; all others should be deselected):
- C/C++ Compiler and Tools
- KDE (or Gnome)
- LSB Runtime Environment
- Help & Support Documentation
- Graphical Base System
- YaST2 config modules
- SLES Administration Tools
- It is recommended that the following items not be installed, as they may conflict with Oracle products providing the same service:
- Simple Webserver
- Authentication Server (NIS, LDAP, Kerberos)
- Time Zone
- Set your time zone.
- Click on Accept.
- A warning box appears. Click on Yes, install when ready to proceed.
- Change CDs as prompted by the installer.
- When the software has been installed, a window will appear advising that the base system has been successfully installed.
- Remove the installation CD, and click on OK.
- The system reboots.
- Enter a password for root, and repeat to confirm.
- Create an account for yourself. Do not create the oracle account at this time; we’ll do that later.
- Desktop Settings
- Accept the default.
- A warning window appears regarding automatic detection of local printers.
- Click on Skip detection.
- Configure your network interface(s), and click on Next when ready to proceed.
- Static IP addresses are recommended for servers.
- There is no need to configure printers, modems, ISDN adapters, or sound in order to build a database.
- A graphical login screen appears.
- Now you need to install Service Pack 3. Log in as yourself.
- Insert the update CD, and click on Patch CD Update.
- Start YaST2, SUSE’s system administration tool.
- Select SUSE > System > YaST2. (SUSE is the round green button with the smiling lizard face in profile at the bottom left of the screen. It means “Start.”)
- A window appears, prompting for the root password. Enter the password, and click on OK.
- The YaST Control Center appears.
- The YaST Online Update window appears.
- Accept the defaults, and click on Next.
- A window appears with a list of patch updates.
- YaST needs to update itself first before updating the rest of the system. The needed packages are already selected. Do not select any other packages at this point.
- Click on Accept.
- A window appears advising to restart the online update.
- Click on OK.
- A window appears, stating that the installation was successful.
- Click on OK.
- In the YaST Online Update window, click on Finish.
- In the YaST Control Center window, click on Close.
- Repeat steps 21 and 22.
- A window appears with a list of patch updates.
- Click on Accept, to accept the defaults.
- Small pop-up windows may appear with various advisories, such as “Make sure you update sendmail.” Click on OK to dismiss them.
- This step takes a while. Hover your cursor over the Next button. If the update is still running, a clock icon will appear.
- A window appears, reporting that the installation was successful.
- Click on OK.
- On the YaST Online Update screen, click on Next.
- The installer writes the system configuration.
- In the YaST Control Center, click on Close.
- Log out.
- SUSE > Logout.
- Remove the update CD.
- Reboot the system.
- On the graphical login screen, click on Menu.
- Select Shutdown.
- Select Restart computer.
- Enter the root password.
- Click on OK.
- Congratulations! Your Linux software is now installed.
If you’ve completed the steps above, you should have all the packages and updates required for Oracle 10g. However, you can take the steps below to verify your installation.
Required kernel version: 2.4.21-138 (or later)
Check your kernel version by running the following command:
uname -rOther required package versions (or later):Ex:
# uname -r
k_smp-2.4.21-138
- gcc-3.2.2-38
- make-3.79
- binutils-2.12
- openmotif-2.2.2-124
rpm -q gcc make binutils openmotifIf any of the package versions on your system are missing or the versions are earlier than those specified above, you can download and install the updates from the SUSE Linux Portal.Ex:
# rpm rpm -q gcc make binutils openmotif
gcc-3.2.2-38
make-3.79.1-407
binutils-2.12.90.0.15-50
openmotif-2.2.2-124
Part II: Configuring Linux for Oracle
Now that the Linux software is installed, you need to configure it for Oracle. This section walks through the steps required to configure Linux for Oracle Database 10g.
To verify that your system meets the minimum requirements for an Oracle 10g database, log in as root and run the commands below.
grep MemTotal /proc/meminfo
grep SwapTotal /proc/meminfoEx:
# grep MemTotal /proc/meminfo
MemTotal: 512236 kB
# grep SwapTotal /proc/meminfo
SwapTotal: 1574360 kB
The minimum RAM required is 512MB, and the minimum required swap space is 1GB. Swap space should be twice the amount of RAM for systems with 2GB of RAM or less and between one and two times the amount of RAM for systems with more than 2GB.
You also need 2.5GB of available disk space for the Oracle 10g software and another 1.2GB for the database. The /tmp directory needs at least 400MB of free space. To check the available disk space on your system, run the following command:
df -hEx:
# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 6.8G 1.3G 5.2G 20% /
/dev/sda1 99M 17M 77M 18% /boot
The example shows that the /tmp directory does not have its own filesystem. (It’s part of the root filesystem for this guide.) With 5.2 GB available, the root filesystem has just enough space for the installation (2.5 + 1.2 + 0.4 = 4.1GB) with a little room left over.
Create the Oracle Groups and User Account
Next, create the Linux groups and user account that will be used to install and maintain the Oracle 10g software. The user account will be called oracle, and the groups will be oinstall and dba. Execute the following commands as root:
/usr/sbin/groupadd oinstall
/usr/sbin/groupadd dba
/usr/sbin/useradd -m -g oinstall -G dba oracle
id oracleEx:
# /usr/sbin/groupadd oinstall
# /usr/sbin/groupadd dba
# /usr/sbin/useradd -m -g oinstall -G dba oracle
# id oracle
uid=501(oracle) gid=501(oinstall) groups=501(oinstall),502(dba)
Set the password on the oracle account:
passwd oracleEx:
# passwd oracle
Changing password for user oracle.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
Now create directories to store the Oracle 10g software and the database files. This guide adheres to the Optimal Flexible Architecture (OFA) for the naming conventions used in creating the directory structure. For more information on OFA standards, see Appendix D of the Oracle Database 10g Installation Guide for UNIX Systems.
The following assumes that the directories are being created in the root filesystem. This is done for the sake of simplicity and is not recommended as a general practice. These directories would normally be created as separate filesystems.
Issue the following commands as root:
mkdir -p /u01/app/oracle
mkdir -p /u02/oradata
chown -R oracle:oinstall /u01/app/oracle /u02/oradata
chmod -R 775 /u01/app/oracle /u02/oradataEx:
# mkdir -p /u01/app/oracle
# mkdir -p /u02/oradata
# chown -R oracle:oinstall /u01/app/oracle /u02/oradata
# chmod -R 775 /u01/app/oracle /u02/oradata
Configuring the Linux Kernel Parameters
The Linux kernel is a wonderful thing. Unlike most other *NIX systems, Linux allows modification of most kernel parameters while the system is up and running. There’s no need to reboot the system after making kernel parameter changes. Oracle Database 10g requires the kernel parameter settings shown below. The values given are minimums, so if your system uses a larger value, don’t change it.
kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
If you’re following along and have just installed Linux, the kernel parameters will all be at their default values and you can just cut and paste the following commands while logged in as root.
cat >> /etc/sysctl.conf <<EOF
kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
EOF
/sbin/sysctl -pEx:
# cat >> /etc/sysctl.conf <<EOF
> kernel.shmall = 2097152
> kernel.shmmax = 2147483648
> kernel.shmmni = 4096
> kernel.sem = 250 32000 100 128
> fs.file-max = 65536
> net.ipv4.ip_local_port_range = 1024 65000
> EOF
# /sbin/sysctl -p
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
kernel.sysrq = 0
kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
Run the following commands as root to verify your settings:
/sbin/sysctl -a | grep shm
/sbin/sysctl -a | grep sem
/sbin/sysctl -a | grep file-max
/sbin/sysctl -a | grep ip_local_port_rangeEx:
# /sbin/sysctl -a | grep shm
kernel.shmmni = 4096
kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shm-use-bigpages = 0
# /sbin/sysctl -a | grep sem
kernel.sem = 250 32000 100 128
# /sbin/sysctl -a | grep file-max
fs.file-max = 65536
# /sbin/sysctl -a | grep ip_local_port_range
net.ipv4.ip_local_port_range = 1024 65000
If any of the parameters on your system are set lower than those shown, edit the /etc/sysctl.conf file and add or change the parameters. When you’re finished, run the following command to activate the changes:
/sbin/sysctl -p
For SLES-8 only, run the following command after completing the step above.
/sbin/chkconfig boot.sysctl on
Setting Shell Limits for the oracle User
Oracle recommends setting limits on the number of processes and open files each Linux account may use. To make these changes, cut and paste the following commands as root:
cat >> /etc/security/limits.conf <<EOF
oracle soft nproc 2047
oracle hard nproc 16384
oracle soft nofile 1024
oracle hard nofile 65536
EOFcat >> /etc/pam.d/login <<EOF
session required /lib/security/pam_limits.so
EOF
For RHEL 2.1 and 3, use the following:
cat >> /etc/profile <<EOF
if [ \$USER = "oracle" ]; then
if [ \$SHELL = "/bin/ksh" ]; then
ulimit -p 16384
ulimit -n 65536
else
ulimit -u 16384 -n 65536
fi
umask 022
fi
EOFcat >> /etc/csh.login <<EOF
if ( \$USER == “oracle” ) then
limit maxproc 16384
limit descriptors 65536
umask 022
endif
EOF
For SLES-8, use the following:
cat >> /etc/profile.local <<EOF
if [ \$USER = "oracle" ]; then
if [ \$SHELL = "/bin/ksh" ]; then
ulimit -p 16384
ulimit -n 65536
else
ulimit -u 16384 -n 65536
fi
umask 022
fi
EOFcat >> /etc/csh.login.local <<EOF
if ( \$USER == “oracle” ) then
limit maxproc 16384
limit descriptors 65536
umask 022
endif
EOF
There is a bug in the installation of Oracle Enterprise Manager 10g on SLES-8 that causes it to fail due to required ports that are reserved in /etc/services. The OEM DBConsole needs port 1830, and in SLES8 environments, this port is already reserved in /etc/services. This bug is documented on MetaLink as bug# 3513603.
To avoid problems during the installation, log in as root and comment out the lines for ports 1830 through 1849 in the /etc/services file prior to installing the Oracle 10g software. (Note: It’s probably a good idea to reboot the server at this point, to ensure that the above changes are in effect.)
Environment Variables for the oracle User
Several environment variables should or must be set in order to use Oracle products. For the database server, the recommended environment variables are:
ORACLE_BASE
ORACLE_HOME
ORACLE_SID
PATH
If you have more than one Oracle product or database on the same server, the ORACLE_HOME, ORACLE_SID, and PATH variables may change. The ORACLE_BASE variable should not change and can be set in your login profile if you want. Oracle provides a utility, called oraenv, for setting the remaining variables.
Log in as oracle and add ORACLE_BASE to your login profile by adding the following line to your .bash_profile or .profile (bash or ksh):
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
or add this line to your .login (csh):
setenv ORACLE_BASE /u01/app/oracle
This change will take effect the next time you log in to the oracle account. To make the changes active for the current session, simply run the command from the command line.
Oracle Database 10g can be downloaded from OTN. Oracle offers a development and testing license free of charge. However, no support is provided and the license does not permit production use. A full description of the license agreement is available on OTN.
The easiest way to make the Oracle 10g distribution media available on your server is to download them directly to the server.
Use the graphical login to log in as oracle.
Create a directory to contain the Oracle 10g distribution:
mkdir 10g_db
To download Oracle Database 10g from OTN, point your browser (Mozilla works well) to http://www.oracle.com/technology/software/products/database/oracle10g/htdocs/linuxsoft.html. Fill out the Eligibility Export Restrictions page, and read the OTN License agreement. If you agree with the restrictions and the license agreement, click on I Accept.
Click on the ship.db.cpio.gz link, and save the file in the directory you created for this purpose (10g_db)—if you have not already logged in to OTN, you may be prompted to do so at this point.
Unzip and extract the file:
cd 10g_db
gunzip ship.db.cpio.gz
cpio -idmv < ship.db.cpio
Log in using the oracle account.
Specify the database name (ORACLE_SID). This is usually five characters or fewer. Use demo1 for this installation.
Set the environment variables:
- Borne and Korn shells
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
ORACLE_SID=demo1; export ORACLE_SID
- C shell
setenv ORACLE_BASE /u01/app/oracle
setenv ORACLE_SID demo1
Ex:
$ cd $HOME/10g_db
Change directory to Disk1.
Ex:
$ cd Disk1
Start the Oracle Universal Installer.
$ ./runInstaller
- Welcome
- Click on Next.
- Specify Inventory Directory and Credentials
- If you’ve been following the steps in this guide, the defaults will be correct. If not, edit the path to the inventory directory to point to the correct directory.
- The operating system group name should be oinstall.
- If this is the first time Oracle has been installed on this machine, you will get a pop-up window indicating that the orainstRoot.sh script needs to be run as root. Log in as root, cd to the directory specified in the window, and execute the script before proceeding.
- Specify File Locations
- If you’ve been following the steps in this guide, the defaults will be correct. Otherwise, make sure that the Source path and the Destination path is correct before proceeding.
- Select Installation Type
- Accept the default of Enterprise Edition.
- Product-specific Prerequisite Checks
- If you’ve been following the steps in this guide, all the checks should pass without difficulty. If one or more checks fail, correct the problem before proceeding.
- Select Database Configuration
- Accept the defaults of Create a starter database and General Purpose.
- Specify Database Configuration Options
- Enter the global database name for your database. This should include ORACLE_SID followed by the domain name for the server (for example, demo1.orademo.org, where demo1 is the ORACLE_SID and orademo.org is the domain name).
- The SID box fills in automatically when you enter the Global Database Name.
- Accept the default Database Character Set.
- Select Create database with sample schemas.
- Select Database Management Option
- Select Use Database Control for Database Management.
- Specify Database File Storage Option
- Select File System, and enter the pathname to be used for the database files (/u02/oradata, in this case).
- Specify Backup and Recovery Options
- Select Do not enable Automated backups.
- Specify Database Schema Passwords
- Select Use the same password for all the accounts.
- Choose a password and enter it twice to confirm.
- Summary
- A summary of the products being installed is presented.
- Click on Install.
- Install
- This screen progresses through several stages as the Oracle software is being installed and linked.
- A pop-up window appears at the end of the installation process, displaying configuration information. Make note of the Enterprise Manager URL and click OK to dismiss the window.
- A “Setup Privileges” pop-up window appears, indicating that a configuration script needs to be run as root. Log in as root, cd to the directory indicated in the window, and execute the root.sh script. The script prompts for the location of the local bin directory. Accept the default by pressing Enter. When the script completes, return to the Setup Privileges window and click on OK. (See below.)
- End of Installation
- Make note of the URLs presented in the summary, and click on Exit when ready.
- Congratulations! Your new Oracle 10g database is up and ready for use.
|
The database we created in Part III used a single filesystem (/u02/oradata) for disk storage. However, there are several ways to configure storage for an Oracle database.
Part IV explores other methods of configuring disk storage for this database. In particular, it describes creating additional filesystems and using Automatic Storage Management (ASM). Use of raw devices and Oracle Cluster File System (OCFS) is deferred until another article in this series, which covers the creation of a cluster database using Oracle Real Application Clusters (RAC).
Filesystems are the most widely used means of storing data file, redo logs, and control files for Oracle databases. Filesystems are easy to implement and require no third-party software to administer.
In most cases, filesystems are created during the initial installation of Linux. However, there are times when a new filesystem must be created after the initial installation, such as when a new disk drive is being installed.
This section describes building a new filesystem and using it in an Oracle database. Unless otherwise noted, all commands must be run as root.
Partition the Disk
You must have an empty disk partition to create the filesystem. If you already have an empty disk partition available, skip to the next step.
The following shows an example of creating a new partition for a Linux filesystem. (WARNING: Improperly partitioning a disk is one of the surest and fastest ways to wipe out everything on your hard disk. If you are unsure how to proceed, stop and get help, or you will risk losing data.)
This example uses /dev/sdb (an empty SCSI disk with no existing partitions) to create a single partition for the entire disk (36 GB).
Ex:
# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel. Changes will remain in memory only,
until you decide to write them. After that, of course, the previous
content won’t be recoverable.The number of cylinders for this disk is set to 4427.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)Command (m for help): p
Disk /dev/sdb: 255 heads, 63 sectors, 4427 cylinders
Units = cylinders of 16065 * 512 bytesDevice Boot Start End Blocks Id System
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-4427, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-4427, default 4427):
Using default value 4427Command (m for help): w
The partition table has been altered!Calling ioctl() to re-read partition table.
WARNING: If you have created or modified any DOS 6.x
partitions, please see the fdisk manual page for additional
information.
Syncing disks.
Now verify the new partition:
Ex:
# fdisk /dev/sdbThe number of cylinders for this disk is set to 4427.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)Command (m for help): p
Disk /dev/sdb: 255 heads, 63 sectors, 4427 cylinders
Units = cylinders of 16065 * 512 bytesDevice Boot Start End Blocks Id System
/dev/sdb1 1 4427 35559846 83 LinuxCommand (m for help): q
Create the Filesystem
Use ext3 to create this new filesystem. Other filesystems work just as well, but ext3 offers the fastest recovery time in the event of a system crash.
Ex:
# mke2fs -j /dev/sdb1
mke2fs 1.26 (3-Feb-2002)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
4447744 inodes, 8889961 blocks
444498 blocks (5.00%) reserved for the super user
First data block=0
272 block groups
32768 blocks per group, 32768 fragments per group
16352 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632,
2654208, 4096000, 7962624Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: doneThis filesystem will be automatically checked every 23 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
Create the Mount Point
A filesystem must have a mount point, which is simply an empty directory where the new filesystem “attaches” to the system’s directory tree. Mount points should be given names consistent with the Oracle Flexible Architecture (OFA) standard. For more information on OFA standards, see Appendix D of the Oracle 10g Database Installation Guide.
Because you have already used the /u01 and /u02 directory names in Part I, use /u03 for this example.
Ex:
# mkdir /u03
Add the New Filesystem to /etc/fstab
So that the new filesystem will be mounted automatically when the system boots, you need to add a line to the /etc/fstab file that describes the new filesystem and where to mount it. Add a line similar to the one below to /etc/fstab, using a text editor.
/dev/sdb1 /u03 ext3 defaults 1 1
Mount the New Filesystem
Mounting the filesystem makes it available for use. Until the filesystem is mounted, files cannot be stored in it. Use the following commands to mount the filesystem and verify that it is available.
mount /u03
df -h /u03Ex:
# mount /u03
# df -h /u03
Filesystem Size Used Avail Use% Mounted on
/dev/sdb1 33G 33M 31G 1% /u03
Create Oracle Directories and Set Permissions
Now you create a directory to store your Oracle files. The directory name used in the example follows the OFA standard naming convention for a database with ORACLE_SID=demo1.
mkdir -p /u03/oradata/demo1
chown -R oracle:oinstall /u03/oradata
chmod -R 775 /u03/oradata
Create a New Tablespace in the New Filesystem
The new filesystem is ready for use. Next you create a new tablespace in the filesystem to store your database objects. Connect to the database as the SYSTEM user, and execute the CREATE TABLESPACE statement, specifying the data file in the new filesystem.
Ex:
$ sqlplusSQL*Plus: Release 10.1.0.2.0 – Production on Sun Jun 13 15:01:08 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Enter user-name: system
Enter password:Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 – Production
With the Partitioning, OLAP and Data Mining optionsSQL> create tablespace data1
2 datafile ‘/u03/oradata/demo1/data1_01.dbf’ size 100M
3 extent management local
4 segment space management auto;Tablespace created.
Now you can use the new tablespace to store database objects such as tables and indexes.
Ex:
SQL> create table demotab (id number(5) not null primary key,
2 name varchar2(50) not null,
3 amount number(9,2))
4 tablespace data1;Table created.
Automatic Storage Management (ASM)
I’ve saved the best for last. ASM is a fantastic new feature in Oracle Database 10g that provides the services of a filesystem, logical volume manager, and software RAID in a platform-independent manner. ASM can stripe and mirror your disks, allow disks to be added or removed while the database is under load, and automatically balance I/O to remove “hot spots.” It also supports direct and asynchronous I/O and implements the Oracle Data Manager API (simplified I/O system call interface) introduced in Oracle9i.
ASM is not a general-purpose filesystem and can be used only for Oracle data files, redo logs, and control files. Files in ASM can be created and named automatically by the database (by use of the Oracle Managed Files feature) or manually by the DBA. Because the files stored in ASM are not accessible to the operating system, the only way to perform backup and recovery operations on databases that use ASM files is through Recovery Manager (RMAN).
ASM is implemented as a separate Oracle instance that must be up if other databases are to be able to access it. On Linux the OCSSD service (installed by default by the Oracle Universal Installer) must be running to allow use of ASM. Memory requirements for ASM are light: only 64 MB for most systems.
Installing ASM
On Linux platforms, ASM can use raw devices or devices managed via the ASMLib interface. Oracle recommends ASMLib over raw devices, for ease-of-use and performance reasons. ASMLib is available for free download from OTN. This section walks through the process of configuring a simple ASM instance by using ASMLib and building a database that uses ASM for disk storage.
Determine Which Version of ASMLib You Need
ASMLib is delivered as a set of three Linux packages:
- oracleasmlib – the ASM libraries
- oracleasm-support – utilities needed to administer ASMLib
- oracleasm – a kernel module for the ASM library
First, determine which kernel you are using by logging in as root and running the following command:
uname -rmEx:
# uname -rm
2.4.9-e.27smp i686
The example shows that this is a 2.4.9 kernel for an SMP (multiprocessor) box using Intel i686 CPUs.
Use this information to find the correct ASMLib packages on OTN:
- Point your Web browser to http://www.oracle.com/technology/tech/linux/asmlib
- Select the link for your version of Linux.
- Download the oracleasmlib and oracleasm-support packages for your version of Linux
- Download the oracleasm package corresponding to your kernel. In the example above, the oracleasm-2.4.9-e-smp-1.0.0-1.i686.rpm package is downloaded.
Next, install the packages by executing the following command as root:
rpm -Uvh oracleasm-kernel_version-asmlib_version.cpu_type.rpm \
oracleasmlib-asmlib_version.cpu_type.rpm \
oracleasm-support-asmlib_version.cpu_type.rpmEx:
# rpm -Uvh \
> oracleasm-2.4.9-e-smp-1.0.0-1.i686.rpm \
> oracleasmlib-1.0.0-1.i386.rpm \
> oracleasm-support-1.0.0-1.i386.rpm
Preparing… #################################### [100%]
1:oracleasm-support #################################### [ 33%]
2:oracleasm-2.4.9-e-smp #################################### [ 66%]
Linking module oracleasm.o into the module path [ OK ]
3:oracleasmlib #################################### [100%]
Configuring ASMLib
Before using ASMLib, you must run a configuration script to prepare the driver. Run the following command as root, and answer the prompts as shown in the example below.
# /etc/init.d/oracleasm configure
Configuring the Oracle ASM library driver.This will configure the on-boot properties of the Oracle ASM library
driver. The following questions will determine whether the driver is
loaded on boot and what permissions it will have. The current values
will be shown in brackets (‘[]‘). Hitting <ENTER> without typing an
answer will keep that current value. Ctrl-C will abort.Default user to own the driver interface []: oracle
Default group to own the driver interface []: dba
Start Oracle ASM library driver on boot (y/n) [n]: y
Fix permissions of Oracle ASM disks on boot (y/n) [y]: y
Writing Oracle ASM library driver configuration [ OK ]
Creating /dev/oracleasm mount point [ OK ]
Loading module “oracleasm” [ OK ]
Mounting ASMlib driver filesystem [ OK ]
Scanning system for ASM disks [ OK ]
Now enable the ASMLib driver as shown below.
# /etc/init.d/oracleasm enable
Writing Oracle ASM library driver configuration [ OK ]
Scanning system for ASM disks [ OK ]
Configuring Disks for ASM
Next you tell the ASM driver which disks you want it to use. Note that these are bare disks with nothing on them (not even a partition). It is possible to use disk partitions with ASM, but it isn’t recommended.
You mark disks for use by ASMLib by running the following command as root:
/etc/init.d/oracleasm createdisk DISK_NAME device_name
(Tip: Enter the DISK_NAME in UPPERCASE letters. There is a bug in the current release that prevents the disks from being visible to the ASM instance if lowercase is used.)
Ex:
# /etc/init.d/oracleasm createdisk VOL1 /dev/sdb
Marking disk “/dev/sdb” as an ASM disk [ OK ]
# /etc/init.d/oracleasm createdisk VOL2 /dev/sdc
Marking disk “/dev/sdc” as an ASM disk [ OK ]
# /etc/init.d/oracleasm createdisk VOL3 /dev/sdd
Marking disk “/dev/sdd” as an ASM disk [ OK ]
# /etc/init.d/oracleasm createdisk VOL4 /dev/sdf
Marking disk “/dev/sdf” as an ASM disk [ OK ]
# /etc/init.d/oracleasm createdisk VOL5 /dev/sdg
Marking disk “/dev/sdg” as an ASM disk [ OK ]
# /etc/init.d/oracleasm createdisk VOL6 /dev/sdh
Marking disk “/dev/sdh” as an ASM disk [ OK ]
The following example shows how to list all the disks marked for use by ASMLib.
# /etc/init.d/oracleasm listdisks
VOL1
VOL2
VOL3
VOL4
VOL5
VOL6
Now that ASMLib is installed and the disks are marked for use, you can create an ASM instance and build a database that uses ASM for disk storage. This is easiest to accomplish with the Data Base Configuration Assistant (DBCA).
Log in as oracle and start DBCA:
$ dbca
- Welcome
- Click on Next.
- Operations
- Select Create a Database.
- Database Templates
- Select General Purpose.
- Database Identification
- Enter the Global Database Name.
- Management Options
- Select Configure the Database with Enterprise Manager.
- Select Use Database Control for Database Management.
- Database Credentials
- Select Use Same Password for All Accounts.
- Enter the password and confirm.
- Storage Options
- Select Automatic Storage Management (ASM).
- Create ASM Instance
- Enter a password for the ASM instance, and confirm.
- A pop-up window appears, advising that DBCA will now create and start the ASM instance.
- Click on OK.
- A pop-up window displaying a gearbox appears while the ASM instance is being created.
- ASM Disk Groups
- The window shows no available disk groups, because this is a new ASM instance and you haven’t created any yet.
- Click on Create New.
- Create Disk Group
- Disk Group Name
- Enter a name, such as DATA1, for the disk group.
- Redundancy
- High mirrors data twice.
- Normal mirrors data once.
- External does not mirror data within ASM. This is typically used if an external RAID array is providing redundancy.
- Select Member Disks
- You have to tell ASM where to look for your ASMLib disks manually, so click on Change Disk Discovery Path
- A pop-up window appears for entry of the Disk Discovery Path. Change the Disk Discovery Path to ‘ORCL:*’ as shown below.
- Click on OK to continue.
- You are returned to the Select Member Disks window. All your ASMLib disks should now appear in the window.
Select the disks for the disk group by clicking on the box at the beginning of the line. Click on OK when finished.
- Disk Group Name
- ASM Disk Groups
- You are returned to the ASM Disk Groups window. This time, the disk group you created in the previous step appears.
- Select this disk group by clicking on the box at the beginning of the line. (Use a single disk group in this case.)
- Click on Next.
- Database File Locations
- Select Use Oracle-Managed Files.
- Make sure the Database Area is set to the disk group you created. It has a leading plus sign—+DATA1, for example.
- Recovery Configuration
- Select Specify Flash Recovery Area.
- Flash Recovery Area—Enter the ASM disk group to be used for Flash Recovery.
- Flash Recovery Area Size—Accept the default, 2048.
- Select Enable Archiving if you want to use archivelog mode. For an evaluation database, you can leave this unchecked.
- Select Specify Flash Recovery Area.
- Database Content
- Select Sample Schemas.
- You are not using Custom Scripts, so click on Next.
- Initialization Parameters
- Accept the defaults and click on Next.
- Database Storage
- Accept the defaults and click on Next.
- Creation Options
- Select Create Database (the default) and click on Finish.
- Confirmation
- Click on OK when you’ve finished reviewing Database Details.
- DBCA displays a list of actions and a progress bar. Database creation can take from several minutes to several hours, depending on your hardware.
- When the database creation is complete, a window appears, displaying a summary. Note the Enterprise Manager URL, and click on Exit.
|
Now that your database is up and running, you can begin exploring the many new features offered in Oracle 10g. A great place to start is Oracle Enterprise Manager, which has been completely re-written with a crisp new Web-based interface. If you’re unsure where to begin, the Oracle Concepts Guide and the 2-Day DBA Guide will help familiarize you with your new database. OTN also has a number of articles designed to help you get the most out of 10g. One of my favorites is the series by Arup Nanda, “Oracle Database 10g: The Top 20 Features for DBAs.”
Stay tuned for the next article, in which we will walk through the installation and configuration of a fully functional, two-node Oracle RAC 10g database.
Accessing the Database with SQL*Plus
Log into Linux as oracle. Set the environment.
Set the Oracle environment variables:
$ export ORACLE_BASE=/u01/app/oracle
$ export ORACLE_SID=demo1
$ export ORACLE_HOME=$ORACLE_BASE/product/10.1.0/db_1
$ export PATH=$PATH:$ORACLE_HOME/bin
Run SQL*Plus:
$ sqlplusSQL*Plus: Release 10.1.0.2.0 – Production on Sat Jun 5 16:59:21 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Enter user-name: / as sysdba
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 – Production
With the Partitioning, OLAP and Data Mining optionsSQL>
Using Oracle Enterprise Manager 10g Database Control
In a Web browser, connect to the URL provided during the installation.
Ex:
http://ds1.orademo.org:5500/em (You may have to use the IP address instead of the host name if your database server isn’t in your DNS.)
User Name: SYS
Password: <The password you chose during installation>
Connect As: SYSDBA
Click on <Login>
|
Welcome to the wonderful world of Oracle Enterprise Manager 10g Database Control!
Starting and Stopping Oracle Enterprise Manager Database Control:
$ emctl start dbconsole
$ emctl stop dbconsole
Accessing the Database Using iSQL*Plus
iSQL*Plus is a Web-based version of the venerable SQL*Plus interactive tool for accessing databases. To use iSQL*Plus, click on the iSQL*Plus link in the Related Links section of the OEM console or point your browser to the iSQL*Plus URL provided during installation.
Ex:
http://ds1.orademo.org:5560/isqlplus (You may have to use the IP address instead of the host name if your database server isn’t in your DNS.)
User Name: SYSTEM
Password: <The password you chose during installation>
Click on <Login>.
Enter SQL commands in the Workspace box, and click on Execute.
|
Starting and Stopping iSQL*Plus:
$ isqlplusctl start
$ isqlplusctl stop
Starting and Stopping the Listener:
The listener accepts connection requests from clients and creates connections to the database once the credentials have been authenticated. Before you can use OEM or iSQL*Plus, the listener must be up.
$ lsnrctl start
$ lsnrctl stop
Starting and Stopping the Database:
The easiest way to start and stop the database is from the OEM Console. To do that from the command line, use SQL*Plus while logged in as oracle, as follows:
Startup:
$ sqlplusSQL*Plus: Release 10.1.0.2.0 – Production on Sun Jun 13 22:27:48 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Enter user-name: / as sysdba
Connected to an idle instance.SQL> startup
ORACLE instance started.Total System Global Area 188743680 bytes
Fixed Size 778036 bytes
Variable Size 162275532 bytes
Database Buffers 25165824 bytes
Redo Buffers 524288 bytes
Database mounted.
Database opened.
SQL> exit
Shutdown:
$ sqlplusSQL*Plus: Release 10.1.0.2.0 – Production on Sun Jun 13 22:25:55 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Enter user-name: / as sysdba
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 – Production
With the Partitioning, OLAP and Data Mining optionsSQL> shutdown immediate
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> exit
List the Oracle Processes:
$ ps –fuoracle
What Are Those ocssd.bin Processes?
Oracle Cluster Synchronization Services (OCSSD) is a component of Oracle Cluster Ready Services (CRS) and is required for RAC and single-instance databases using ASM. It is installed by default, uses very few system resources, and is configured in /etc/inittab. These processes are started automatically each time the system boots. Oracle recommends against disabling OCSSD, even if you are not running ASM.