PostgreSQL database access with psql

Connecting to a Postgres database

Assuming your user has postgres privileges, access database <db_name> with:

psql -d <db_name>

For instance, to access a NELA database:

psql -d nela-eng

To list the existing databases in a Postgres server use:

\l

Saving queries to a CSV file

Once connected to a database in psql, you can use \copy to save query results to a file:

\copy (SELECT title, content FROM articles WHERE date_published >= '2025-01-01') to '/path/to/file.csv' with csv header;

INNER JOIN example creating a random sample of a NELA database

This example will save 1000 random entries from a NELA database and save it to a CSV file.

\copy (SELECT * FROM (articles INNER JOIN sources on articles.source_id=sources.id) WHERE date_published >= '2024-01-01' ORDER BY RANDOM() LIMIT 1000) to '/path/to/file.csv' with csv header;