postgresql Cheat Sheet

A Programming › PostgreSQL cheat sheet in English by cgp

This is a postgresql cheat sheet.

7,321 views 1,468 downloads 13 Jul 2023 History

Database

\l
list databases
\l+
list databases with more details
\c <db­_na­me>
Connects to a given database
\h CREATE DATABASE
gives help on creating a database
CREATE DATABASE mytest;
Creates a database called mytest

Table

\d <TA­BLE­_NA­ME>
Shows inform­ation on the given table_name
\d+ <TA­BLE­_NA­ME>
Gives more detailed info on a given table
\dt
List tables from a given schema
\dt .
List tables from all schemas
\dt <na­me-­of-­sch­ema­>.*
List tables for a given schema
\copy (SELECT * FROM <my­_ta­ble­>) TO '­fil­e_p­ath­_an­d_n­ame.cs­v' WITH CSV
Copies data from a table to a CSV file
ANALYZE [__tab­le__]
Shows statistics about a table
SELECT * FROM pg_indexes WHERE tablen­ame­='__­tab­le_­nam­e__­' AND schema­nam­e='_­_sc­hem­a_n­ame­__';
Show indexes on a table
Comment on table employee is '­Stores employee record­s';
Add a comment about a table
Comment on column employ­ee.ssn is '­Emp­loyee Social Security Number­';
Add a comment about a column in a table

Command line

psql [OPTIO­N]... [DBNAME [USERN­AME]]
-d, --dbna­me=­DBNAME
database name to connect to (default: "­fam­ily­")
-f, --file­=FI­LENAME
execute commands from file, then exit
-c, --comm­and­=CO­MMAND
run only single command (SQL or internal) and exit
-h, --host­=HO­STNAME
database server host
-p, --port­=PORT
database server port (default: "­543­2")
-U, --user­nam­e=U­SERNAME
database user name (default: "­fam­ily­")
-H, --html
HTML table output mode

Config­uration

show all
Display config­uration parameters
select * from pg_set­tings;
Display config­uration parameters using sql
show config­_file;
Show location of config file

User Commands

\password <us­ern­ame>
Change the password for given username
select * from pg_user;
Show all users
DROP USER <us­ern­ame>
Removes a given user
CREATE USER name [ [ WITH ] option [ ... ] ]
Cre

Backup and Restore

$ pg_dump mydb > mydb.b­ak.sql

// Create a backup for a database “mydb” in plain-text SQL Script file (mydb.b­ak.sql) (pg_dump)

$ pg_dump -c -C -F p -f mydb.b­ak.sql mydb

// Creates a backup for a database “mydb” in plain text format with drop & create database commands included in output file mydb.b­ak.sql (pg_dump)

psql -U username -f filena­me.sql

// restores from a set of SQL commands as given above

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.