DB (데이터베이스)/Postgresql (포스트그래)

[Postgresql] postgresql partition table 파티션 테이블 생성 예제

뜽배 2025. 2. 27. 19:07
728x90
반응형

Postgresql 파티션 테이블 생성과 삭제 예제

 

 

1.  TABLE생성

Postgresql에서는 테이블 생성 시 pratitiong컬럼으로 하려면  PK도 partition기준 컬럼으로 해야한다.

CREATE TABLE PARTITION_TEST
(
	INF_KEY VARCHAR(50) ,
	DATA_INPUT_TIME TIMESTAMP NOT NULL,
	VALUE1 VARCHAR(10),
	VALUE2 VARCHAR(10),
	VALUE3 VARCHAR(10)
) partition by range (DATA_INPUT_TIME);

테이블 생성 시에는 따로 PK를 지정하지 않는다

 

 

2. 파티션 테이블 생성

개별 파티션에 PK추가  [Postgresql 10부터 Global index지원하지 않음]

 

-- 202501 ~ 202502 파티션 테이블 생성
create table partition_test_202501 partition of partition_test
for values from ('2025-01-01') to ('2025-02-01');

-- PK생성
create unique index pk_partition_test_202501 on partition_test_202501(inf_key);

-------------------------------------------------------------------------------

-- 202502 ~ 202503 파티션 테이블 생성
create table partition_test_202502 partition of partition_test
for values from ('2025-02-01') to ('2025-03-01');

-- PK생성
create unique index pk_partition_test_202502 on partition_test_202502(inf_key);

-------------------------------------------------------------------------------

-- 범위 벗어난 default 테이블생성
create table partition_test_default partition of partition_test default;

-- PK생성
create unique index pk_partition_test_default on partition_test_default(inf_key);

 

3. partition테이블 조회

-- partition테이블명
-- partition 유형 (r = range, l = list , h = hash)
-- partition컬럼

select
	partrelid::regclass as partition_table,
	partstrat as partition_div,
	partnatts as partition_column_id
from pg_partitioned_table;

----------------------------------------------------------------------------------------

-- partition테이블명
-- partitioning테이블명
SELECT
	inhparent::regclass AS parent_table,
    inhrelid::regclass AS partition_table
FROM pg_inherits;

 

 4. 데이터 insert test

insert into partition_test values ('1', '20250101', '1', '2', '3');
insert into partition_test values ('1', '20250201', '1', '2', '3');
insert into partition_test values ('1', '20250301', '1', '2', '3');

 

5. 조회

-- 전체테이블 조회
select *
from partition_test;

-- 파티션테이블별 조회
select *
from partition_test_202501;

select *
from partition_test_202502;

select *
from partition_test_default;

 

-- 파티션테이블별 용량 조회 (부모테이블은 용량 조회 불가)
select pg_size_pretty(pg_total_relation_size('partition_test_202501'));
select pg_size_pretty(pg_total_relation_size('partition_test_202502'));

 

 

6. 자식테이블 분리 or 삭제 , 추가

-- 자식테이블 분리
alter table partition_test detach partition partition_test_202501;

-- 자식테이블 삭제
drop table partition_test_202501;

-- 자식테이블 추가
create table partition_test_202503 partition of partition_test
for values from ('2025-03-01') to ('2025-04-01');

create unique index pk_partition_test_202503 on partition_test_202503(inf_key);
728x90
반응형