HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🤩
개발
/데이터베이스(Database)/
Postgresql

Postgresql

Docker로 셋업하기Stored ProcedurepsqlBackup and restore(pg_dump, psql)partitioning table backup쿼리TroubleShooting

Docker로 셋업하기

[ Blog ] postgres docker volume 셋업하기
- ./pgdata:/var/lib/postgresql/data
[ Github ] postgres container health check

Stored Procedure

MySQL 스토어드 프로시져와 MSSQL, Oracle 의 스토어드 프로시져 관리 차이
Stored Procedure의 query plan 이 캐시 되는지, 확인하기위해 찾아본 과정
  • Postgresql은 session 별로 prepared statements를 관리하고 shared query plan cache 도 지원하지 않음. 그래서 connection 별로 cache가 지원되기에, connection pool 을 이용해야 함
Prepared statements vs Stored Procedures
Getting the query plan for statements inside a stored procedure in PostgreSQL
Is there a shared query plan cache for Postgres ? → No
[ StackExchange ] Postgresql Function, Stored Procedure
[ StackExchange ] When to use stored procedure / user-defined function?
[ Postgresql Docs ] CREATE PROCEDURE
[ Postgresql Docs ] CALL
[ Postgresql Docs ] PREPARE

psql

아래 버전의 Amazon Linux 에서 psql install 하는 방법 : sudo amazon-linux-extras postgresql14 (근데 14 버전까지 밖에 지원안됨. 15 다운로드 하려면 os 바꾸라함)
[ Medium ] How to install Postgresql15 On Amazon Linux 2023
NAME="Amazon Linux" VERSION="2" ID="amzn" ID_LIKE="centos rhel fedora" VERSION_ID="2" PRETTY_NAME="Amazon Linux 2" ANSI_COLOR="0;33" CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2" HOME_URL="https://amazonlinux.com/" SUPPORT_END="2025-06-30"
postgresql 15를 위 버전에서 받기 위한 방법 [ reddit ]
  1. compile and roll your own package
  1. migrate over to one of the al2023 platforms, but that has its own complications (no epel, limited package selection, etc)
  1. Move to a custom, non-amazon linux, ami rocky/alma/redhat if you want to license it
 
 
[ 블로그 ] 알아두면 유용한 psql 명령어 정리
drop database <database_name> create database <database_name> \dt # list tables \l # list databases

Backup and restore(pg_dump, psql)

[Postgresql docs] pg_dump
# backup data pg_dump --host localhost --port 11543 -U gateway_user -t gateway.ais_blclst -O -a -E UTF8 postgres > dump.sql # backup schema of database pg_dump --host localhost --port 11543 -U gateway_user -O -E UTF8 <database> > dump.sql ## reload psql -d newdb -f db.sql
  • -O : To make a script that can be restored by any user, but will give that user ownership of all the objects, specify -O
  • -a : Dump only the data, not the schema (data definitions).
  • -E : Create the dump in the specified character set encoding
  • -t pattern : Dump only tables with names matching pattern
  • -s : Dump only the object definitions (schema), not data.
  • -n pattern : Dump only schemas matching pattern

partitioning table backup

pg_dump not dumping the table data
notion image
  • 위 이미지에서 보듯이 ais_ship_data_hist의 데이터가 ais_ship_data_hist테이블에 있는 것이 아니라 각각의 파티션 테이블에 존재함. 그래서 pg_dump를 해당 테이블들을 다 명시해주어야 데이터 dump 까지 진행됨
pg_dump --host localhost --port 11543 -U gateway_user -v -O -a -E UTF8 -t gateway.ais_ship_data_hist -t gateway.pais_ship_data_hist_230309 -t gateway.pais_ship_data_hist_230310 -t gateway.pais_ship_data_hist_230311 -t gateway.pais_ship_data_hist_230312 -t gateway.pais_ship_data_hist_230313 -t gateway.pais_ship_data_hist_230314 -t gateway.pais_ship_data_hist_230315 -t gateway.pais_ship_data_hist_230316 postgres > /data/ais_ship_data_hist.sql
 

쿼리

SELECT datname FROM pg_database -- 전체 데이터베이스 조회 SELECT datname FROM pg_database WHERE datistemplate = false -- 사용자가 생성한 데이터베이스만 조회 select nspname from pg_catalog.pg_namespace -- 현재 db의 전체 스키마 조회 select tablename from pg_tables -- 전체 테이블 조회 -- max 함수는 여러 행에 대해서 최대값 찾는 것이고, greatest 함수는 여러 열에 대해서 최대값 찾음 SELECT greatest(values...); // ALTER TABLE /// 컬럼 추가 ALTER TABLE cars ADD column <columnname> VARCHAR(255); /// 컬럼 삭제 ALTER TABLE townhall_reservations DROP COLUMN organization_id; /// 제약조건 삭제 ALTER TABLE townhall_reservations DROP CONSTRAINT fk_townhall_org_id; /// 제약조건 추가 ALTER TABLE orders ADD CONSTRAINT fk_city_id FOREIGN KEY (city_id) REFERENCES city (id); // 인덱스 삭제 DROP INDEX [ CONCURRENTLY ] [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] // 인덱스 조회 SELECT * FROM pg_indexes WHERE tablename = 'your_table'; // 인덱스 생성 CREATE UNIQUE INDEX CONCURRENTLY name ON table_name (column_name); ALTER TABLE equipment ADD CONSTRAINT <constraint_name> UNIQUE USING INDEX <index_name>; //현재 시퀀스 값 조회 SELECT currval('시퀀스명'); SELECT last_value FROM 시퀀스명; // 시퀀스 값 업데이트 ALTER SEQUENCE 시퀀스명 restart with 시퀀스값;
 

TroubleShooting

delete 후 table size 줄이기 (OS에게 디스크 반환)
VACUUM returning disk space to operating system
  • VACUUM FULL <table_name>
  • VACUUM FUUL
password 자동으로 setup
hostname:port:database:username:password
  • 위 형태의 .pgpass file을 계정의 home directory에 만들기
  • 그 후 권한 설정
    • chmod 600 ~/.pgpass
INSERT string with single quote(’)
[ Stack Overflow ] Insert text with single quotes in postgresql
'user's log' -- 안됨 'user''s log' # 가능 E'user\'s log' # 가능
예약어 이름과 같은 컬럼에 INSERT 할 때
  • double quote를 사용하기
    • INSERT INTO table (id, name, "year") VALUES ( ... );