가이드
psql 명령어 치트 시트: 데이터베이스, 테이블, 사용자 목록 보기 등
가장 자주 쓰는 psql 명령어는 다음과 같습니다. \l은 데이터베이스 목록을 보여 주고, \c dbname은 다른 데이터베이스에 접속합니다. \dt는 테이블 목록을 보여 주며(스키마 하나만 보려면 \dt shop.*), \d orders는 테이블 구조를 보여 줍니다. \du는 사용자와 role 목록, \x auto는 긴 행을 읽기 쉽게 표시하고, \?는 모든 명령어를 보여 주며, \q는 종료합니다. 백슬래시 명령어는 psql 전용이므로 다른 도구에서는 아래의 SQL을 써야 합니다.
접속하기
psql은 접속 URI나 개별 플래그를 받습니다. 셸이 ?와 &를 해석하지 않도록 URI를 따옴표로 감싸세요.
psql "postgresql://[email protected]:5432/appdb?sslmode=require"
psql -h db.example.com -p 5432 -U app_user -d appdb
psql -l # list databases and exit
psql -d appdb -c "SELECT now();" # run one command and exit
psql -d appdb -f migrate.sql # run a file and exit프롬프트에는 현재 데이터베이스가 표시됩니다. 일반 사용자는 appdb=>, 슈퍼유저는 appdb=#입니다. 백슬래시 명령어(메타 명령어)는 psql이 직접 처리하므로 세미콜론이 필요 없고 줄이 끝나면 끝납니다. SQL 문은 서버로 전송되며, psql이 마지막 ;를 만나면 실행됩니다.
아직 psql이 없다면 Mac에 psql 설치하는 방법을 참고하세요. 이 페이지의 모든 명령어는 읽기 전용 Tablux 데모 데이터베이스에서 동작하므로 서버 없이도 직접 해 볼 수 있습니다.
데이터베이스 목록 보기와 전환
\l -- list databases: name, owner, encoding, locale, access privileges
\l+ -- adds size, default tablespace and description
\l app* -- only databases whose name starts with app
\c appdb -- connect to another database (same user, host, port)
\c appdb alice -- ... as another user
\conninfo -- which database, user, host and port you are on, and SSL details\l은 \list, \c는 \connect의 줄임말입니다. PostgreSQL 연결은 하나의 데이터베이스에 속하므로 USE dbname이 없습니다. \c는 새 연결을 열고 기존 연결을 닫습니다. 새 연결에 실패하면 psql은 이전 연결을 유지합니다(대화형 모드에서).
테이블 목록 보기: \dt
appdb=> \dt
List of relations
Schema | Name | Type | Owner
--------+-------+-------+-----------
public | notes | table | app_owner
(1 row)주의할 점: 패턴 없이 실행하면 \dt는 search_path에 있는 스키마(보통 public)의 테이블만 보여 줍니다. 테이블이 다른 스키마에 있다면 스키마 이름을 지정하세요.
\dt shop.* -- every table in schema shop
\dt shop.ord* -- tables in shop whose name starts with ord
\dt *.orders -- a table called orders in any schema
\dt *.* -- every table in every schema, system catalogs included
\dt+ shop.* -- adds persistence, access method, size on disk and description패턴에서 *는 임의의 문자열, ?는 임의의 한 문자와 일치합니다. 이름은 큰따옴표로 감싸지 않으면 소문자로 바뀝니다: \dt "Orders". psql이 어디를 찾는지는 SHOW search_path;로 확인하고, 세션 동안 바꾸려면 SET search_path = shop, public;을 실행하세요.
관련 명령어에도 같은 패턴 규칙이 적용되며, 문자를 조합할 수도 있습니다. \dtv shop.*는 테이블과 뷰를 함께 보여 줍니다.
테이블, 뷰, 인덱스, 함수 구조 보기
\d shop.orders -- columns, types, defaults, indexes, constraints, foreign keys, triggers
\d+ shop.orders -- adds storage, compression, statistics target and column comments
\d -- tables, views, materialized views, sequences and foreign tables
\dn -- schemas (\dn+ adds privileges)
\dv -- views
\dm -- materialized views
\di -- indexes, with the table each belongs to
\ds -- sequences
\df -- functions and procedures (\df+ adds volatility, owner, language and more)
\sf my_function -- a function's full CREATE statement
\dx -- installed extensions
\dp shop.orders -- access privileges (GRANTs) on a table
\ddp -- default privileges대부분의 \d 명령어는 패턴을 주거나 S를 붙이지 않으면 시스템 객체를 숨깁니다. \dfS는 내장 함수 목록을 보여 줍니다. 일반적인 \d 출력은 다음과 같습니다.
Table "shop.orders"
Column | Type | Collation | Nullable | Default
-------------+---------------+-----------+----------+------------------------------
id | bigint | | not null | generated always as identity
customer_id | bigint | | |
total | numeric(10,2) | | |
Indexes:
"orders_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES shop.customers(id)사용자와 role 목록 보기: \du
appdb=# \du
List of roles
Role name | Attributes
-----------+---------------------------------------------
app_user | 10 connections +
| Password valid until 2027-01-01 00:00:00+00
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS
reporting | Cannot loginPostgreSQL의 계정은 role 한 종류뿐이며, "사용자"는 로그인할 수 있는 role입니다. \du와 \dg는 같은 명령어입니다. PostgreSQL 16부터 \du에는 "Member of" 열이 없습니다. 누가 어떤 role의 멤버인지는 \drg로 ADMIN, INHERIT, SET 옵션과 함께 확인합니다. 사용자를 만들고 비밀번호를 설정하는 방법은 PostgreSQL에서 사용자 만들기를 참고하세요. \password alice를 쓰면 비밀번호가 history나 서버 로그에 남지 않게 변경할 수 있습니다.
출력, 실행 시간, 편집
\x auto -- expanded (one column per line) only when rows are too wide
\x -- toggle expanded output
\timing on -- print how long each statement took
\pset null '∅' -- show NULLs as something visible
\e -- edit the current query (or the last one) in your editor
\i setup.sql -- run a file
\ir child.sql -- run a file relative to the current script's folder
\o result.txt -- send query output to a file; \o alone sends it back
\watch 5 -- re-run the last query every 5 seconds (Ctrl-C stops)
\g -- run the query buffer again\e는 PSQL_EDITOR, EDITOR, VISUAL에 지정된 편집기를 엽니다(아무것도 없으면 vi). 저장하고 종료하면 ;로 끝나는 쿼리는 바로 실행됩니다. \x auto나 \timing on처럼 항상 쓰는 명령어는 ~/.psqlrc에 넣어 두세요.
\copy와 COPY의 차이
둘 다 테이블과 파일 사이에서 데이터를 옮깁니다. 차이는 누구의 파일이냐입니다.
-- psql reads/writes a file on YOUR machine; any user with access to the table can run it
\copy shop.orders TO 'orders.csv' WITH (FORMAT csv, HEADER)
\copy (SELECT id, total FROM shop.orders WHERE total > 100) TO 'big.csv' WITH (FORMAT csv, HEADER)
\copy shop.customers (email) FROM 'customers.csv' WITH (FORMAT csv, HEADER)
-- the SERVER reads/writes a file on the database host
COPY shop.orders TO '/var/lib/postgresql/orders.csv' WITH (FORMAT csv, HEADER);서버 측 COPY로 파일을 읽거나 쓰려면 슈퍼유저이거나 pg_write_server_files / pg_read_server_files의 멤버여야 합니다. 그렇지 않으면 PostgreSQL은 permission denied to COPY to a file 오류와 함께 \copy는 누구나 쓸 수 있다는 힌트를 보여 줍니다. RDS나 Supabase 같은 관리형 서비스에서는 어차피 서버 디스크에 접근할 수 없으니 \copy를 쓰세요. \copy는 한 줄에 작성해야 합니다. 다른 메타 명령어처럼 줄바꿈에서 끝나기 때문입니다.
도움말, 명령어 뒤의 SQL, 종료
\? -- every psql command
\? variables -- psql variables such as ON_ERROR_STOP
\h -- list SQL commands
\h CREATE INDEX -- syntax of one SQL command
\set ECHO_HIDDEN on -- show the catalog queries behind \d commands (or start psql -E)
\q -- quit (Ctrl-D works too)ECHO_HIDDEN은 카탈로그를 익히는 가장 빠른 방법입니다. 이 옵션을 켜고 \dn을 실행하면 psql이 결과 앞에 pg_namespace로 보낸 쿼리를 출력합니다.
psql 밖에서 SQL로 같은 작업하기
백슬래시 명령어는 psql에서만 동작합니다. GUI 클라이언트, 애플리케이션, 다른 드라이버에서는 카탈로그를 직접 조회하세요. 아래 쿼리는 현재 지원되는 모든 PostgreSQL에서 실행됩니다.
-- list databases (\l)
SELECT datname FROM pg_database WHERE NOT datistemplate ORDER BY datname;
-- current database and user (\conninfo)
SELECT current_database(), current_user, inet_server_addr(), inet_server_port();
-- list tables (\dt *.*, without system schemas)
SELECT schemaname, tablename
FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
ORDER BY 1, 2;
-- the standard way, also works in MySQL and SQL Server
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY 1, 2;
-- columns of one table (\d shop.orders)
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'shop' AND table_name = 'orders'
ORDER BY ordinal_position;
-- schemas (\dn)
SELECT nspname FROM pg_namespace
WHERE nspname NOT LIKE 'pg\_%' AND nspname <> 'information_schema'
ORDER BY 1;
-- views (\dv) and indexes (\di)
SELECT schemaname, viewname FROM pg_views WHERE schemaname NOT IN ('pg_catalog', 'information_schema');
SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = 'shop';
-- users and roles (\du)
SELECT rolname, rolsuper, rolcreatedb, rolcreaterole, rolcanlogin, rolvaliduntil
FROM pg_roles WHERE rolname !~ '^pg_' ORDER BY rolname;
-- sizes (\l+ and \dt+)
SELECT datname, pg_size_pretty(pg_database_size(datname)) FROM pg_database ORDER BY pg_database_size(datname) DESC;
SELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS total
FROM pg_class WHERE relkind = 'r' AND relnamespace = 'shop'::regnamespace
ORDER BY pg_total_relation_size(oid) DESC;알아 둘 차이가 하나 있습니다. information_schema는 권한이 조금이라도 있는 테이블과 컬럼만 보여 주지만, pg_tables를 비롯한 pg_catalog 뷰는 모든 것을 보여 줍니다. 한쪽 쿼리에는 테이블이 있는데 다른 쪽에는 없다면 권한 문제입니다.
psql 치트 시트
| 작업 | psql | 어디서나 쓰는 SQL |
|---|---|---|
| 데이터베이스 목록 | \l | SELECT datname FROM pg_database; |
| 데이터베이스 전환 | \c dbname | 다시 접속 |
| 현재 접속 정보 | \conninfo | SELECT current_database(), current_user; |
| 테이블 목록 | \dt, \dt schema.* | SELECT * FROM pg_tables; |
| 테이블 구조 보기 | \d table | information_schema.columns |
| 스키마 목록 | \dn | pg_namespace |
| 뷰 / 인덱스 목록 | \dv / \di | pg_views / pg_indexes |
| 함수 목록 | \df | information_schema.routines |
| 사용자 목록 | \du | SELECT rolname FROM pg_roles; |
| role 멤버십(16 이상) | \drg | pg_auth_members |
| 테이블 권한 | \dp table | information_schema.role_table_grants |
| 확장 | \dx | SELECT * FROM pg_extension; |
| 확장 출력 | \x auto | |
| 쿼리 실행 시간 | \timing on | |
| 쿼리 편집 | \e | |
| 파일 실행 | \i file.sql | |
| CSV로 내보내기 | \copy … TO 'f.csv' WITH (FORMAT csv, HEADER) | COPY … TO STDOUT |
| 비밀번호 변경 | \password user | ALTER ROLE … PASSWORD |
| 도움말 | \?, \h CMD | |
| 종료 | \q |
데모 데이터베이스에서 직접 해 보기
Tablux 데모는 공개된 읽기 전용 PostgreSQL 데이터베이스로, shop 스키마에 가상의 쇼핑몰 데이터가 들어 있습니다.
psql "host=aws-1-eu-west-2.pooler.supabase.com port=5432 dbname=postgres user=tablux_demo.nwazeancgffixzvpqgvc sslmode=require"
# password: tablux-demo-readonly
\dt shop.*
\d shop.orders
\x auto
SELECT * FROM shop.orders ORDER BY ordered_at DESC LIMIT 5;쓰기는 거부되므로 \copy … FROM과 CREATE는 실패합니다. 읽기 작업은 모두 동작합니다. 스키마를 탭해서 넘겨 보는 목록으로 보고 싶다면, Tablux로 Mac, iPhone, iPad에서 PostgreSQL에 접속해 SQL 편집기 옆에서 테이블과 뷰의 컬럼, 타입, 키를 확인할 수 있습니다.

자주 묻는 질문
PostgreSQL에서 모든 데이터베이스 목록을 보려면 어떻게 하나요?
psql에서 \l을 입력하세요(또는 셸에서 psql -l 실행). SQL로는 SELECT datname FROM pg_database WHERE NOT datistemplate ORDER BY datname;을 실행합니다.
\dt가 "Did not find any relations"라고 나오는 이유는 무엇인가요?
패턴 없는 \dt는 search_path에 있는 스키마의 테이블만 보여 줍니다. 테이블이 다른 스키마에 있을 가능성이 높습니다. \dt *.* 또는 \dt schema_name.*을 실행해 보거나, \conninfo로 올바른 데이터베이스에 접속했는지 확인하세요.
SHOW TABLES나 USE database에 해당하는 psql 명령어는 무엇인가요?
\dt는 테이블 목록을 보여 주고 \c dbname은 데이터베이스를 전환합니다. PostgreSQL은 각 연결이 하나의 데이터베이스에 속하기 때문에 USE 문이 없습니다.
PostgreSQL에서 사용자 목록을 보려면 어떻게 하나요?
psql에서 \du를 입력하거나, 어떤 클라이언트에서든 SELECT rolname FROM pg_roles;를 실행하세요. 로그인할 수 있는 role은 rolcanlogin = true입니다.
\copy와 COPY의 차이는 무엇인가요?
\copy는 psql이 실행하며, 내 권한으로 내 컴퓨터의 파일을 읽거나 씁니다. 파일 대상 COPY는 서버에서 실행되어 서버 디스크를 사용하며, 슈퍼유저 권한이나 pg_read_server_files / pg_write_server_files role이 필요합니다.
psql을 종료하려면 어떻게 하나요?
\q를 입력하고 Return을 누르거나 Control-D를 누르세요.
업데이트 2026-11-26