# How to import and export a PostgreSQL database

We always recommend to dump and import through the command line, if possible. This documentation will
explain how to do this securely.

## PostgreSQL export

For most databases (only a couple of gigabytes big), you can dump the database with this command:

```bash
pg_dump -U DBUsername DatabaseName > DBNAME.sql
```

For larger databases (tens of gigabytes or bigger), compress the database to conserve disk space and
speed up transfer:

```bash
pg_dump -U DBUsername DatabaseName | gzip -3 -v > test.gz
```

> [!NOTE]
> As an alternative, you can dump to the compressed custom format instead of piping through `gzip`.
> A custom-format dump restores faster and lets you restore selectively with `pg_restore`:
>
> ```bash
> pg_dump -U DBUsername -Fc DatabaseName > DBNAME.dump
> ```

## Transferring the database

Use `scp` to transfer the file:

```bash
scp FileName user@HostnameOrIP:Path/To/Folder
```

> [!NOTE]
> To place the file in the user's home directory, remove everything after the colon.

## Importing the database

```bash
psql -U DBUsername DatabaseName < dbname
```

Or, if compressed:

```bash
gunzip -c dbname.gz | psql -U DBUsername DatabaseName
```

> [!NOTE]
> If you dumped to the custom format, restore it with `pg_restore` instead:
>
> ```bash
> pg_restore -U DBUsername -d DatabaseName DBNAME.dump
> ```

> [!NOTE]
> Large databases can take time to import, especially on high-load servers.

## Extra tips

### Nohup

Use `nohup` to ensure the dump or import continues if the connection is lost.

### Screen

Use `screen` to allow session sharing or recovery:

- Create a session:

  ```bash
  screen -S <session_name>
  ```

- Disconnect (keep running):

  ```
  Ctrl + A, then D
  ```

- Reattach or take over session:

  ```bash
  screen -dr <session_name>
  ```

- List sessions:

  ```bash
  screen -ls
  ```

### SSH key

Avoid password prompts by setting up SSH key authentication.

## Related

- [Configure PostgreSQL](configure.md)
- [Create and manage PostgreSQL users](manage-database-users.md)
- [Backups and restore](../../platform/hosts/backups.md)
- [SSH access](../../platform/hosts/ssh.md)
- [Database problems](../../troubleshooting/database-issues.md)
