############################# ### PostgreSQL CheatSheet ### ############################# ### Connect to database psql -h host -d database -U user -W ### Connect to database via SSL psql -U user -h host "_dbname_=db sslmode=require" ### CREATE DATABASE CREATE DATABASE _dbname_; ### CREATE TABLE (with auto numbering integer id) CREATE TABLE tableName ( id serial PRIMARY KEY, name varchar(50) UNIQUE NOT NULL, dateCreated timestamp DEFAULT current_timestamp ); ### Add a primary key ALTER TABLE tableName ADD PRIMARY KEY (id); ### Create an INDEX CREATE UNIQUE INDEX indexName ON tableName (columnNames); ### Backup a database (command line) pg_dump -U _dbuser_ _dbname_ > _dbname_.sql pg_dump -U _dbuser_ -F c -b _dbname_ > /path/to/your/file/dump_name.sql pg_dump -U _dbuser_ -F t -b _dbname_ > /path/to/your/file/dump_name.tar -b include large objects in dump -c clean (drop) database objects before recreating -C include commands to create database in dump -U to specify which user will connect to the PostgreSQL database server. -W or --password will force pg_dump to prompt for a password before connecting to the server. -F is used to specify the format of the output file, which can be one of the following: p – plain-text SQL script c – custom-format archive d – directory-format archive t – tar-format archive pg_dump -? - help ### Backup all databases (command line) pg_dumpall > pgbackup.sql ### Restore a database psql -U db_user _dbname_ < _dumpname_.sql ### Restore a database using pg_restore pg_restore -d _dbname_ /path/to/your/file/_dumpname_.tar -c -U db_user -1 -c to drop database objects before recreating them -C to create a database before restoring into it -e exit if an error has encountered -F format to specify the format of the archive pg_restore -? - help ### Run a SQL script (command line) psql -f script.sql _dbname_ ### Search using a regular expression SELECT column FROM table WHERE column ~ 'foo.*'; ### The first N records SELECT columns FROM table LIMIT 10; ### Pagination SELECT cols FROM table LIMIT 10 OFFSET 30; ### Prepared Statements PREPARE preparedInsert (int, varchar) AS INSERT INTO tableName (intColumn, charColumn) VALUES ($1, $2); EXECUTE preparedInsert (1,'a'); EXECUTE preparedInsert (2,'b'); DEALLOCATE preparedInsert; ### Create a Function CREATE OR REPLACE FUNCTION month (timestamp) RETURNS integer AS 'SELECT date_part(''month'', $1)::integer;' LANGUAGE 'sql'; ### Table Maintenance VACUUM ANALYZE table; ### Reindex a database, table or index REINDEX DATABASE _dbname_; ### Show query plan EXPLAIN SELECT * FROM table; ### Import from a file COPY destTable FROM '/tmp/somefile'; ### Show all runtime parameters SHOW ALL; ### Grant all permissions to a user GRANT ALL PRIVILEGES ON table TO username; ### Perform a transaction BEGIN TRANSACTION UPDATE accounts SET balance += 50 WHERE id = 1; COMMIT; #################################################################################################### ### Basic SQL ###################################################################################### #################################################################################################### ### Get all columns and rows from a table SELECT * FROM table; ### Add a new row INSERT INTO table (column1,column2) VALUES (1, 'one'); ### Update a row UPDATE table SET foo = 'bar' WHERE id = 1; ### Delete a row DELETE FROM table WHERE id = 1; #################################################################################################### ### Useful Commands ################################################################################ #################################################################################################### Usage: psql [OPTION]... [DBNAME [USERNAME]] General \copyright show PostgreSQL usage and distribution terms \errverbose show most recent error message at maximum verbosity \g [FILE] or ; execute query (and send results to file or |pipe) \gexec execute query, then execute each value in its result \gset [PREFIX] execute query and store results in psql variables \q quit psql \crosstabview [COLUMNS] execute query and display results in crosstab \watch [SEC] execute query every SEC seconds Help \? [commands] show help on backslash commands \? options show help on psql command-line options \? variables show help on special variables \h [NAME] help on syntax of SQL commands, * for all commands Query Buffer \e [FILE] [LINE] edit the query buffer (or file) with external editor \ef [FUNCNAME [LINE]] edit function definition with external editor \ev [VIEWNAME [LINE]] edit view definition with external editor \p show the contents of the query buffer \r reset (clear) the query buffer \s [FILE] display history or save it to file \w FILE write query buffer to file Input/Output \copy ... perform SQL COPY with data stream to the client host \echo [STRING] write string to standard output \i FILE execute commands from file \ir FILE as \i, but relative to location of current script \o [FILE] send all query results to file or |pipe \qecho [STRING] write string to query output stream (see \o) Informational (options: S = show system objects, + = additional detail) \d[S+] list tables, views, and sequences \d[S+] NAME describe table, view, sequence, or index \da[S] [PATTERN] list aggregates \dA[+] [PATTERN] list access methods \db[+] [PATTERN] list tablespaces \dc[S+] [PATTERN] list conversions \dC[+] [PATTERN] list casts \dd[S] [PATTERN] show object descriptions not displayed elsewhere \ddp [PATTERN] list default privileges \dD[S+] [PATTERN] list domains \det[+] [PATTERN] list foreign tables \des[+] [PATTERN] list foreign servers \deu[+] [PATTERN] list user mappings \dew[+] [PATTERN] list foreign-data wrappers \df[antw][S+] [PATRN] list [only agg/normal/trigger/window] functions \dF[+] [PATTERN] list text search configurations \dFd[+] [PATTERN] list text search dictionaries \dFp[+] [PATTERN] list text search parsers \dFt[+] [PATTERN] list text search templates \dg[S+] [PATTERN] list roles \di[S+] [PATTERN] list indexes \dl list large objects, same as \lo_list \dL[S+] [PATTERN] list procedural languages \dm[S+] [PATTERN] list materialized views \dn[S+] [PATTERN] list schemas \do[S] [PATTERN] list operators \dO[S+] [PATTERN] list collations \dp [PATTERN] list table, view, and sequence access privileges \drds [PATRN1 [PATRN2]] list per-database role settings \ds[S+] [PATTERN] list sequences \dt[S+] [PATTERN] list tables \dT[S+] [PATTERN] list data types \du[S+] [PATTERN] list roles \dv[S+] [PATTERN] list views \dE[S+] [PATTERN] list foreign tables \dx[+] [PATTERN] list extensions \dy [PATTERN] list event triggers \l[+] [PATTERN] list databases \sf[+] FUNCNAME show a function's definition \sv[+] VIEWNAME show a view's definition \z [PATTERN] same as \dp Formatting \a toggle between unaligned and aligned output mode \C [STRING] set table title, or unset if none \f [STRING] show or set field separator for unaligned query output \H toggle HTML output mode (currently off) \pset [NAME [VALUE]] set table output option (NAME := {border|columns|expanded|fieldsep|fieldsep_zero| footer|format|linestyle|null|numericlocale|pager| pager_min_lines|recordsep|recordsep_zero|tableattr|title| tuples_only|unicode_border_linestyle| unicode_column_linestyle|unicode_header_linestyle}) \t [on|off] show only rows (currently off) \T [STRING] set HTML