Skip to content

Instantly share code, notes, and snippets.

@tuannvm
Last active January 13, 2025 11:38
Show Gist options
  • Save tuannvm/25a333011bfb9080293499df627ce3da to your computer and use it in GitHub Desktop.
Save tuannvm/25a333011bfb9080293499df627ce3da to your computer and use it in GitHub Desktop.
#postgres #cheatsheet
@tuannvm
Copy link
Author

tuannvm commented Jul 20, 2017

  • +2 minutes queries:
SELECT now() - query_start as "runtime", usename, datname, waiting, state, query
  FROM  pg_stat_activity
  WHERE now() - query_start > '2 minutes'::interval
 ORDER BY runtime DESC;
  • Check table sizes:
select table_schema, table_name, pg_relation_size('"'||table_schema||'"."'||table_name||'"')
from information_schema.tables
order by 3;

@tuannvm
Copy link
Author

tuannvm commented Aug 4, 2017

  • Create db and grant privilege to user:
CREATE DATABASE <db-name>;
CREATE USER <user-name> WITH PASSWORD <password>;
GRANT ALL PRIVILEGES ON DATABASE <db-name> to <user-name>;

@tuannvm
Copy link
Author

tuannvm commented Aug 10, 2017

Access psql:

psql -U <username> -d <dbname> -h <host>

@tuannvm
Copy link
Author

tuannvm commented Aug 24, 2017

you must use the same password for postgres master/slave DBs

@tuannvm
Copy link
Author

tuannvm commented Oct 16, 2017

# backup
pg_dump -U $username --format=c --file=$mydatabase.sqlc $dbname

# dump without owner & privileges
pg_dump -U $username --format=c --file=$mydatabase.sqlc -O -x $dbname

# -O, --no-owner               skip restoration of object ownership in plain-text format
# -x, --no-privileges          do not dump privileges (grant/revoke)
---

# restore only a specified index from a backup file:
pg_restore -U $username --dbname=$dbname --index=$indexname

# restore only a single function:
pg_restore -U $username --dbname=$dbname --function=$functionname(args)

# restore only a single table:
pg_restore -U $username --dbname=$dbname --table=$tablename

# simple restore:
pg_restore -U$username --dbname=$databasename $filename

@tuannvm
Copy link
Author

tuannvm commented Feb 8, 2018

  • Query all postgres settings:
SELECT name,setting,unit FROM pg_settings;
  • Create new schema and grant privileges:
CREATE USER abc WITH PASSWORD 'ks839#@S';
CREATE SCHEMA abc;
GRANT ALL ON ALL TABLES IN SCHEMA abc TO abc;
ALTER DEFAULT PRIVILEGES IN SCHEMA abc GRANT ALL ON TABLES TO abc;
GRANT ALL PRIVILEGES ON SCHEMA abc TO abc;
  • Read-only user:
GRANT SELECT ON ALL TABLES IN SCHEMA public TO abc;
GRANT USAGE ON SCHEMA public TO abc;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO abc;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment