Installation on MacOS using Homebrew services
- Install PostgreSQL, preferably a pinned version
brew install postgresql@10
- If you don't have one, get the
psql
client.
brew install libpq
libpq
won't install itself in the/usr/local/bin
directory like other Homebrew applications. To make that happen, you need to run:
brew link --force libpq
- Start Postgres services
brew services start postgresql
Check
brew info postgresql
- Create a database, and...
createdb `first`
Fix role "postgres" does not exist error
createuser -s postgres
- Run psql client as user postgres -
psql -U postgres
- Connect to local postgres database as a specific user - `psql -h localhost -U <postgres_user> ``
\?
- List all available commands\q
- Quit/Exit\l
- List databases\c <database>
- Connect to a database
-
\d
- List tables -
\d <table>
- Show table definition, including triggers -
\d+ <table>
- Show additional info about a table -
\dy
- List events -
\df
- List functions -
\di
- List indexes -
\dn
- List schemas -
\dv
- List views -
\e
- Open default text editor in psql shell -
\copy (SELECT * FROM __table_name__) TO 'file_path_and_name.csv' WITH CSV
- Export a table as CSV
\timing
- Turn on query timing\x
- Pretty-format query results
pg_dump <dbname> > db.sql
- plain text
pg_dump -Fc <dbname> > db.bak
- compressed binary formatpg_dump -Ft <dbname> > db.tar
- tarball format
If the database already exists,
pg_restore -Fc db.bak
- restore compressed binary formatpg_restore -Ft db.tar
- restore tarball format
If creating the database new from a dump, you'll need to add the -C
flag.
Create the database
createdb -T template0 <dbname>
Import database from dump
pg_restore --clean --no-owner --verbose -d <dbname> db.bak
-
- Create database
createdb <database_name>
- Drop database
dropdb <database_name>
- Restore database
pg_restore --no-owner --dbname <database> <database.dump>
- Create database
CREATE DATABASE <database>
- Remove database
DROP DATABASE <database>