psql (postgresql client) command

    어찌보면 psql은 pgadmin과 더불어 Postgresql의 공식 client 중 하나이다. 그리고, 생각보다 많은 기능을 준다. CLI라는 점 때문에 무시할 법도 하지만, 오히려 psql 고유의 커맨드 때문에 이것을 더 선호하는 순간이 있기도 하다.

     

    Postgresql에 접속하기 위한 psql 옵션들

    접속에 사용하는 주요 파라미터는 다음과 같다.

    -d: 데이터베이스
    -h: 호스트 또는 IP
    -p: 포트
    -U: 사용자계정
    -w: 패스워드 없이 접속
    -W: 패스워드 확인

     

    help를 실행하자

    psql에 접속한 후에 help를 실행하면 다음과 같이 안내 메시지가 뜬다.

    postgres=# help
    You are using psql, the command-line interface to PostgreSQL.
    Type:  \copyright for distribution terms
           \h for help with SQL commands
           \? for help with psql commands
           \g or terminate with semicolon to execute query
           \q to quit

     

    \h: SQL commands - SQL문 관련

    Available help:
      ABORT                            ALTER SEQUENCE                   CREATE AGGREGATE                 CREATE SUBSCRIPTION              DROP EXTENSION                   DROP TEXT SEARCH PARSER          REVOKE
      ALTER AGGREGATE                  ALTER SERVER                     CREATE CAST                      CREATE TABLE                     DROP FOREIGN DATA WRAPPER        DROP TEXT SEARCH TEMPLATE        ROLLBACK
      ALTER COLLATION                  ALTER STATISTICS                 CREATE COLLATION                 CREATE TABLE AS                  DROP FOREIGN TABLE               DROP TRANSFORM                   ROLLBACK PREPARED
      ALTER CONVERSION                 ALTER SUBSCRIPTION               CREATE CONVERSION                CREATE TABLESPACE                DROP FUNCTION                    DROP TRIGGER                     ROLLBACK TO SAVEPOINT
      ALTER DATABASE                   ALTER SYSTEM                     CREATE DATABASE                  CREATE TEXT SEARCH CONFIGURATION DROP GROUP                       DROP TYPE                        SAVEPOINT
      ALTER DEFAULT PRIVILEGES         ALTER TABLE                      CREATE DOMAIN                    CREATE TEXT SEARCH DICTIONARY    DROP INDEX                       DROP USER                        SECURITY LABEL
      ALTER DOMAIN                     ALTER TABLESPACE                 CREATE EVENT TRIGGER             CREATE TEXT SEARCH PARSER        DROP LANGUAGE                    DROP USER MAPPING                SELECT
      ALTER EVENT TRIGGER              ALTER TEXT SEARCH CONFIGURATION  CREATE EXTENSION                 CREATE TEXT SEARCH TEMPLATE      DROP MATERIALIZED VIEW           DROP VIEW                        SELECT INTO
      ALTER EXTENSION                  ALTER TEXT SEARCH DICTIONARY     CREATE FOREIGN DATA WRAPPER      CREATE TRANSFORM                 DROP OPERATOR                    END                              SET
      ALTER FOREIGN DATA WRAPPER       ALTER TEXT SEARCH PARSER         CREATE FOREIGN TABLE             CREATE TRIGGER                   DROP OPERATOR CLASS              EXECUTE                          SET CONSTRAINTS
      ALTER FOREIGN TABLE              ALTER TEXT SEARCH TEMPLATE       CREATE FUNCTION                  CREATE TYPE                      DROP OPERATOR FAMILY             EXPLAIN                          SET ROLE
      ALTER FUNCTION                   ALTER TRIGGER                    CREATE GROUP                     CREATE USER                      DROP OWNED                       FETCH                            SET SESSION AUTHORIZATION
      ALTER GROUP                      ALTER TYPE                       CREATE INDEX                     CREATE USER MAPPING              DROP POLICY                      GRANT                            SET TRANSACTION
      ALTER INDEX                      ALTER USER                       CREATE LANGUAGE                  CREATE VIEW                      DROP PROCEDURE                   IMPORT FOREIGN SCHEMA            SHOW
      ALTER LANGUAGE                   ALTER USER MAPPING               CREATE MATERIALIZED VIEW         DEALLOCATE                       DROP PUBLICATION                 INSERT                           START TRANSACTION
      ALTER LARGE OBJECT               ALTER VIEW                       CREATE OPERATOR                  DECLARE                          DROP ROLE                        LISTEN                           TABLE
      ALTER MATERIALIZED VIEW          ANALYZE                          CREATE OPERATOR CLASS            DELETE                           DROP ROUTINE                     LOAD                             TRUNCATE
      ALTER OPERATOR                   BEGIN                            CREATE OPERATOR FAMILY           DISCARD                          DROP RULE                        LOCK                             UNLISTEN
      ALTER OPERATOR CLASS             CALL                             CREATE POLICY                    DO                               DROP SCHEMA                      MOVE                             UPDATE
      ALTER OPERATOR FAMILY            CHECKPOINT                       CREATE PROCEDURE                 DROP ACCESS METHOD               DROP SEQUENCE                    NOTIFY                           VACUUM
      ALTER POLICY                     CLOSE                            CREATE PUBLICATION               DROP AGGREGATE                   DROP SERVER                      PREPARE                          VALUES
      ALTER PROCEDURE                  CLUSTER                          CREATE ROLE                      DROP CAST                        DROP STATISTICS                  PREPARE TRANSACTION              WITH
      ALTER PUBLICATION                COMMENT                          CREATE RULE                      DROP COLLATION                   DROP SUBSCRIPTION                REASSIGN OWNED
      ALTER ROLE                       COMMIT                           CREATE SCHEMA                    DROP CONVERSION                  DROP TABLE                       REFRESH MATERIALIZED VIEW
      ALTER ROUTINE                    COMMIT PREPARED                  CREATE SEQUENCE                  DROP DATABASE                    DROP TABLESPACE                  REINDEX
      ALTER RULE                       COPY                             CREATE SERVER                    DROP DOMAIN                      DROP TEXT SEARCH CONFIGURATION   RELEASE SAVEPOINT
      ALTER SCHEMA                     CREATE ACCESS METHOD             CREATE STATISTICS                DROP EVENT TRIGGER               DROP TEXT SEARCH DICTIONARY      RESET

     

    psql 주요 명령어

    전체 명령어는 굉장히 많다. 아래 섹션을 참고하자. 우선, 주요 명령어만 몇 개 나열하면 다음과 같다.

    • 기본적으로 \(backslash) 뒤에 명령어를 입력한다.
    • *나 ? 와 같은 와일드카드 문자를 사용할 수 있다.

    제어 명령어

    \s: 실행한 명령어 히스토리
    \s filename: 실행한 명령어 히스토리를 특정 파일로 저장
    \e: 쿼리를 편집 한 후 실행
    \e filename: 특정 파일에 쿼리를 저장 후 실행
    \w filename: 특정 파일에 쿼리 저장
    \o filename: 특정 파일에 실행 결과 저장
    \q: 종료하기

    정보 조회 명령어

    데이터 베이스의 정보를 조회할 수 있는 유용한 명령어들을 제공하며, \뒤에 알파벳을 붙여서 실행하는 형태로 구성되어 있다.

    \l: 데이터 베이스 리스트
    \dn: 스키마 목록
    \db: 테이블 스페이스 목록
    \df: 함수 목록
    \du: 사용자 목록
    \di: 해당 스키마의 인덱스 정보
    \ds: 해당 스키마의 시퀀스 정보
    \dt: 해당 스키마의 테이블 정보
    \dv: 해당 스키마의 view 정보
    \dS: 시스템 테이블 정보
    \dp: 접근권한, 테이블, 뷰, 시퀀스 정보
    \drds: 정의된 설정 정보
    

     

    psql 고유 명령어 (전체)

    \?를 실행하면 psql 고유 명령어를 보여준다. (굉장히 많다.)

    General
      \copyright             show PostgreSQL usage and distribution terms
      \crosstabview [COLUMNS] execute query and display results in crosstab
      \errverbose            show most recent error message at maximum verbosity
      \g [(OPTIONS)] [FILE]  execute query (and send results to file or |pipe);
                             \g with no arguments is equivalent to a semicolon
      \gdesc                 describe result of query, without executing it
      \gexec                 execute query, then execute each value in its result
      \gset [PREFIX]         execute query and store results in psql variables
      \gx [(OPTIONS)] [FILE] as \g, but forces expanded output mode
      \q                     quit psql
      \watch [SEC]           execute query every SEC seconds
    
    Help
      \? [commands]          show help on backslash commands
      \? options             show help on psql command-line options
      \? variables           show help on special variables
      \h [NAME]              help on syntax of SQL commands, * for all commands
    
    Query Buffer
      \e [FILE] [LINE]       edit the query buffer (or file) with external editor
      \ef [FUNCNAME [LINE]]  edit function definition with external editor
      \ev [VIEWNAME [LINE]]  edit view definition with external editor
      \p                     show the contents of the query buffer
      \r                     reset (clear) the query buffer
      \s [FILE]              display history or save it to file
      \w FILE                write query buffer to file
    
    Input/Output
      \copy ...              perform SQL COPY with data stream to the client host
      \echo [-n] [STRING]    write string to standard output (-n for no newline)
      \i FILE                execute commands from file
      \ir FILE               as \i, but relative to location of current script
      \o [FILE]              send all query results to file or |pipe
      \qecho [-n] [STRING]   write string to \o output stream (-n for no newline)
      \warn [-n] [STRING]    write string to standard error (-n for no newline)
    
    Conditional
      \if EXPR               begin conditional block
      \elif EXPR             alternative within current conditional block
      \else                  final alternative within current conditional block
      \endif                 end conditional block
    
    Informational
      (options: S = show system objects, + = additional detail)
      \d[S+]                 list tables, views, and sequences
      \d[S+]  NAME           describe table, view, sequence, or index
      \da[S]  [PATTERN]      list aggregates
      \dA[+]  [PATTERN]      list access methods
      \dAc[+] [AMPTRN [TYPEPTRN]]  list operator classes
      \dAf[+] [AMPTRN [TYPEPTRN]]  list operator families
      \dAo[+] [AMPTRN [OPFPTRN]]   list operators of operator families
      \dAp    [AMPTRN [OPFPTRN]]   list support functions of operator families
      \db[+]  [PATTERN]      list tablespaces
      \dc[S+] [PATTERN]      list conversions
      \dC[+]  [PATTERN]      list casts
      \dd[S]  [PATTERN]      show object descriptions not displayed elsewhere
      \dD[S+] [PATTERN]      list domains
      \ddp    [PATTERN]      list default privileges
      \dE[S+] [PATTERN]      list foreign tables
      \det[+] [PATTERN]      list foreign tables
      \des[+] [PATTERN]      list foreign servers
      \deu[+] [PATTERN]      list user mappings
      \dew[+] [PATTERN]      list foreign-data wrappers
      \df[anptw][S+] [PATRN] list [only agg/normal/procedures/trigger/window] functions
      \dF[+]  [PATTERN]      list text search configurations
      \dFd[+] [PATTERN]      list text search dictionaries
      \dFp[+] [PATTERN]      list text search parsers
      \dFt[+] [PATTERN]      list text search templates
      \dg[S+] [PATTERN]      list roles
      \di[S+] [PATTERN]      list indexes
      \dl                    list large objects, same as \lo_list
      \dL[S+] [PATTERN]      list procedural languages
      \dm[S+] [PATTERN]      list materialized views
      \dn[S+] [PATTERN]      list schemas
      \do[S]  [PATTERN]      list operators
      \dO[S+] [PATTERN]      list collations
      \dp     [PATTERN]      list table, view, and sequence access privileges
      \dP[itn+] [PATTERN]    list [only index/table] partitioned relations [n=nested]
      \drds [PATRN1 [PATRN2]] list per-database role settings
      \dRp[+] [PATTERN]      list replication publications
      \dRs[+] [PATTERN]      list replication subscriptions
      \ds[S+] [PATTERN]      list sequences
      \dt[S+] [PATTERN]      list tables
      \dT[S+] [PATTERN]      list data types
      \du[S+] [PATTERN]      list roles
      \dv[S+] [PATTERN]      list views
      \dx[+]  [PATTERN]      list extensions
      \dy     [PATTERN]      list event triggers
      \l[+]   [PATTERN]      list databases
      \sf[+]  FUNCNAME       show a function's definition
      \sv[+]  VIEWNAME       show a view's definition
      \z      [PATTERN]      same as \dp
    
    Formatting
      \a                     toggle between unaligned and aligned output mode
      \C [STRING]            set table title, or unset if none
      \f [STRING]            show or set field separator for unaligned query output
      \H                     toggle HTML output mode (currently off)
      \pset [NAME [VALUE]]   set table output option
                             (border|columns|csv_fieldsep|expanded|fieldsep|
                             fieldsep_zero|footer|format|linestyle|null|
                             numericlocale|pager|pager_min_lines|recordsep|
                             recordsep_zero|tableattr|title|tuples_only|
                             unicode_border_linestyle|unicode_column_linestyle|
                             unicode_header_linestyle)
      \t [on|off]            show only rows (currently off)
      \T [STRING]            set HTML <table> tag attributes, or unset if none
      \x [on|off|auto]       toggle expanded output (currently off)
    
    Connection
      \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
                             connect to new database (currently "postgres")
      \conninfo              display information about current connection
      \encoding [ENCODING]   show or set client encoding
      \password [USERNAME]   securely change the password for a user
    
    Operating System
      \cd [DIR]              change the current working directory
      \setenv NAME [VALUE]   set or unset environment variable
      \timing [on|off]       toggle timing of commands (currently off)
      \! [COMMAND]           execute command in shell or start interactive shell
    
    Variables
      \prompt [TEXT] NAME    prompt user to set internal variable
      \set [NAME [VALUE]]    set internal variable, or list all if no parameters
      \unset NAME            unset (delete) internal variable
    
    Large Objects
      \lo_export LOBOID FILE
      \lo_import FILE [COMMENT]
      \lo_list
      \lo_unlink LOBOID      large object operations

    댓글

    Designed by JB FACTORY