목차

, , , ,

psql

PostgreSQL interactive terminal이다. 대화형 SQL 실행, 스크립트 실행, 메타 커맨드 기반 점검에 가장 자주 쓰이는 기본 클라이언트다.

Summary

Usage

psql [OPTION]... [DBNAME [USERNAME]]
psql -d appdb
psql -h 127.0.0.1 -p 5432 -U postgres -d appdb
psql -c 'SELECT now();' -d postgres
psql -f schema.sql -d appdb

Options

Examples

# 로컬 소켓으로 기본 사용자/DB 조합 접속
psql
 
# 특정 데이터베이스 접속
psql -d appdb
 
# 원격 서버 접속
psql -h 127.0.0.1 -p 5432 -U postgres -d appdb
 
# SQL 한 줄만 실행
psql -d appdb -c 'SELECT current_database(), current_user;'
 
# 에러 발생 시 즉시 중단하도록 스크립트 실행
psql -X -v ON_ERROR_STOP=1 -d appdb -f ./schema.sql
 
# plain SQL dump 복원
psql -X -v ON_ERROR_STOP=1 -d appdb -f ./backup.sql

Troubleshooting

Internal Commands

psql prompt에서 따옴표로 감싸지 않은 backslash(\)로 시작하는 입력은 서버에 보내는 SQL이 아니라 psql client가 처리하는 meta-command(internal command)다. 현재 client가 지원하는 전체 목록은 \? commands 또는 psql –help=commands로 확인한다.

\d 계열 command에서 S는 system object 포함, +는 추가 상세 정보, PostgreSQL 18의 x는 expanded output을 뜻한다. 지원 command와 modifier는 psql client version에 따라 다르므로 접속 대상 서버보다 최신인 client를 사용하는 편이 안전하다.

Help, Session, Connection

Object and Catalog Inspection

Query Buffer and Execution

\gexec는 query 결과를 SQL 문장으로 실행한다. 생성될 SQL을 먼저 일반 query로 검토하고, automation에서는 필요에 따라 ON_ERROR_STOP과 transaction을 함께 사용한다.

Input, Output, and Files

Output Formatting and Timing

Variables and Script Control

Shell and History

Extended Query Protocol and Pipeline

PostgreSQL 18 client는 extended query protocol과 pipeline 시험용 command를 제공한다. 구버전 client에는 일부 command가 없을 수 있다.

pg_dump의 plain format 출력은 보통 pg_restore가 아니라 psql로 복원한다. 반대로 custom, directory, tar format archive는 pg_restore로 다루는 편이 일반적이다.

Compatibility

Help

psql --help

See Also

History