Postgres Commands Cheat Sheet

Tags

Quick reference Postgres commands you should know.

Configuration
sudo -u postgres psql
Switch and connect
postgres=# \l
List all databases
postgres=# \c postgres
Connect to the database named postgres
postgres=# \q
postgres=# \!
Disconnect
Service management commands

sudo service postgresql stop
sudo service postgresql start
sudo service postgresql restart
sudo systemctl restart postgresql
                    
Create command

There are many CREATE choices, like CREATE DATABASE __database_name__,
CREATE TABLE __table_name__ ...
Parameters differ but can be checked at the official documentation.

Handy queries #1
SELECT * FROM pg_proc WHERE proname='__procedurename__'
List procedure/function
SELECT * FROM pg_views WHERE viewname='__viewname__';
List view (including the definition)
SELECT pg_size_pretty(pg_total_relation_size( '__table_name__'));
Show DB table space in use
SELECT pg_size_pretty(pg_database_size( '__database_name__'));
Show DB space in use
show statement_timeout;
Show current user's statement timeout
SELECT * FROM pg_indexes WHERE tablename= '__table_name__' AND schemaname= '__schema_name__';
Show table indexes
Execution data: Queries being executed at a certain DB:

SELECT datname, application_name, pid, backend_start, query_start, state_change, state, query 
  FROM pg_stat_activity 
  WHERE datname='__database_name__';
                
Get all indexes from all tables of a schema

SELECT
   t.relname AS table_name,
   i.relname AS index_name,
   a.attname AS column_name
FROM
   pg_class t,
   pg_class i,
   pg_index ix,
   pg_attribute a,
    pg_namespace n
WHERE
   t.oid = ix.indrelid
   AND i.oid = ix.indexrelid
   AND a.attrelid = t.oid
   AND a.attnum = ANY(ix.indkey)
   AND t.relnamespace = n.oid
    AND n.nspname = 'kartones'
ORDER BY
   t.relname,
   i.relname
                
Get all queries from all dbs waiting for data (might be hung)

SELECT * FROM pg_stat_activity WHERE waiting='t'
                   
Currently running queries with process pid

SELECT 
  pg_stat_get_backend_pid(s.backendid) AS procpid, 
  pg_stat_get_backend_activity(s.backendid) AS current_query
FROM (SELECT pg_stat_get_backend_idset() AS backendid) AS s;
                   
Get Connections by Database

SELECT datname, numbackends FROM pg_stat_database;
                   
Generating random data

INSERT INTO some_table (a_float_value) SELECT random() * 100000 FROM generate_series(1, 1000000) i;        
    
Permissions
Become the postgres user, if you have permission errors

sudo su - postgres
psql
                   
Grant all permissions on database

GRANT ALL PRIVILEGES ON DATABASE  TO ;
                        
Grant permissions on schema

GRANT USAGE ON SCHEMA public TO ;
                     
Grant connection permissions on database

GRANT CONNECT ON DATABASE  TO ;
                     
Grant permissions to functions

GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO ;
                     
Grant permissions to select, update, insert, delete, on a all tables

GRANT SELECT, UPDATE, INSERT ON ALL TABLES IN SCHEMA public TO ;
                     
Grant permissions, on a table

GRANT SELECT, UPDATE, INSERT ON <table_name> TO ;
                     
Grant permissions, to select, on a table

GRANT SELECT ON ALL TABLES IN SCHEMA public TO ;
                     
Data
Select all data

SELECT * FROM <table_name>;
                   
Read one row of data

SELECT * FROM <table_name> LIMIT 1;
                    
Search for data

SELECT * FROM <table_name> WHERE <column_name> = <value>;
                     
Insert data

INSERT INTO <table_name> VALUES( <value_1>, <value_2> );
                     
Update data

UPDATE <table_name>
SET <column_1> = <value_1>, <column_2> = <value_2>
WHERE <column_1> = <value>;
                     
Delete all data

DELETE FROM <table_name>;
                     
Delete specific data

DELETE FROM <table_name>
WHERE <column_name> = <value>;
                     
Performance
Show the query plan for a query

EXPLAIN query;
                   
Show and execute the query plan for a query

EXPLAIN ANALYZE query;
                    
Collect statistics

ANALYZE table_name;
                     
Common Flags

Some interesting flags (to see all, use -h or --help depending on your psql version)

-E
will describe the underlaying queries of the \ commands
-l
psql will list all databases and then exit (useful if the user you connect with doesn't has a default database, like at AWS RDS)

Most \d commands support additional param of __schema__.name__ and accept wildcards like *.*

\?
Show help (list of available commands with an explanation)
\q
Quit/Exit
\c __database__
Connect to a database
\d __table__
Show table definition (columns, etc.) including triggers
\d+ __table__
More detailed table definition including description and physical disk size
\l
List databases
\dy
List events
\df
List functions
\di
List indexes
\dn
List schemas
\dt *.*
List tables from all schemas (if *.* is omitted will only show SEARCH_PATH ones)
\dT+
List all data types
\dv
List views
\dx
List all extensions installed
\df+ __function__
Show function SQL code.
\x
Pretty-format query results instead of the not-so-useful ASCII tables
\copy (SELECT * FROM __table_name__) TO 'file_path_and_name.csv' WITH CSV
Export a table as CSV
\des+
List all foreign servers
\dE[S+]
List all foreign tables
\! __bash_command__
execute __bash_command__ (e.g. \! ls)
User Related Flags
\du
List users
\du __username__
List a username if present.
create role __test1__
Create a role with an existing username.
create role __test2__ noinherit login password __passsword__;
Create a role with username and password.
set role __test__;
Change role for current session to __test__.
grant __test2__ to __test1__;
Allow __test1__ to set its role as __test2__.
\deu+
List all user mapping on server
Handy queries #2
Get sizes of tables, indexes and full DBs

  SELECT current_database() as database,
  pg_size_pretty(total_database_size) as total_database_size,
  schema_name,
  table_name,
  pg_size_pretty(total_table_size) as total_table_size,
  pg_size_pretty(table_size) as table_size,
  pg_size_pretty(index_size) as index_size
  FROM ( SELECT table_name,
          table_schema as schema_name,
          pg_database_size(current_database()) as total_database_size,
          pg_total_relation_size(table_name) as total_table_size,
          pg_relation_size(table_name) as table_size,
          pg_indexes_size(table_name) as index_size
          FROM information_schema.tables
          WHERE table_schema=current_schema() and table_name like 'table_%'
          ORDER BY total_table_size
      ) as sizes;        
    
COPY command: Import/export from CSV to tables

COPY table_name [ ( column_name [, ...] ) ]
FROM { 'filename' | STDIN }
[ [ WITH ] ( option [, ...] ) ]

COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
TO { 'filename' | STDOUT }
[ [ WITH ] ( option [, ...] ) ]        
    
List all grants for a specific user

SELECT table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges
WHERE  grantee = 'user_to_check' ORDER BY table_name;        
    
List all assigned user roles

SELECT
    r.rolname,
    r.rolsuper,
    r.rolinherit,
    r.rolcreaterole,
    r.rolcreatedb,
    r.rolcanlogin,
    r.rolconnlimit,
    r.rolvaliduntil,
    ARRAY(SELECT b.rolname
      FROM pg_catalog.pg_auth_members m
      JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
      WHERE m.member = r.oid) as memberof, 
    r.rolreplication
FROM pg_catalog.pg_roles r
ORDER BY 1;
    
Check permissions in a table

SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_name='name-of-the-table';
    
Kill all Connections

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database() AND pid <> pg_backend_pid();
            
Columns
Add column

ALTER TABLE <table_name> IF EXISTS
ADD <column_name> <data_type> [<constraints>];
                   
Update column

ALTER TABLE <table_name> IF EXISTS
ALTER <column_name> TYPE <data_type> [<constraints>];
                        
Delete column

ALTER TABLE <table_name> IF EXISTS
DROP <column_name>;
                     
Update column to be an auto-incrementing primary key

ALTER TABLE <table_name>
ADD COLUMN <column_name> SERIAL PRIMARY KEY;
                     
Insert into a table, with an auto-incrementing primary key

INSERT INTO <table_name>
VALUES (DEFAULT, <value1>);


INSERT INTO <table_name> (<column1_name>,<column2_name>)
VALUES ( <value1>,<value2> );
                     
Try These Related Tools



Programming can be fun, so can cryptography; however they should not be combined.

Kreitzberg and Shneiderman