A crash course in PostgreSQL, part 2

15.09.2011

There are several important items to note here. There are two copy commands: a SQL COPY command, and a psql \copy command. These are close siblings, but not twins. Using COPY means the postgres user must have read permissions to the text file. Using \copy means the system user who is logged into psql must have read permissions on the file; for example, the "carla" user can import from a text file in her home directory.

The COPY command is faster because it runs on the server, where the \copy command runs from the psql client to the server. On success it returns a COPY [count] message telling how many rows it copied. It also saves a fair bit of hassle because you can run scripts without having to worry about who owns your source data file.

\copy does not require a terminating semi-colon, while COPY does. You may also elect to use a different delimiter, such as a comma or a pipe symbol instead of tabs. Make sure there are no spaces on either side of your delimiter, then specify your chosen delimiter like this COPY example:

testdb=# COPY comics FROM '/etc/postgresql/9.0/main/freakbros.txt'

USING DELIMITERS ',';