CUBRID Tutorial (Unix/)

소개: 본 문서는 CUBRID 제품을 처음 접하는 사용자가 제품 사용에 익숙해질 수 있도록 Database 생성, Database 구동/종료 등의 Database 운영에서부터 스키마 생성/변경 데이터 조작 및 검색 등 Database 조작에 이르는 일련의 기본적인 과정을 예제를 통해 살펴 볼 수 있도록 구성되어 있다. 문서는 CUBRID 사용을 위한 기본적인 내용들만 다루고 있기 때문에, 추가적인 사항은 CUBRID 매뉴얼의 참조를 권고한다.

2008-10-03 기술컨설팅팀 정만영, CUBRID

적용 대상: CUBRID2008

목 차 용어 ...... 1 CUBRID 시작하기 ...... 1 Database 생성하고 시작하기 ...... 2 CUBRID 조작하기 ...... 3 Demodb Database Table 정보 ...... 3 SQL/X 접속하기 ...... 4 스키마 생성하기 ...... 5 데이터 조작하기 ...... 6 데이터 검색하기 ...... 7 파티션과 뷰 생성하기 ...... 14 CUBRID DB 정지 ...... 16

용어

CUBRID 는 기본적으로 객체 관계 형 DBMS 용어를 사용하고 있으나, 기존 관계 형 DBMS 사용자의 이해를 돕기 위해, 본 문서에서는 관계 형 용어를 사용하였다. 다음은 관계 형 용어와 객체 관계 형 용어간의 관계 Table 이다.

관계 형 용어 객체 관계 형 용어

Data type Domain

Column Attribute

Row, Tuple, Record Instance

Table Class

Procedure Method

CUBRID 시작하기 본 문서는 CUBRID 의 설치가 완료되었다는 가정하에 작성되었다. 만약 CUBRID 가 설치되어 있지 않다면, CUBRID 설치를 완료한 후에 본 문서를 참조하기 바란다.

CUBRID 가 설치된 호스트에 CUBRID 를 설치한 사용자로 로그인을 하고 아래 예제를 따라서 한다.

Database 생성하고 시작하기

Database 생성하기

Database 을 생성하는 명령은 다음과 같다.

createdb [options] database_name

createdb 를 실행하면 명령을 실행한 현재 디렉토리에 Database 가 생성 되므로 Database 를 생성하기 전에 Database 가 생성될 디렉토리를 먼저 생성하고 생성된 디렉토리로 이동하여 작업해야 Database 가 사용할 볼륨파일을 효율적으로 관리할 수 있다.

[cubrid@testsrv4 cubrid]$ mkdir testdb

[cubrid@testsrv4 cubrid]$ cd testdb

[cubrid@testsrv4 testdb]$ cubrid createdb testdb

Creating database with 5000 pages.

*** CUBRID Standalone Release 6.5.0.1006 ***

Generated Jun 3 2006 at 12:39:48

Database `testdb' was successfully created at `/home/cubrid/testdb'.

If you want to start this database, run command `cubrid server start testdb'.

If you want to execute query, run command `csql testdb'.

[cubrid@testsrv4 testdb]$

# 옵션을 통해 Database 크기를 지정해 주지 않고 기본 크기로 생성한 Database 는 페이지 사이즈가 default 4kbytes 인 5000 개 page 를 갖는 Database 로 실제 사용되기에는 작은 크기로 생성되며 업무 내용에 따라 createdb 의 옵션중 ?p 옵션을 이용하여 크기를 설정할 수 있다. 그 외의 옵션들은 CUBRID 매뉴얼의 참조를 권고한다.

Database 시작하기

생성된 Database 서버를 구동하는 명령은 다음과 같다.

cubrid server start [-timeout second] database_name

[cubrid@testsrv4 testdb]$ cubrid server start testdb

This may take a long time depending on the amount of recovery works to do.

*** CUBRID Server Release 6.5.0.1006 ***

Generated Jun 3 2006 at 12:54:15

[cubrid@testsrv4 testdb]$ 구동중인 Database 확인하기

현재 구동중인 Database 을 확인하는 명령은 다음과 같다.

cub_commdb ?P

[cubrid@testsrv4 testdb]$ cub_commdb -P

The CUBRID master running on host testsrv4

was started at Tue Jun 13 08:15:07 2006

has serviced 4 requests. 1 server(s) running.

Server testdb (rel 6.5, pid 25087)

[cubrid@testsrv4 testdb]$

CUBRID 조작하기

Database 를 조작하는 방법은 여러 가지가 있으며, 본 문서에서는 SQL/X 을 이용한 방법을 소개한다. SQL/X 을 이용하려면 Database 를 먼저 구동시켜야 한다. “데이터 조작하기” 부분에서는 CUBRID 를 설치하면 자동으로 생성되는 ¡demodb¡ Database 를 활용하였다. ¡demodb¡, ¡demodb”는 개발자들이 예제로 활용할 수 있도록 추가한 Database 이다.

¡cubrid server start¡ 명령어를 이용하여 demodb Database 를 구동한다.

[cubrid@testsrv4 cubrid]$ cubrid server start demodb

This may take a long time depending on the amount of recovery works to do.

*** CUBRID Server Release 6.5.0.1006 ***

Generated Jun 3 2006 at 12:54:15

[cubrid@testsrv4 cubrid]$

Demodb Database Table 정보

아래의 Table 에 입력된 데이터는 단순히 예제로 사용하기 위해 만든 데이터임으로 실제 정보와는 다를 수 있다.

SQL/X 접속하기 SQL/X 는 Database 에 스키마를 다루거나 데이터를 다루기 위해 문을 입력, 편집, 수행 할 때 사용하는 Command Line 기반 SQL 인터프리터이다.

SQL/X 인터프리터로 접속하기 위한 방법은 다음과 같다.

csql [option list] database_name

[cubrid@testsrv4 cubrid]$ csql demodb

CUBRID SQL Interpreter

Type `;help' for help messages.

csql>

demodb 라는 Database 에 접속하고 csql> 와 같이 프롬프트가 나타난다.

# csql 의 자세한 명령어는 csql 에 접속된 상태에서 ¡;help¡를 입력하면 확인 할 수 있다.

스키마 생성하기

Table 생성 및 확인하기

Table 생성하기는 SQL/X 에 접속된 상태에서 다음과 같은 형식으로 Table 을 생성한다.

create table Table 명

( 컬럼명 데이터_타입,

컬럼명 데이터 _타입 )

# csql 사용법 : 입력한 SQL 문을 실행하려면 ¡;ru¡, ¡;x¡를 입력하고 Enter 키를 누른다. 두 명령어의 차이는 ¡;ru¡는 실행 후에 SQL 문을 버퍼에서 삭제하지 않고 그대로 유지하고 ¡;x¡는 SQL 문을 버퍼에서 삭제한다. csql> create table employee csql> (name varchar(50), csql> birth_date date, csql> title varchar(50), csql> employee_num integer csql> ); csql> ;x

Current transaction has been committed.

1 command(s) successfully processed. csql>

생성된 Table 의 스키마를 확인하는 방법은 아래와 같다. ;sc Table 명

csql> ;sc employee

=== Help: Schema of a Class> ===

employee

name : character varying(50)

birth_date : date

title : character varying(50)

employee_num : integer

Current transaction has been committed.

csql>

데이터 조작하기

데이터 삽입하기

Insert 구문을 사용하여 새로운 Row 를 추가한다.

질의) ¡olympic¡ Table 에 2008 베이징올림픽정보(2008, ¡China¡, Beijing, 2008-08-08, 2008-08-24, FUWA,¡ One world, One dream¡)를 추가한다.

csql> insert into olympic(host_year, host_nation, host_city, opening_date, closing_date, mascot, slogan)

csql> values(2008, 'China', 'Beijing', '2008-08-08', '2008-08-24', ' FUWA', 'One world, One dream');

csql> ;x

1 rows inserted.

Current transaction has been committed.

1 command(s) successfully processed.

csql> select host_year, host_nation, host_city, mascot from olympic order by host_year desc

csql> ;x

=== ===

host_year host_nation host_city mascot

======

2008 'China' 'Beijing' ' FUWA'

2004 'Greece' 'Athens' 'Athena Phevos'

2000 'Australia' 'Sydney' 'Olly Syd Millie'

중간생략 1904 'USA' 'St. Louis' ''

1900 'France' 'Paris' ''

1896 'Greece' 'Athens' '' 데이터 수정하기

Update 구문을 사용하여 이미 입력된 값을 새로운 값으로 수정한다.

질의) ¡olympic¡ Table 에 입력되어 있는 2008 년 host_nation 의 값을 People's Republic of China 로 수정하라

csql> update olympic set host_nation='People''s Republic of China' where host_year=2008

csql> select host_year, host_nation, host_city, mascot from olympic where host_year=2008

csql> ;x

=== ===

host_year host_nation host_city mascot

======

2008 'People's Republic of China' 'Beijing' ' FUWA'

1 rows selected.

Current transaction has been committed.

1 command(s) successfully processed. 3 command(s) successfully processed.

데이터 삭제하기

Update 구문을 사용하여 이미 입력된 데이터 중에서 원하는 Row 를 삭제한다.

질의) ¡olympic¡ Table 에 입력되어 있는 데이터 중 2008 년의 데이터를 삭제한다

csql> delete from olympic where host_year=2008

csql> select host_year, host_nation, host_city, mascot from olympic where host_year=2008

csql> ;x

=== ===

There are no results.

0 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.csql>

데이터 검색하기

Select

데이터를 검색하기 위해서 사용하는 Select 구문은 SELECT 절, FROM 절, 선택사항인 WHERE 절로 구성된다.

 SELECT 절 SELECT 절에는 컬럼명, 문자, 연산자, DISTINCT, *, alias.*, Table 명.*, 서브질의 등이 올 수 있다.

 FROM 절

데이터를 검색할 Table(들)을 명시한다.

 WHERE 절

연산자

비교 연산자

컬럼의 값을 주어진 조건의 값과 비교한다.

질의) 역대 올림픽이 열린 국가를 중복되지 않게 조회하라

csql> select distinct host_nation from olympic;

=== ===

host_nation

======

'Australia'

'Belgium'

중간생략

'USA'

'USSR'

'United Kingdom'

18 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.csql>

질의) 88 년 서울올림픽에서 대한민국이 획득한 금, 은, 동메달의 수를 모두 합하면 몇 개인지 조회하라.

csql> select gold+silver+bronze as AN¢¨¢¨¨o from participant where nation_code='KOR' and host_year=1988;

csql> ;x

=== ===

총메달수

======

33

1 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.csql> 질의) 88 년 서울올림픽이 며칠 동안 진행되었는지 구하라.

csql> select closing_date-opening_date as A©CaAI¨o from olympic where hos t_year=1988;

csql> ;x

=== ===

A©CaAI¨o

======

15

1 rows selected.

Current transaction has been committed.

1 command(s) successfully processedcsql>

함수

함수를 통하여 원하는 결과값을 보여준다.

질의) 88 년 서울올림픽에 참가한 모든 국가를 대문자로 출력하라.

csql> select upper(A.name) from nation A, participant B where A.code=B.nation_code and B.host_year=1988;

csql>x;

=== ===

upper(A.name)

======

'ZIMBABWE'

'ZAMBIA'

'ZAIRE' 'KOREA'

중간생략

'UNITED STATES OF AMERICA'

'GERMAN DEMOCRATIC REPUBLIC'

'U.R.S.S.'

156 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.csql>

질의) 88 년 서울올림픽의 개최일을 ¡March 1 Mon¡ 형식으로 출력하라

csql> select host_year, host_city, TO_CHAR(opening_date, 'MONTH dd DY') from olympic where host_year=1988;

csql> ;x === ===

host_year host_city to_char(opening_date, 'MONTH dd DY', 'en_US')

======

1988 'Seoul' 'SEPTEMBER 17 SAT'

1 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.

질의) 역대 올림픽마스코트를 출력하고, 마스코트가 지정되어 있지 않다면 ¡없음¡을 출력하라.

csql>select host_year, nvl( mascot, '없음') from olympic;

csql> ;x

=== ===

host_year nvl(mascot, ¡없음¡)

======

2004 'Athena Phevos'

2000 'Olly Syd Millie'

1996 'Izzy'

1992 'Cobi'

1988 'HODORI'

1984 'Sam'

1980 'Misha'

1976 'Amik'

1972 'Waldi'

1968 ''

중간생략

1904 ''

1900 ''

1896 ''

25 rows selected.

Current transaction has been committed.

1 command(s) successfully processed

질의) 88 년 서울올림픽의 금메달의 총 개수를 구하라

csql> select host_year, sum(gold) from participant group by host_year HAVING host_year =1988;

csql> ;x

=== ===

host_year sum(gold)

======

1988 241

1 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.

질의) 88 년 서울올림픽에서 수영으로 금메달을 획득한 국가와 ¡Seoul Olympic Stadium¡에서 금메달을 획득한 국가들의 합집합을 조회하라.

csql> select * from nation where code in(

csql> select nation_code from game

csql> where event_code in(select code from event where sports ='Swimming') and medal='G' and host_year=1988

csql> UNION

csql> select nation_code from game where stadium_code in(

csql> select code from stadium where name ='Seoul Olympic Stadium') and medal='G' and host_year=1988);

csql> ;x

=== ===

code name continent capital

======

'AUS' 'Australia' 'Oceania' 'Canberra'

'BUL' 'Bulgaria' 'Europe' 'Sofia'

중간생략

'URS' 'U.R.S.S.' 'Europe' 'Moscow'

'USA' 'United States of America' 'Americas' 'Washington.D.'

18 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.

조인

테이블간의 관계를 통하여 데이터를 조회한다.

질의) 역대올림픽육상 100M 의 최고기록과 그 기록 보유 선수의 이름을 조회하라

csql> select B_2 as 기록, A.name from athlete A INNER JOIN as

csql> (select athlete_code, cast(score as numeric(4,2)) from record

csql> where event_code in(select code from event where name='100m') order by 2 asc) B

csql> on A.code=B.athlete_code and rownum=1;;

csql> ;x

50 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.

csql> select a.line,b.station

csql> from line a, station b

csql> where a.line like '2 호선%' and

csql> a.line_id = b.line_id

csql> ;x

csql> ;x

=== ===

기록 name

======

9.84 'Bailey Donovan'

1 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.csql>

질의) 88 년 서울올림픽에 참가한 세계 모든 국가와 그 순위를 조회하라

csql> select B.name, A.gold, A.silver, A.bronze from participant A inner join nation B

csql> on B.code=A.nation_code and A.host_year=1988 order by 2 desc,3 desc,4 desc, name asc; csql> ;x

=== ===

name gold silver bronze

======

'U.R.S.S.' 55 31 46

'German Democratic Republic' 37 35 30

'Korea' 12 10 11

'Federal Republic of Germany' 11 14 15

'Hungary' 11 6 6

'Bulgaria' 10 12 13

중간생략

'Zambia' 0 0 0

'Zimbabwe' 0 0 0

156 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.csql>

질의) 88 년 서울올림픽의 1 위부터 10 위까지의 국가 순위를 조회하라

csql> select B.name, A.gold, A.silver, A.bronze from participant A inner join nation B

csql> on B.code=A.nation_code and A.host_year=1988

csql> order by 2 desc,3 desc,4 desc, name asc for orderby_num() between 1 and 10;

csql> ;x

=== ===

name gold silver bronze

======

'U.R.S.S.' 55 31 46

'German Democratic Republic' 37 35 30

'United States of America' 36 31 27

'Korea' 12 10 11

'Federal Republic of Germany' 11 14 15

'Hungary' 11 6 6

'Bulgaria' 10 12 13 'Romania' 7 11 6

'France' 6 4 6

'Italy' 6 4 4

10 rows selected.

Current transaction has been committed.

1 command(s) successfully processed.

파티션과 뷰 생성하기

쿼리를 이용하여 구분에 따라 파티션을 나누고 원하는 뷰를 생성하는 방법을 확인한다.

파티션()

조건) game 테이블을 획득 메달 기준으로 리스트 분할하라.

csql> alter table game partition by list (medal)

csql> (partition medal1 values in ('G'),

csql> partition medal2 values in ('S'),

csql> partition medal3 values in ('B')

csql> );

csql> ;x

Current transaction has been committed.

1 command(s) successfully processed.

csql> ;sc game

=== ===

game

game__p__medal1

game__p__medal2

game__p__medal3

host_year INTEGER NOT NULL

event_code INTEGER NOT NULL

athlete_code INTEGER NOT NULL stadium_code INTEGER NOT NULL

nation_code CHARACTER(3)

medal CHARACTER(1)

game_date DATE

PRIMARY KEY pk_game_host_year_event_code_athlete_code ON game (host_year, event_code, athlete_code)

FOREIGN KEY fk_game_event_code ON game (event_code) REFERENCES event ON DELETE RESTRICT, ON UPDATE RESTRICT

FOREIGN KEY fk_game_athlete_code ON game (athlete_code) REFERENCES athlete ON DELETE RESTRICT, ON UPDATE RESTRICT

PARTITION BY LIST (medal)

PARTITION medal1 VALUES IN ('G')

PARTITION medal2 VALUES IN ('S')

PARTITION medal3 VALUES IN ('B')

Current transaction has been committed.);

뷰(view)

조건) game 테이블을 획득 메달 기준으로 리스트 분할하라. csql>create view game_1988 as csql>select B.name as 선수명, A.name as 국가명, B.event as 종목명 csql>from nation A INNER JOIN (select name, nation_code, event from athlete csql>where code in(select athlete_code from game where medal='G' and host_year=1988)) B csql>on A.code=B.nation_code;

csql> ;x

Current transaction has been committed.

1 command(s) successfully processed.

csql> ;sc game_1988

=== ===

game_1988

선수명 CHARACTER VARYING(40)

국가명 CHARACTER VARYING(40)

종목명 CHARACTER VARYING(30)

select B."name", A."name", B."event" from nation A inner join (select athlete."name", athlete.nation_code, athlete."event" from athlete athlete where athlete.code in (select distinct game.athlete_code from game game where game.medal='G' and game.host_year=1988)) B ("name", nation_code, "event") on A.code=B.nation_code

SQL/X 를 종료 할 때는 다음과 같이 한다. csql> ;exit

[cubrid@testsrv4 cubrid]$

CUBRID DB 정지

구동중인 Database 을 종료하는 명령은 다음과 같다. cubrid server stop database_name

[joung2008@mozart ~]$ cub_commdb -P

Server demodb (rel 8.1, pid 10138)

[joung2008@mozart ~]$ cubrid server stop demodb

@ cubrid server stop: demodb

Server demodb notified of shutdown.

This may take several minutes. Please wait.

++ cubrid server stop: success

[joung2008@mozart ~]$ cub_commdb -P

[joung2008@mozart ~]$

All rights reserved.