Skip to content

Instantly share code, notes, and snippets.

@sblack4
Forked from DominikSerafin/01PostgreSQLSnippets.md
Last active August 13, 2020 17:15
Show Gist options
  • Save sblack4/b950a7d6f71bc423bbb5f3961b4e6db3 to your computer and use it in GitHub Desktop.
Save sblack4/b950a7d6f71bc423bbb5f3961b4e6db3 to your computer and use it in GitHub Desktop.
PostgreSQL Snippets

Database Export and Import

  1. pg_dump -h localhost -U username dbname -w > "/backups/dbname-$(date +'%y-%m-%d-%H%M').backup"
  2. su - postgres
  3. psql --set ON_ERROR_STOP=on --single-transaction db_name < backup-file
  4. grant all permissions to the db for the db user
    • GRANT ALL ON ALL TABLES IN SCHEMA public to username;
    • GRANT ALL ON ALL SEQUENCES IN SCHEMA public to username;
    • GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to username;

Bash Commands

Login into psql sudo -u postgres psql

Login into postgres user su - postgres

Create database user createuser -P username

Delete database user dropuser username

Create database createdb dbname

Drop database dropdb dbname

Execute PSQL Command psql -c <somecommand>

Import Database psql -h localhost -U username db_name < /srv/db_name.backup

Import Database #2 psql -h localhost -U username -d dbname -f file.sql

Import Database (from custom format, atomic) pg_restore -U username -d dbname -1 filename

Dump Database (export) pg_dump -h localhost -U username dbname > /srv/db_name.backup

Dump Database (custom compressed format) pg_dump -Fc -h localhost -U username dbname > /srv/db_name.backup

Dump Database (one line with password) PGPASSWORD=abc123 pg_dump -h localhost -U username dbname > /srv/db_name.backup

Queries and commands inside PSQL

General Help \?

Syntax Help on SQL Commands \help <somequery>

List Databases \l or \list

List users \du or \dg

Select database \c db or \connect dbname

See currently selected database \c or \connect

Import database \i <file>

Quit PSQL \q or CTRL+D

Create user CREATE USER username WITH PASSWORD 'password';

Drop User DROP USER username;

Create Database with owner CREATE DATABASE dbname WITH OWNER username;

Change user password ALTER USER postgres PASSWORD 'new_password';

Give privileges to database to user GRANT ALL PRIVILEGES ON DATABASE dbname TO username;

Drop Database DROP DATABASE dbname;

Describe current schema

db info schema

SET search_path TO 'information_schema';

list tables

-- list the tables in the schema
SELECT table_name from information_schema.tables
WHERE table_schema = 'myschema';

describe table

SELECT column_name, is_nullable, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'mytable'
ORDER BY ordinal_position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment