{{tag>[cli postgres postgresql sql client]}}
====== psql ======
PostgreSQL interactive terminal이다. 대화형 SQL 실행, 스크립트 실행, 메타 커맨드 기반 점검에 가장 자주 쓰이는 기본 클라이언트다.
===== Summary =====
* 데이터베이스에 접속해 SQL과 ''\d'', ''\l'' 같은 meta command를 실행한다.
* ''-c''로 단발성 SQL 실행, ''-f''로 스크립트 실행, ''-X''로 사용자 설정 파일 배제를 제어할 수 있다.
* plain SQL dump 복원은 보통 ''psql -f backup.sql'' 형태로 처리한다.
===== 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
* ''**psql** [OPTIONS...] [DBNAME [USERNAME]]''
* ''**psql** **-d** DBNAME'' 대상 데이터베이스 지정
* ''**psql** **-h** HOST **-p** PORT **-U** USER'' 원격 접속 정보 지정
* ''**psql** **-c** COMMAND'' 단일 SQL 또는 internal command 실행 후 종료
* ''**psql** **-f** FILE.sql'' 스크립트 파일 실행
===== Options =====
* ''**-c**'', ''**--command**'' SQL 또는 internal command 한 번 실행 후 종료
* ''**-d**'', ''**--dbname**'' 접속할 데이터베이스 지정
* ''**-f**'', ''**--file**'' 파일에서 SQL 읽기
* ''**-l**'', ''**--list**'' 데이터베이스 목록 조회 후 종료
* ''**-v**'', ''**--set**'', ''**--variable**'' psql 변수 설정. 예: ''-v ON_ERROR_STOP=1''
* ''**-X**'', ''**--no-psqlrc**'' ''~/.psqlrc''를 읽지 않음
* ''**-1**'', ''**--single-transaction**'' 비대화형 실행을 단일 transaction으로 묶음
* ''**-A**'', ''**--no-align**'' unaligned 출력
* ''**-t**'', ''**--tuples-only**'' 결과 행만 출력
* ''**-x**'', ''**--expanded**'' expanded output
* ''**-h**'', ''**--host**'' 서버 호스트 또는 socket directory
* ''**-p**'', ''**--port**'' 서버 포트
* ''**-U**'', ''**--username**'' 접속 사용자
* ''**-w**'', ''**--no-password**'' 비밀번호 프롬프트 비활성화
* ''**-W**'', ''**--password**'' 비밀번호 프롬프트 강제
===== 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 =====
* 접속 실패 시 ''PGHOST'', ''PGPORT'', ''PGUSER'', ''PGDATABASE'' 환경 변수와 CLI 옵션 충돌 여부를 함께 확인한다.
* automation에서는 ''-X''와 ''-v ON_ERROR_STOP=1'' 조합을 쓰면 사용자별 ''.psqlrc'' 영향과 중간 실패 누락을 줄일 수 있다.
* ''peer authentication failed''가 나오면 Unix socket 접속과 ''pg_hba.conf'' 정책을 먼저 확인한다.
* 대화형 세션에서 object 탐색은 ''\dt'', ''\dv'', ''\du'', ''\dn'', ''\dx''가 빠르다.
===== 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 ====
* ''**\?** [TOPIC]'' backslash command(''commands''), CLI option(''options''), variable(''variables'') 도움말
* ''**\h** [SQL_COMMAND]'' SQL syntax 도움말. ''\h *''는 전체 SQL command 목록을 표시한다.
* ''**\conninfo**'' 현재 database, user, host, port, SSL 연결 정보 표시
* ''**\c** [DBNAME [USER [HOST [PORT]]]]'' 또는 ''**\connect** CONNINFO'' 새 연결로 전환
* ''**\encoding** [ENCODING]'' client encoding 조회 또는 변경
* ''**\password** [USERNAME]'' command history에 평문 password를 남기지 않고 role password 변경
* ''**\q**'' ''psql'' 종료
==== Object and Catalog Inspection ====
* ''**\l**[x+] [PATTERN]'' 또는 ''**\list**'' database 목록
* ''**\d**[Sx+] [PATTERN]'' relation 목록 또는 지정한 table, view, sequence, index 상세
* ''**\dt**[Sx+] [PATTERN]'' table 목록
* ''**\dv**[Sx+] [PATTERN]'', ''**\dm**[Sx+] [PATTERN]'' view와 materialized view 목록
* ''**\di**[Sx+] [PATTERN]'', ''**\ds**[Sx+] [PATTERN]'' index와 sequence 목록
* ''**\dn**[Sx+] [PATTERN]'' schema 목록
* ''**\du**[Sx+] [PATTERN]'' 또는 ''**\dg**[Sx+] [PATTERN]'' role 목록
* ''**\dx**[x+] [PATTERN]'' extension 목록
* ''**\dp**[x] [PATTERN]'' 또는 ''**\z**'' table, view, sequence access privilege 표시
* ''**\dconfig**[x+] [PATTERN]'' server configuration parameter 표시. 인수 없이 실행하면 기본값이 아닌 항목만 표시한다.
* ''**\sf**[+] FUNCTION'', ''**\sv**[+] VIEW'' function 또는 view 정의 표시
==== Query Buffer and Execution ====
* ''**\p**'' 현재 query buffer 표시
* ''**\r**'' query buffer 초기화
* ''**\e** [FILE [LINE]]'' editor에서 query buffer 또는 file 편집
* ''**\g** [FILE]'' query buffer 실행. file 또는 ''|COMMAND''를 주면 결과를 해당 대상으로 보낸다.
* ''**\gx** [FILE]'' expanded output을 강제해 query 실행
* ''**\gdesc**'' query를 실행하지 않고 결과 column name과 data type 표시
* ''**\gset** [PREFIX]'' 정확히 한 행인 query 결과를 ''psql'' variable에 저장
* ''**\gexec**'' query 결과의 각 값을 SQL로 다시 실행
* ''**\watch** [INTERVAL]'' 현재 query를 지정 간격으로 반복 실행
''\gexec''는 query 결과를 SQL 문장으로 실행한다. 생성될 SQL을 먼저 일반 query로 검토하고, automation에서는 필요에 따라 ''ON_ERROR_STOP''과 transaction을 함께 사용한다.
==== Input, Output, and Files ====
* ''**\i** FILE'' SQL 또는 meta-command script 실행
* ''**\ir** FILE'' 현재 script file 위치를 기준으로 상대 경로 script 실행
* ''**\copy** ...'' client host의 권한과 file 경로를 사용해 ''COPY'' 수행
* ''**\o** [FILE]'' 이후 query 결과를 file 또는 ''|COMMAND''로 전송. 인수 없이 실행하면 standard output으로 복귀한다.
* ''**\w** FILE'' 현재 query buffer를 file 또는 ''|COMMAND''에 기록
* ''**\echo** [TEXT]'', ''**\qecho** [TEXT]'' standard output 또는 현재 query output stream에 text 출력
==== Output Formatting and Timing ====
* ''**\x** [ON|OFF|AUTO]'' expanded output 전환
* ''**\pset** [OPTION [VALUE]]'' border, format, pager, null 표시 등 결과 출력 형식 설정
* ''**\a**'' aligned/unaligned output 전환
* ''**\t**'' column heading과 row count footer 표시 전환
* ''**\timing** [ON|OFF]'' SQL 실행 시간 표시 전환
* ''**\crosstabview** [COLUMNS]'' 현재 query 결과를 crosstab 형태로 표시
==== Variables and Script Control ====
* ''**\set** [NAME [VALUE]]'', ''**\unset** NAME'' ''psql'' variable 설정 또는 해제
* ''**\prompt** [TEXT] NAME'' 입력받은 값을 variable에 저장
* ''**\getenv** PSQL_VAR ENV_VAR'', ''**\setenv** NAME [VALUE]'' environment variable 조회 또는 설정
* ''**\if** EXPR'', ''**\elif** EXPR'', ''**\else**'', ''**\endif**'' script 조건 분기
* ''**\warn** TEXT'' standard error에 message 출력
==== Shell and History ====
* ''**\cd** [DIR]'' ''psql'' process의 working directory 변경
* ''**\!** [COMMAND]'' shell command 실행 또는 interactive shell 시작
* ''**\s** [FILE]'' command history 표시 또는 file로 저장
==== Extended Query Protocol and Pipeline ====
PostgreSQL 18 client는 extended query protocol과 pipeline 시험용 command를 제공한다. 구버전 client에는 일부 command가 없을 수 있다.
* ''**\parse** STATEMENT_NAME'', ''**\bind** [PARAMETER...]'', ''**\bind_named** STATEMENT_NAME [PARAMETER...]'' prepared statement parse/bind 작업
* ''**\close_prepared** STATEMENT_NAME'' client connection의 prepared statement 닫기
* ''**\startpipeline**'', ''**\sendpipeline**'', ''**\syncpipeline**'', ''**\endpipeline**'' pipeline 시작, query 전송, 동기화, 종료
* ''**\flushrequest**'', ''**\flush**'', ''**\getresults** [COUNT]'' pipeline의 flush 요청, client send buffer flush, 대기 결과 읽기
''pg_dump''의 plain format 출력은 보통 ''pg_restore''가 아니라 ''psql''로 복원한다. 반대로 custom, directory, tar format archive는 [[postgresql:pg_restore]]로 다루는 편이 일반적이다.
===== Compatibility =====
* Internal command 설명은 PostgreSQL 18 공식 ''psql'' 문서를 기준으로 정리했다.
* 이 페이지의 folded 도움말은 로컬에 설치된 PostgreSQL 10.23 client 출력이다.
* 현재 환경의 ''psql --help''에는 기본 DB와 기본 사용자 예시가 ''master''로 보인다. 다른 시스템에서는 현재 OS 사용자명이나 배포판 설정에 따라 값이 다를 수 있다.
* ''psql''은 같은 major version 또는 더 오래된 PostgreSQL server와 함께 사용할 때 가장 안정적이다. 특히 backslash command는 client보다 새로운 server에서 실패할 수 있다.
===== Help =====
++++ psql --help |
psql is the PostgreSQL interactive terminal.
Usage:
psql [OPTION]... [DBNAME [USERNAME]]
General options:
-c, --command=COMMAND run only single command (SQL or internal) and exit
-d, --dbname=DBNAME database name to connect to (default: "master")
-f, --file=FILENAME execute commands from file, then exit
-l, --list list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set psql variable NAME to VALUE
(e.g., -v ON_ERROR_STOP=1)
-V, --version output version information, then exit
-X, --no-psqlrc do not read startup file (~/.psqlrc)
-1 ("one"), --single-transaction
execute as a single transaction (if non-interactive)
-?, --help[=options] show this help, then exit
--help=commands list backslash commands, then exit
--help=variables list special variables, then exit
Input and output options:
-a, --echo-all echo all input from script
-b, --echo-errors echo failed commands
-e, --echo-queries echo commands sent to server
-E, --echo-hidden display queries that internal commands generate
-L, --log-file=FILENAME send session log to file
-n, --no-readline disable enhanced command line editing (readline)
-o, --output=FILENAME send query results to file (or |pipe)
-q, --quiet run quietly (no messages, only query output)
-s, --single-step single-step mode (confirm each query)
-S, --single-line single-line mode (end of line terminates SQL command)
Output format options:
-A, --no-align unaligned table output mode
-F, --field-separator=STRING
field separator for unaligned output (default: "|")
-H, --html HTML table output mode
-P, --pset=VAR[=ARG] set printing option VAR to ARG (see \pset command)
-R, --record-separator=STRING
record separator for unaligned output (default: newline)
-t, --tuples-only print rows only
-T, --table-attr=TEXT set HTML table tag attributes (e.g., width, border)
-x, --expanded turn on expanded table output
-z, --field-separator-zero
set field separator for unaligned output to zero byte
-0, --record-separator-zero
set record separator for unaligned output to zero byte
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "local socket")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "master")
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
++++
===== See Also =====
* [[https://www.postgresql.org/docs/current/app-psql.html|PostgreSQL Documentation: psql]]
* [[postgresql:pg_dump]]
* [[postgresql:pg_restore]]
* [[postgresql:command]]
* [[postgresql:config:pg_hba.conf]]
===== History =====
* codex:: 2026-08-04 Expanded internal commands by task, including catalog inspection, query execution, scripting, and PostgreSQL 18 pipeline commands.
* codex:: 2026-06-22 Reorganized psql into a structured CLI reference with connection, scripting, and restore workflow notes.
{{indexmenu>.#1|js}}