PostgreSQL Cheat Sheet

From Gejoreuy
Jump to navigation Jump to search

List PostgreSQL Databases

postgres=# \l

List PostgreSQL Schemas

postgres=# \dn

List PostgreSQL Tables

postgres=# \dt

List PostgreSQL Users

postgres=# \du

Change or Reset PostgreSQL User Password

postgres=# ALTER USER <user-name> WITH PASSWORD '<new-password>';

Find PostgreSQL Active Connection

postgres=# SELECT * FROM pg_stat_activity WHERE datname = '<database_name>';

Terminate All Active Connections in Database

postgres=# SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '<database_name>';

Check If The Server is Postgres Master or Slave

postgres=# SELECT pg_is_in_recovery();

If it's true, we're on a slave; if false, we're in master.

Find Postgresql Configuration Location

postgres=# SELECT name, source, sourcefile, sourceline, pending_restart FROM pg_settings;

Check Replication Slots

postgres=# SELECT * from pg_replication_slots;

Create New Database

postgres=# CREATE DATABASE <database_name>;

Delete or Drop User from Database

postgres=# DROP USER IF EXISTS <user_name_1>, <user_name_2>, ..., <user_name_n>;

Delete or Drop Database

postgres=# DROP DATABASE IF EXISTS <database_name>;

Export PostgreSQL Database to Dump File

[root@gejoreuy ~]# pg_dump -U <username> -h <hostname> -p <port> <source_database_name> -f <dump_file_name>

Export PostgreSQL Database to Dump File with Password

[root@gejoreuy ~]# PGPASSWORD="password" pg_dump -U <username> -h <hostname> -p <port> <source_database_name> -f <dump_file_name>

Import PostgreSQL Database from Dump File

[root@gejoreuy ~]# psql -U <username> -h <hostname> -p <port> -d <destination_database_name> -f <dump_file_name>