0% found this document useful (0 votes)
103 views

PostgreSQL Cheat Sheet & Quick Reference

Uploaded by

ducho.korea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

PostgreSQL Cheat Sheet & Quick Reference

Uploaded by

ducho.korea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

QuickRef.ME Search for cheatsheet ⌘ K Stars 6.

3k Follow Me

PostgreSQL cheatsheet
The PostgreSQL cheat sheet provides you with the common PostgreSQL commands
and statements.

# Getting Started
Getting started psql commands

Switch and connect Option Example Description

[-d] <database> psql -d mydb Connecting to database


$ sudo -u postgres psql
-U psql -U john mydb Connecting as a specific user
List all databases
-h -p psql -h localhost -p 5432 mydb Connecting to a host/port

postgres=# \l
psql -U admin -h 192.168.1.5 -p 2506 -d
-U -h -p -d Connect remote PostgreSQL
mydb
Connect to the database named postgres
-W psql -W mydb Force password
postgres=# \c postgres
Execute a SQL query or
-c psql -c '\c postgres' -c '\dt'
command
Disconnect
-H psql -c "\l+" -H postgres > database.html Generate HTML report
postgres=# \q
postgres=# \! -l psql -l List all databases

-f psql mydb -f file.sql Execute commands from a file

-V psql -V Print the psql version

Getting help

Help on syntax of SQL


\h
commands

\h DELETE DELETE SQL statement syntax

\? List of PostgreSQL command

Run in PostgreSQL console

# PostgreSQL Working
Recon Databases Tables

Show version List databases List tables, in current db

SHOW SERVER_VERSION; \l \dt

Show system status Connect to database SELECT table_schema,table_name FROM


information_schema.tables ORDER BY
table_schema,table_name;
\conninfo \c <database_name>

List tables, globally


Show environmental variables Show current database
SHOW ALL; SELECT current_database(); \dt *.*.

List users Create database SELECT * FROM pg_catalog.pg_tables

SELECT rolname FROM pg_roles; CREATE DATABASE <database_name> WITH List table schema
OWNER <username>;
Show current user \d <table_name>
Drop database \d+ <table_name>

SELECT current_user;
SELECT column_name, data_type,
DROP DATABASE IF EXISTS
character_maximum_length
Show current user's permissions <database_name>;
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '<table_name>';
\du Rename database

Create table
Show current database ALTER DATABASE <old_name> RENAME TO
<new_name>;
CREATE TABLE <table_name>(
SELECT current_database(); <column_name> <column_type>,
<column_name> <column_type>
);
Show all tables in database

\dt Create table, with an auto-incrementing


primary key

List functions
CREATE TABLE <table_name> (
<column_name> SERIAL PRIMARY KEY
\df <schema>
);

Delete table

DROP TABLE IF EXISTS <table name>

Permissions Columns Data

Become the postgres user, if you have Add column Select all data
permission errors
ALTER TABLE <table_name> IF EXISTS SELECT * FROM <table_name>;
sudo su - postgres ADD <column_name> <data_type>
psql [<constraints>]; Read one row of data

Grant all permissions on database Update column SELECT * FROM <table_name> LIMIT 1;

GRANT ALL PRIVILEGES ON DATABASE ALTER TABLE <table_name> IF EXISTS Search for data
<db_name> TO <user_name>; ALTER <column_name> TYPE <data_type>
[<constraints>];
SELECT * FROM <table_name> WHERE
Grant connection permissions on database <column_name> = <value>;
Delete column
GRANT CONNECT ON DATABASE <db_name>
Insert data
TO <user_name>; ALTER TABLE <table_name> IF EXISTS
DROP <column_name>;
INSERT INTO <table_name> VALUES(
Grant permissions on schema <value_1>, <value_2> );
Update column to be an auto-incrementing
GRANT USAGE ON SCHEMA public TO primary key
Update data
<user_name>;
ALTER TABLE <table_name>
UPDATE <table_name>
Grant permissions to functions ADD COLUMN <column_name> SERIAL
SET <column_1> = <value_1>,
PRIMARY KEY;
<column_2> = <value_2>
GRANT EXECUTE ON ALL FUNCTIONS IN WHERE <column_1> = <value>;
SCHEMA public TO <user_name>; Insert into a table, with an auto-
incrementing primary key
Delete all data
Grant permissions to select, update, insert,
delete, on a all tables INSERT INTO <table_name>
DELETE FROM <table_name>;
VALUES (DEFAULT, <value1>);

GRANT SELECT, UPDATE, INSERT ON ALL


Delete specific data
TABLES IN SCHEMA public TO
INSERT INTO <table_name>
<user_name>;
(<column1_name>,<column2_name>) DELETE FROM <table_name>
VALUES ( <value1>,<value2> ); WHERE <column_name> = <value>;
Grant permissions, on a table

GRANT SELECT, UPDATE, INSERT ON


<table_name> TO <user_name>;

Grant permissions, to select, on a table

GRANT SELECT ON ALL TABLES IN SCHEMA

Users Schema Dates

List roles List schemas Show current date YYYY-MM-DD

SELECT rolname FROM pg_roles; \dn SELECT current_date;

Create user SELECT schema_name FROM Calculate age between two dates
information_schema.schemata;

CREATE USER <user_name> WITH SELECT age(timestamp, timestamp);


SELECT nspname FROM
PASSWORD '<password>';
pg_catalog.pg_namespace;
Show current time with time zone
Drop user
Create schema
SELECT current_time;
DROP USER IF EXISTS <user_name>;
CREATE SCHEMA IF NOT EXISTS
<schema_name>; Make dates using integers
Alter user password

Drop schema SELECT make_date(2021,03,25);


ALTER ROLE <user_name> WITH PASSWORD
'<password>';
DROP SCHEMA IF EXISTS <schema_name>
CASCADE;

# PostgreSQL Commands
Tables Query buffer Informational

\d <table> Describe table \e [FILE] Edit the query buffer (or file) \l[+] List all databases

Describe table with \ef [FUNC] Edit function definition \dn[S+] List schemas
\d+ <table>
details
\p Show the contents \di[S+] List indexes
List tables from current
\dt
schema Reset (clear) the query \du[+] List roles
\r
buffer
List tables from all \ds[S+] List sequences
\dt *.*
schemas Display history or save it to
\s [FILE]
file \df[antw][S+] List functions
\dt <schema>.* List tables for a schema
\w FILE Write query buffer to file \deu[+] List user mappings
List table access
\dp
privileges \dv[S+] List views

\det[+] List foreign tables \dl List large objects

\dT[S+] List data types


Connection Formatting
\da[S] List aggregates
Connect to new Toggle between unaligned
\c [DBNAME] \a
database and aligned \db[+] List tablespaces

Show or set Set table title, or unset if \dc[S+] List conversions


\encoding [ENCODING] \C [STRING]
client encoding none
\dC[+] List casts
Change the Show or set field separator
\password [USER] \f [STRING]
password for unaligned \ddp List default privileges

Display \H Toggle HTML output mode \dd[S] Show object descriptions


\conninfo
information
\t [on|off] Show only rows \dD[S+] List domains

Set or unset HTML <table> \des[+] List foreign servers


\T [STRING]
tag attributes
\x [on|off] Toggle expanded output List foreign-data
\dew[+]
wrappers

Input/Output Variables List text search


\dF[+]
configurations
Import/export table \prompt [TEXT] NAME Set variable
\copy ...
See also: copy List text search
Set variable (or \dFd[+]
dictionaries
\echo [STRING] Print string \set [NAME [VALUE]] list all if no
parameters) \dFp[+] List text search parsers
\i FILE Execute file
\unset NAME Delete variable List text search
Export all results to \dFt[+]
\o [FILE] templates
file
List procedural
String to output \dL[S+]
\qecho [STRING] languages
stream
\do[S] List operators

Misc Large Objects \dO[S+] List collations

\cd [DIR] Change the directory List per-database role


\lo_export LOBOID FILE
\drds
settings
\timing [on|off] Toggle timing
\lo_import FILE [COMMENT]
\dx[+] List extensions
\! [COMMAND] Execute in shell
\lo_list

\! ls -l List all in shell \lo_unlink LOBOID


S: show system objects, +: additional detail

# Miscellaneous
Backup Restore Remote access

Use pg_dumpall to backup all databases Restore a database with psql Get location of postgresql.conf

$ pg_dumpall -U postgres > all.sql $ psql -U user mydb < mydb_backup.sq $ psql -U postgres -c 'SHOW config_f

Use pg_dump to backup a database


Restore a database with pg_restore Append to postgresql.conf

$ pg_dump -d mydb -f mydb_backup.sql


$ pg_restore -d mydb mydb_backup.sql listen_addresses = '*'

-a Dump only the data, not the schema


Append to pg_hba.conf (Same location as
-s Dump only the schema, no data -U Specify a database user postgresql.conf)

-c Drop database before recreating -c Drop database before recreating


host all all 0.0.0.0/0 md5
host all all ::/0 md5
-C Create database before restoring
-C Create database before restoring

-e Exit if an error has encountered Restart PostgreSQL server


-t Dump the named table(s) only

-F Format (c: custom, d: directory, t: tar) -F Format (c: custom, d: directory, t: tar, $ sudo systemctl restart postgresql
p: plain text sql(default))

Use pg_dump -? to get the full list of Use pg_restore -? to get the full list of
options options

Import/Export CSV

Export table into CSV file

\copy table TO '<path>' CSV


\copy table(col1,col1) TO '<path>' C
\copy (SELECT...) TO '<path>' CSV

Import CSV file into table

\copy table FROM '<path>' CSV


\copy table(col1 col1) FROM '<path>'
See also: Copy

# Also see
Posgres-cheatsheet (gist.github.com)

Related Cheatsheet Recent Cheatsheet


QuickRef.ME
MySQL Cheatshe MongoDB Cheats Remote Work Re Homebrew Cheat
Share quick reference and cheat sheet for
Quick Reference Quick Reference Quick Reference Quick Reference
developers.

中文版 #Notes
Neo4j Cheatshee PyTorch Cheatshe Taskset Cheatshe
Quick Reference Quick Reference Quick Reference

© 2023 QuickRef.ME, All rights reserved.

You might also like