Postgresql Queries Cheat Sheet



title: PostgreSQLicon: icon-postgresbackground: bg-blue-800tags:

Importing Data from CSV in PostgreSQL Insert multiple rows List the tables in SQLite opened with ATTACH Meta commands in PSQL Outputting Query Results to Files with o Random Sequences Show Tables in Postgres SQL Cheat Sheet. Queries Cheat Sheet Some of the queries in the table below can only be run by an admin. These are marked with '- priv' at the end of the query. PostgreSQL CHEAT SHEET DROP VIEW viewname; Delete a view DROP INDEX idxname; Drop an index CREATE VIEW v(c1,c2) AS SELECT c1, c2 FROM t; WITH CASCADED LOCAL CHECK OPTION; Create a new view with check option CREATE RECURSIVE VIEW v AS select-statement -anchor part UNION ALL select-statement; -recursive part.

  • nullcategories:
  • Databasedate: 2021-01-11 14:19:24intro: |The PostgreSQL cheat sheet provides you with the common PostgreSQL commands and statements.

Getting started {.cols-3}

Getting started

Switch and connect

List all databases

Connect to the database named postgres

Disconnect

psql commands {.col-span-2}

OptionExampleDescription
[-d] <database>psql -d mydbConnecting to database
-Upsql -U john mydbConnecting as a specific user
-h-ppsql -h localhost -p 5432 mydbConnecting to a host/port
-U-h-p-dpsql -U admin -h 192.168.1.5 -p 2506 -d mydbConnect remote PostgreSQL
-Wpsql -W mydbForce password
-cpsql -c 'c postgres' -c 'dt'Execute a SQL query or command
-Hpsql -c 'l+' -H postgres > database.htmlGenerate HTML report
-lpsql -lList all databases
-fpsql mydb -f file.sqlExecute commands from a file
-Vpsql -VPrint the psql version
{.show-header}

Getting help

--
hHelp on syntax of SQL commands
h DELETEDELETE SQL statement syntax
?List of PostgreSQL command

Run in PostgreSQL console

Working {.cols-3}

Recon

Show version

Show system status

Show environmental variables

List users

Postgresql Commands Cheat Sheet

Show current user

Show current user's permissions

Show current database

Show all tables in database

List functions

Databases

List databases

Connect to database

Show current database

Tables

List tables, in current db

List tables, globally

List table schema

Create table, with an auto-incrementing primary key

Permissions

Become the postgres user, if you have permission errors

Grant all permissions on database

Grant connection permissions on database

Grant permissions on schema

Grant permissions to functions

Grant permissions to select, update, insert, delete, on a all tables

Grant permissions, on a table

Grant permissions, to select, on a table

Columns

Update column

Delete column

Update column to be an auto-incrementing primary key

Insert into a table, with an auto-incrementing primary key

Data

[Select](http://www.postgresql.org/docs/current/static/sql-select.html] all data

Ulysses s grant memoir Excerpts from Ulysses S. Grant - Personal Memoirs. In the winter of 1838-9 I was attending school at Ripley, only ten miles distant from Georgetown, but spent the Christmas holidays at home. During this vacation my father received a letter from the Honorable Thomas Morris, then United States Senator from Ohio. When he read it he said to me. Writing His Mind: Passages from Ulysses S. Grant’s memoirs reveal a man of clear purpose and frank opinion The sick, aging warrior put down his pen. It was July 18, 1885, and Ulysses S. Grant had just finished his memoirs. The hero of war had no way of knowing his final determined act would also make him a literary hero. Grant 1885 Memoirs 1st Edition Originals (w/ Lincoln 4 vol. Ulysses S Grant / Personal Memoirs of U.S Grant First Edition 1886. LEATHER;ULYSSES GRANT! FIRST EDITION 1885! Memoirs Personal Complete Civil. The Personal Memoirs of Ulysses S. Grant Book Description: This is the first complete annotated edition of Grant’s memoirs, fully representing the great military leader’s thoughts on his life and times through the end of the Civil War—including the antebellum era and the Mexican War—and his invaluable perspective on battlefield decision. Grant Considered among the greatest of military memoirs, these two volumes were an immediate bestseller. With the help of his publisher, Mark Twain, Grant wrote to the last month of his life to leave a legacy for his family after being defrauded a year earlier of his estate.

Read one row of data

Search for data

Insert data

Update data

Delete all data

Delete specific data

Users

List roles

Alter user password

Schema

List schemas

Commands {.cols-3}

Tables

--
d <table>Describe table
d+ <table>Describe table with details
dtList tables from current schema
dt *.*List tables from all schemas
dt <schema>.*List tables for a schema
dpList table access privileges
det[+]List foreign tables

Query buffer

--
e [FILE]Edit the query buffer (or file)
ef [FUNC]Edit function definition
pShow the contents
rReset (clear) the query buffer
s [FILE]Display history or save it to file
w FILEWrite query buffer to file

Informational {.row-span-4}

--
l[+]List all databases
dn[S+]List schemas
di[S+]List indexes
du[+]List roles
ds[S+]List sequences
df[antw][S+]List functions
deu[+]List user mappings
dv[S+]List views
dlList large objects
dT[S+]List data types
da[S]List aggregates
db[+]List tablespaces
dc[S+]List conversions
dC[+]List casts
ddpList default privileges
dd[S]Show object descriptions
dD[S+]List domains
des[+]List foreign servers
dew[+]List foreign-data wrappers
dF[+]List text search configurations
dFd[+]List text search dictionaries
dFp[+]List text search parsers
dFt[+]List text search templates
dL[S+]List procedural languages
do[S]List operators
dO[S+]List collations
drdsList per-database role settings
dx[+]List extensions

S: show system objects, +: additional detail

Connection

--
c [DBNAME]Connect to new database
encoding [ENCODING]Show or set client encoding
password [USER]Change the password
conninfoDisplay information
Sheet

Formatting

--
aToggle between unaligned and aligned
C [STRING]Set table title, or unset if none
f [STRING]Show or set field separator for unaligned
HToggle HTML output mode
`t [onoff]`
T [STRING]Set or unset HTML <table> tag attributes
`x [onoff]`

Input/Output

--
copy ..Import/export table
See also:copy
echo [STRING]Print string
i FILEExecute file
o [FILE]Export all results to file
qecho [STRING]String to output stream

Variables

--
prompt [TEXT] NAMESet variable
set [NAME [VALUE]]Set variable (or list all if no parameters)
unset NAMEDelete variable

Misc

--
cd [DIR]Change the directory
`timing [onoff]`
! [COMMAND]Execute in shell
! ls -lList all in shell

Large Objects

  • lo_export LOBOID FILE
  • lo_import FILE [COMMENT]
  • lo_list
  • lo_unlink LOBOID

Miscellaneous {.cols-3}

Backup

Use pg_dumpall to backup all databases

Use pg_dump to backup a database

  • -a Dump only the data, not the schema
  • -s Dump only the schema, no data
  • -c Drop database before recreating
  • -C Create database before restoring
  • -t Dump the named table(s) only
  • -F Format (c: custom, d: directory, t: tar){.style-none}

Use pg_dump -? to get the full list of options

Restore

Restore a database with psql

Restore a database with pg_restore

  • -U Specify a database user
  • -c Drop database before recreating
  • -C Create database before restoring
  • -e Exit if an error has encountered
  • -F Format (c: custom, d: directory, t: tar, p: plain text sql(default)){.style-none}

Use pg_restore -? to get the full list of options

Remote access

Get location of postgresql.conf Office 365 mac latest version.

Append to postgresql.conf

Append to pg_hba.conf (Same location as postgresql.conf)

Restart PostgreSQL server

Import/Export CSV

Export table into CSV file

Import CSV file into table

See also: Copy

See Also

Postgresql Cheat Sheet Pdf

  • Posgres-cheatsheet(gist.github.com)