DEV Community

Chiheb Abiza
Chiheb Abiza

Posted on

1

PostgreSQL CSV Import and Export Guide

Importing Data from a CSV File

Prerequisites

  • Ensure the PostgreSQL table is already created
  • CSV file should match the table schema
  • The \COPY command is run from the psql command-line interface

Basic Import Syntax

\COPY table_name FROM '/path/to/file.csv' 
DELIMITER ',' 
CSV HEADER;
Enter fullscreen mode Exit fullscreen mode

Example Scenario

Sample CSV File (students.csv)

id,name,age,grade
1,John Doe,20,A
2,Jane Smith,22,B
3,Mike Brown,21,A-
Enter fullscreen mode Exit fullscreen mode

Import Command

\COPY students FROM '/path/to/students.csv' 
DELIMITER ',' 
CSV HEADER;
Enter fullscreen mode Exit fullscreen mode

Exporting Data to a CSV File

Basic Export Syntax

\COPY table_name TO '/path/to/exported_file.csv' 
DELIMITER ',' 
CSV HEADER;
Enter fullscreen mode Exit fullscreen mode

Example Scenario

Export Command

\COPY students TO '/path/to/exported_students.csv' 
DELIMITER ',' 
CSV HEADER;
Enter fullscreen mode Exit fullscreen mode

Important Notes

  • The HEADER option includes column names in the first row
  • Use ',' as the delimiter for standard CSV files
  • Ensure the PostgreSQL user has file system access to the specified paths
  • For large files, consider using COPY instead of \COPY (requires superuser privileges)

Common Options

  • CSV: Specifies CSV format
  • DELIMITER ',': Sets the field separator
  • HEADER: Indicates the first row contains column names

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs