본문 바로가기

Database/PostgreSQL

알아두면 유용한 psql 명령어 정리

반응형

PSQL

보통 PostgreSQL을 설치할 때 Client Tool인 pgAdmin이 같이 설치되고, 대부분 GUI 환경에서 pgAdmin을 사용하기 때문에 PSQL의 존재조차 모를 때가 있다. (필자는 PostgreSQL 처음 사용했을 때 psql의 존재를 1년 정도는 몰랐었다.)  그러나 때때로 오직 Terminal로 DB 상태를 확인해야 할 상황이 생기게 되는데, 그 때 psql이 필요하고, 이 포스팅이 도움이 될 것이다.

PSQL을 통한 PostgreSQL DB 접속

Linux에 PostgreSQL을 설치한 경우 아래의 경로에서 확인할 수 있으며 바로 실행이 가능하다. 

...
[root@localhost sedtest]# ls -la /usr/pgsql-11/bin/
total 10028
...
-rwxr-xr-x. 1 root root  606696 Jun 20 02:51 psql
...

psql에서 사용할 수 있는 Command들와 Option들은 아래와 같으며, 아래 나열된 Option들 중에 Connection Option Part와 -d (or --dbname) option 등을 이용해 DB에 접속하면 psql 실행 모드가 활성화 된다.

psql 사용법
...
[root@localhost ~]# 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: "root")
  -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: "root")
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)

For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.

Report bugs to <pgsql-bugs@postgresql.org>.

 

psql을 통한 DB 접속 예

...
# localhost의 5432 port로 Postgresql 접속을 시도. Target DB는 현재 사용자 이름과 동일한 'browndwarf'
[browndwarf@localhost ~]$ psql

# localhost의 5432 port로 Postgresql 접속을 시도. 접속 User는 'postgres'이며 Target DB는 접속 User와 동일한 'postgres'
[browndwarf@localhost ~]$ psql -U postgres

# 10.52.0.1의 5432 port로 Postgresql 접속을 시도. 접속 User는 'browndwarf'이며 Target DB는 현재 사용자 이름과 동일한 'browndwarf'
[browndwarf@localhost ~]$ psql -h 10.52.0.1 

# 10.52.0.1의 5432 port로 Postgresql 접속을 시도. 접속 User는 'posgres'이며 Target DB는 접속 User와 동일한 'browndwarf'
[browndwarf@localhost ~]$ psql -h 10.52.0.1 -U posgres

# 10.52.0.1의 5432 port로 Postgresql 접속을 시도. 접속 User는 'browndwarf'이며 Target DB는 'galaxy'
[browndwarf@localhost ~]$ psql -h 10.52.0.1 -U browndwarf galaxy
[browndwarf@localhost ~]$ psql -h 10.52.0.1 -U browndwarf -d galaxy


# 10.52.0.1의 9000 port로 Postgresql 접속을 시도. 접속 User는 'browndwarf'이며 Target DB는 'galaxy'
[browndwarf@localhost ~]$ psql -h 10.52.0.1 -p 9000 -U browndwarf galaxy
[browndwarf@localhost ~]$ psql -h 10.52.0.1 -p 9000 -U browndwarf -d galaxy

 

PSQL 주요 Command

1. \c : 접속한 DB Instance를 변경.

여러 DB Instance들이 있고, 정보를 조회나 Query 실행 대상 DB Instance를 변경할 때 사용한다. 

 

사용법

\c [DB Name] [Connection User}

사용예

...
# Database Instance 'db1'에 user 'browndwarf'로 접속
postgres=# \c db1 browndwarf
You are now connected to database "db1" as user "browndwarf".
...

# Database Instance 'postgres'에 user 'postgres'로 접속
db1=# \c postgres postgres
You are now connected to database "postgres" as user "postgres".
postgres=# 

 

2. \list(or \l), \d[ t | s | f | v | u ] : 목록 조회용 명령어.

현재 접속한 DB에서 여러 목록 정보를 조회(단, \list, \du는 접속한 DB와 무관하게 동작)할 때 사용한다. Command 별로 조회되는 목록은 다음과 같다.

  • \list(or \l) : 전체 Database Instance 목록
  • \dt : 접속한 DB Instance의 Table 목록
  • \ds : Sequence 목록
  • \df : Function 목록
  • \dv : View 목록
  • \du : User 목록

위 명령 외에도 여러가지가 더 있지만 크게 사용하지 않아 따로 언급하지 않았다. (예를 들면 \dn은 Schema 목록, \di는 Index 목록 조회시 사용한다. \?를 통해 추가 명령어들을 조회할 수 있다.)

 

'\list' 사용예 ; 전체 DB Instance list 조회

...
galaxy=# \list
                                     List of databases
      Name      |   Owner    | Encoding |   Collate   |    Ctype    |   Access privileges   
----------------+------------+----------+-------------+-------------+-----------------------
 battlefield    | browndwarf | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | 
 db1            | browndwarf | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | 
 db2            | browndwarf | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | 
 galaxy         | browndwarf | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | 
 postgres       | postgres   | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | 
 template0      | postgres   | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | =c/postgres          +
                |            |          |             |             | postgres=CTc/postgres
 template1      | postgres   | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | =c/postgres          +
                |            |          |             |             | postgres=CTc/postgres
 test           | browndwarf | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | 
(8 rows)

 

'\dt' 사용예 ; 현재 접속한 DB Instance의 Table list 조회

...
galaxy=# \dt
                  List of relations
 Schema |         Name          | Type  |   Owner    
--------+-----------------------+-------+------------
 public | databasechangelog     | table | browndwarf
 public | databasechangeloglock | table | browndwarf
 public | planet                | table | browndwarf
 public | star                  | table | browndwarf
(4 rows)

 

'\ds' 사용예 ; 현재 접속한 DB Instance의 Sequence list 조회

...
galaxy=# \ds
               List of relations
 Schema |     Name      |   Type   |   Owner    
--------+---------------+----------+------------
 public | planet_id_seq | sequence | browndwarf
 public | star_id_seq   | sequence | browndwarf
(2 rows)

 

'\df' 사용예 ; 현재 접속한 DB Instance의 Function list 조회

...
galaxy=# \df
                        List of functions
 Schema |  Name  | Result data type | Argument data types  | Type 
--------+--------+------------------+----------------------+------
 public | fn_sum | integer          | a integer, b integer | func
(1 row)

 

'\du' 사용예 ; User list 조회

...
galaxy=# \du
                                    List of roles
  Role name  |                         Attributes                         | Member of 
-------------+------------------------------------------------------------+-----------
 aims        | Superuser                                                  | {}
 browndwarf  | Superuser                                                  | {}
 postgres    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 replication | Replication                                                | {}

 

그리고, 이 Command들은 모두 뒤에 '+'를 붙혀서 상세 정보를 추가할 수 있다. 추가되는 상세 정보 항목들은 Command별로 약간씩 다르다. 아래는 상세 정보를 포함한 Table 목록 조회의 예이다.

 

'\dt+' 사용예

...
galaxy=# \dt+
                               List of relations
 Schema |         Name          | Type  |   Owner    |    Size    | Description 
--------+-----------------------+-------+------------+------------+-------------
 public | databasechangelog     | table | browndwarf | 8192 bytes | 
 public | databasechangeloglock | table | browndwarf | 8192 bytes | 
 public | planet                | table | browndwarf | 53 MB      | 
 public | star                  | table | browndwarf | 81 MB      | 
(4 rows)

 

3. \d : 특정 Table의 상세 정보를 조회

사용법

\d  [table name]

사용예 ; 'galaxy' DB에 있는 'planet' table 정보 조회

...
galaxy=# \d planet
                                         Table "public.planet"
   Column    |            Type             | Collation | Nullable |              Default               
-------------+-----------------------------+-----------+----------+------------------------------------
 id          | bigint                      |           | not null | nextval('planet_id_seq'::regclass)
 createdtime | timestamp without time zone |           |          | 
 description | character varying(255)      |           |          | 
 distance    | integer                     |           | not null | 
 name        | character varying(255)      |           |          | 
 radius      | integer                     |           | not null | 
 updatedtime | timestamp without time zone |           |          | 
 star_id     | bigint                      |           |          | 
Indexes:
    "planet_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "fkc4fuaxedn05182lfgl6jadaqi" FOREIGN KEY (star_id) REFERENCES star(id)

 

4. \g, \s : Command 실행 History 조회 및 활용
  • \g : 방금 전에 실행했던 명령어를 실행. (↑ 키가 사용 가능한 경우 쓰일 일은 없다.)
  • \s : 이전에 실행했던 명령어 전체 List 조회.

'\g' 사용예 : 별다른 Query문 없이 이전에 실행한 Query와 동일한 Query가 실행된다.

...
galaxy=# SELECT fn_sum(5,6);
 fn_sum 
--------
     11
(1 row)

galaxy=# \g
 fn_sum 
--------
     11
(1 row)

 

'\s' 사용예 : 이전에 실행 내역 전체 나열. 예에서는 마지막 2개의 실행 내역 포함해서 전체를 나열.

...
galaxy=# SELECT * FROM star limit 1;
   id   |       createdtime       | description | mass |   name    | pictureurl | radius | class | temperature |       updatedtime       
--------+-------------------------+-------------+------+-----------+------------+--------+-------+-------------+-------------------------
 721784 | 2019-08-03 05:37:42.915 | Mass Test   |   91 | Glisse-17 |            |   8000 |       |          68 | 2019-08-03 05:37:42.915
(1 row)

galaxy=# SELECT * FROM planet limit 1;
 id |       createdtime       | description | distance |    name    | radius |       updatedtime       | star_id 
----+-------------------------+-------------+----------+------------+--------+-------------------------+---------
  1 | 2019-08-02 17:16:16.664 | Mass Test   |       89 | Glisse-36d |     72 | 2019-08-02 17:16:16.664 |  135352
(1 row)

galaxy=# \s
...
SELECT * FROM star limit 1;
SELECT * FROM planet limit 1;
\s
galaxy=# 

 

5. \h, \? : 도움말 조회
  • \h : SQL command 관련 도움말
  • \? : psql Command  관련 도움말

'\?' 사용예

...
galaxy=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display results in crosstab
...

  \lo_list
  \lo_unlink LOBOID      large object operations
...

 

'\h' 사용예

...
galaxy=# \h
Available help:
  ABORT                            ALTER TEXT SEARCH TEMPLATE       CREATE PUBLICATION               DROP FUNCTION                    IMPORT FOREIGN SCHEMA
  ALTER AGGREGATE                  ALTER TRIGGER                    CREATE ROLE                      DROP GROUP                       INSERT
  ALTER COLLATION                  ALTER TYPE                       CREATE RULE                      DROP INDEX                       LISTEN
...
  ALTER TABLE                      CREATE OPERATOR                  DROP DOMAIN                      END                              UPDATE
  ALTER TABLESPACE                 CREATE OPERATOR CLASS            DROP EVENT TRIGGER               EXECUTE                          VACUUM
  ALTER TEXT SEARCH CONFIGURATION  CREATE OPERATOR FAMILY           DROP EXTENSION                   EXPLAIN                          VALUES
  ALTER TEXT SEARCH DICTIONARY     CREATE POLICY                    DROP FOREIGN DATA WRAPPER        FETCH                            WITH
  ALTER TEXT SEARCH PARSER         CREATE PROCEDURE                 DROP FOREIGN TABLE               GRANT                            

 

6. \x, \a, \H : Query 결과 Display 설정
  • \x : Column들을 한줄로 조회하기 힘들 때, Column을 세로로 배치해서 Display하는 기능 on/off.
  • \a : Column Align on/off. Default는 Align On 상태.
  • \H(대문자 유의) : Column 명과 결과 값을 HTML Table 형식으로 Display하는 기능 on/off

'\x' 사용예 : Column이 H-Scroll 넘겨 생성될 때 유용. 단, 조회 목록 숫자를 조정할 필요가 있음.

...
galaxy=# SELECT * FROM star limit 1;
   id   |       createdtime       | description | mass |   name    | pictureurl | radius | class | temperature |       updatedtime       
--------+-------------------------+-------------+------+-----------+------------+--------+-------+-------------+-------------------------
 721784 | 2019-08-03 05:37:42.915 | Mass Test   |   91 | Glisse-17 |            |   8000 |       |          68 | 2019-08-03 05:37:42.915
(1 row)

galaxy=# \x
Expanded display is on.
galaxy=# SELECT * FROM star limit 1;
-[ RECORD 1 ]------------------------
id          | 721784
createdtime | 2019-08-03 05:37:42.915
description | Mass Test
mass        | 91
name        | Glisse-17
pictureurl  | 
radius      | 8000
class       | 
temperature | 68
updatedtime | 2019-08-03 05:37:42.915

galaxy=# \x
Expanded display is off.
galaxy=# SELECT * FROM star limit 1;
   id   |       createdtime       | description | mass |   name    | pictureurl | radius | class | temperature |       updatedtime       
--------+-------------------------+-------------+------+-----------+------------+--------+-------+-------------+-------------------------
 721784 | 2019-08-03 05:37:42.915 | Mass Test   |   91 | Glisse-17 |            |   8000 |       |          68 | 2019-08-03 05:37:42.915
(1 row)

 

'\a' 사용예 : Default는 Align On 상태. \a를 실행하면 Off 되면서 아래와 같이 Space에 의한 Align 기능이 사라짐.

...
galaxy=# \a
Output format is unaligned.
galaxy=# SELECT * FROM star limit 1;
id|createdtime|description|mass|name|pictureurl|radius|class|temperature|updatedtime
721784|2019-08-03 05:37:42.915|Mass Test|91|Glisse-17||8000||68|2019-08-03 05:37:42.915
(1 row)
galaxy=# \a
Output format is aligned.
galaxy=# 

 

'\H' 사용예 : HTML의 <table> tag를 활용해서 출력하고 있다.

...
galaxy=# \H
Output format is html.
galaxy=# SELECT * FROM star limit 1;
<table border="1">
  <tr>
    <th align="center">id</th>
    <th align="center">createdtime</th>
    <th align="center">description</th>
    <th align="center">mass</th>
    <th align="center">name</th>
    <th align="center">pictureurl</th>
    <th align="center">radius</th>
    <th align="center">class</th>
    <th align="center">temperature</th>
    <th align="center">updatedtime</th>
  </tr>
  <tr valign="top">
    <td align="right">721784</td>
    <td align="left">2019-08-03 05:37:42.915</td>
    <td align="left">Mass Test</td>
    <td align="right">91</td>
    <td align="left">Glisse-17</td>
    <td align="left">&nbsp; </td>
    <td align="right">8000</td>
    <td align="left">&nbsp; </td>
    <td align="right">68</td>
    <td align="left">2019-08-03 05:37:42.915</td>
  </tr>
</table>
<p>(1 row)<br />
</p>
galaxy=# \H
Output format is aligned.
galaxy=# 

 

7. \timing : Query 실행 시간 표시. 

Query 실행 시간 Display 기능을 on/off 한다. 주로 Query Tuning할 때 실행 시간 확인시 사용한다.

 

사용예

...
galaxy=# \timing
Timing is on.
galaxy=# \i test.sql
   id   |   name    | class | radius |       createdtime       
--------+-----------+-------+--------+-------------------------
 721784 | Glisse-17 |       |   8000 | 2019-08-03 05:37:42.915
 721951 | Glisse-8  |       |   9000 | 2019-08-03 05:37:46.159
 722011 | Glisse-31 |       |   8000 | 2019-08-03 05:37:47.822
 723699 | Glisse-24 |       |   7000 | 2019-08-03 05:38:45.349
 723838 | Glisse-61 |       |   2000 | 2019-08-03 05:38:48.969
 723875 | Glisse-25 |       |   2000 | 2019-08-03 05:38:50.08
 724205 | Glisse-12 |       |   8000 | 2019-08-03 05:38:58.467
 724321 | Glisse-12 |       |   3000 | 2019-08-03 05:39:02.101
 724325 | Glisse-41 |       |   3000 | 2019-08-03 05:39:02.215
 724766 | Glisse-4  |       |   5000 | 2019-08-03 05:39:14.993
(10 rows)

Time: 4.896 ms
galaxy=# \timing
Timing is off.
...

 

8. /i : 외부 파일을 통한 Query 실행

길고 복잡한 Query같은 경우 외부 편집기에서 Query를 작성한 후에 실행하는 것이 편하기 때문에, 파일에 쓰여진 Query를 실행하는 명령어 이다.

 

사용법

/i  [File Name]

'/i' 사용예 : test.sql에 있는 Query문을 psql 에서 실행 시킨 예.

...
# Query 파일 확인
[browndwarf@localhost work]# cat test.sql
SELECT
	id, name, class, radius, createdTime
FROM
	star
WHERE
	temperature=68
limit 10;
...

# psql로 DB 접속
[browndwarf@localhost work]# psql -h localhost -U browndwarf -p 5432 -d galaxy
psql (11.4)
Type "help" for help.

# psql에서 Query 파일 실행
galaxy=# \i test.sql
   id   |   name    | class | radius |       createdtime       
--------+-----------+-------+--------+-------------------------
 721784 | Glisse-17 |       |   8000 | 2019-08-03 05:37:42.915
 721951 | Glisse-8  |       |   9000 | 2019-08-03 05:37:46.159
 722011 | Glisse-31 |       |   8000 | 2019-08-03 05:37:47.822
 723699 | Glisse-24 |       |   7000 | 2019-08-03 05:38:45.349
 723838 | Glisse-61 |       |   2000 | 2019-08-03 05:38:48.969
 723875 | Glisse-25 |       |   2000 | 2019-08-03 05:38:50.08
 724205 | Glisse-12 |       |   8000 | 2019-08-03 05:38:58.467
 724321 | Glisse-12 |       |   3000 | 2019-08-03 05:39:02.101
 724325 | Glisse-41 |       |   3000 | 2019-08-03 05:39:02.215
 724766 | Glisse-4  |       |   5000 | 2019-08-03 05:39:14.993
(10 rows)
...

 

9. \e, \ef ; 외부 Editor 사용
  • \e : \i가 이미 만들어진 File 안에 있는 Query를 수행하는데 비해, \e는 외부 편집기를 통해 Query를 작성해서 실행할 때 사용한다. Linux에서는 vi가, Window에서는 메모장이 Default Editor로 실행된다. 
  • \ef : \e와 유사하나 FUNCTION 편집할 때 사용한다는 측면에서 상이하다. (view를 편집할 때 사용하는 \ev도 있다.)

사용법

\e  [file name]

\ef  [function name]

Remark : '\e'의 뒤에 [File Name]을 생략하면 Buffer를 통해 작성하게 되고, 실행후에는 작성한 Query가 사라지게 된다. 만약 존재하지 않는 File Name을 사용하면 신규로 파일이 만들어 지는 것이 아니라 오류가 발생하며 종료된다.(*)

 

'\e' 사용예 : \e를 실행하면 vi editor로 전환되고, Query 작성 후에 :wq로 빠져나오면 psql에서 Query가 실행되는 예이다.

...
# psql에서 \e 실행
galaxy=# \e
...
-- Linux에서는 vi가 실행되며, vi에서 아래의 query를 편집 후 :wq로 저장 후 종료
SELECT * FROM star limit 1;
~
...
# 다시 psql 화면에서 Editor로 편집한 query를 실행
   id   |       createdtime       | description | mass |   name    | pictureurl | radius | class | temperature |       updatedtime       
--------+-------------------------+-------------+------+-----------+------------+--------+-------+-------------+-------------------------
 721784 | 2019-08-03 05:37:42.915 | Mass Test   |   91 | Glisse-17 |            |   8000 |       |          68 | 2019-08-03 05:37:42.915
(1 row)

galaxy=# 

 

'\ef' 사용예 : 현재 fn_sum이라는 FUNCTION이 존재하고 있고, 해당 FUNCTION을 \ef로 호출하면 vi로 편집하게 된다. :wq로 나오면 기존 FUNCTION이 replace된다.

...
galaxy=# \df
                        List of functions
 Schema |  Name  | Result data type | Argument data types  | Type 
--------+--------+------------------+----------------------+------
 public | fn_sum | integer          | a integer, b integer | func
(1 row)

galaxy=# \ef fn_sum
...
CREATE OR REPLACE FUNCTION public.fn_sum(a integer, b integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$BEGIN
return a+b;
END;$function$
~                
...
galaxy-# ;
CREATE FUNCTION

 

11. \! : shell command 실행.

psql에서 shell command를 실행할 때 사용한다. 주로 화면을 지우거나 '\i', '\e' command를 위해 현재 경로에 있는 파일 List를 조회하거나 Path를 변경할 때 사용한다. (!뒤에 한 칸의 공백이 있음을 유의하자)

 

사용법

\! [shell command]

 

ex)

\! clear : 화면 Clear

\! pwd : 현재 경로 확인

\! ls : 현재 경로의 파일 확인

\! cd [Path] : [Path]로 경로 이동

 

12. \q : psql 종료

'\q' 사용예

...
galaxy=# \q
[browndwarf@localhost ~]# 
...

 

(*) Appendix

새로운 sql File을 만들고 그 파일을 편집해 실행하려면 아래와 같이 약간의 꼼수가 필요하다. (아래 내용 참조)

 

...
# '\e'를 실행하려는 위치에 a.sql이 존재하지 않아 아래와 같이 Error 발생
galaxy=# \e a.sql
a.sql: No such file or directory
...
# shell command 중 touch를 이용해서 a.sql를 빈 파일로 생성
galaxy=# \! touch a.sql
galaxy=# \! ls -la
total 1664
drwxr-xr-x.  7 root root    4096 Dec 10 15:29 .
dr-xr-x---. 24 root root    4096 Aug 30 15:16 ..
-rw-r--r--.  1 root root      31 Dec 10 15:29 a.sql
...
# 빈 파일을 생성 후 '\e'로 파일 편집을 시도하면 vi로 진입해서 편집이 가능해진다.
galaxy=# \e a.sql
...
-- vi를 통해 a.sql 파일을 편집한다. 
SELECT * FROM planet limit 2;
~
...
# vi를 끝내면 아래와 같이 Query 결과가 나온다.
 id |       createdtime       | description | distance |    name    | radius |       updatedtime       | star_id 
----+-------------------------+-------------+----------+------------+--------+-------------------------+---------
  1 | 2019-08-02 17:16:16.664 | Mass Test   |       89 | Glisse-36d |     72 | 2019-08-02 17:16:16.664 |  135352
  2 | 2019-08-02 17:16:16.664 | Mass Test   |       67 | Glisse-70z |     47 | 2019-08-02 17:16:16.664 |   68467
(2 rows)

 

Reference