Postgres

Create a database

createdb mydb -E UTF8 -O myuser
  • or
CREATE DATABASE mydb WITH OWNER mypuser;
  • By default this will copy template1 db

Create a user

createuser --password myuser
  • or
CREATE USER myuser WITH password 'secret';

Change user password

ALTER USER myuser WITH PASSWORD 'moresecret';

Change user permissions

ALTER USER myuser CREATEDB;

Delete user

dropuser myuser
  • or
DROP USER myuser

List databases

\l

Connect to a database

\c <db>

List all tables

\dt

Describe table

\d+ table

List user and permissions

\du

Show active connections

SELECT * FROM pg_stat_activity;

Export select as CSV

copy(select * from table) to '/some/file' with csv header;

Import CSV

copy table from '/some'file' with csv header;

Backup / Restore

  • Backup in binary format
pg_dump -F c -b -U user database > backup.dump
  • Restore
pg_restore --disable-triggers -U user -d database backup.dump
  • If you want to disable all constraints for data import
echo "SET CONSTRAINTS ALL DEFERRED;" | psql
  • And to enable contraints
echo "SET CONSTRAINTS ALL IMMEDIATE;" | psql

Import SQL file

  • Beside psql < sqlfile there is the possibility to use
\i sqlfile

Change output format

\x on