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

PostgreSQL_cheatsheet

Uploaded by

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

PostgreSQL_cheatsheet

Uploaded by

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

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
-U -h -p -d psql -U admin -h 192.168.1.5 -p 2506 -d mydb Connect remote PostgreSQL

Connect to the database named postgres -W psql -W mydb Force password

postgres=# \c postgres -c psql -c '\c postgres' -c '\dt' Execute a SQL query or command

-H psql -c "\l+" -H postgres > database.html Generate HTML report


Disconnect
-l psql -l List all databases
postgres=# \q
postgres=# \! -f psql mydb -f file.sql Execute commands from a file

-V psql -V Print the psql version

Getting help

\h Help on syntax of SQL 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

\dt *.*.
SHOW ALL; SELECT current_database();

SELECT * FROM pg_catalog.pg_tables


List users Create database

List table schema


SELECT rolname FROM pg_roles; CREATE DATABASE <database_name> WITH OWNER
<username>;
\d <table_name>
Show current user \d+ <table_name>
Drop database
SELECT current_user; SELECT column_name, data_type,
DROP DATABASE IF EXISTS <database_name>; character_maximum_length
FROM INFORMATION_SCHEMA.COLUMNS
Show current user's permissions
WHERE table_name = '<table_name>';
Rename database
\du
ALTER DATABASE <old_name> RENAME TO Create table

Show current database <new_name>;


CREATE TABLE <table_name>(
<column_name> <column_type>,
SELECT current_database();
<column_name> <column_type>
);
Show all tables in database

Create table, with an auto-incrementing primary key


\dt

CREATE TABLE <table_name> (


List functions <column_name> SERIAL PRIMARY KEY
);
\df <schema>
Delete table

DROP TABLE IF EXISTS <table_name> CASCADE;

- Permissions - Columns - Data

Become the postgres user, if you have permission errors Add column Select all data

sudo su - postgres ALTER TABLE <table_name> IF EXISTS SELECT * FROM <table_name>;


psql ADD <column_name> <data_type> [<constraints>];
Read one row of data
Grant all permissions on database Update column
SELECT * FROM <table_name> LIMIT 1;
GRANT ALL PRIVILEGES ON DATABASE <db_name> TO ALTER TABLE <table_name> IF EXISTS
<user_name>; ALTER <column_name> TYPE <data_type> Search for data
[<constraints>];
Grant connection permissions on database SELECT * FROM <table_name> WHERE <column_name>
Delete column = <value>;
GRANT CONNECT ON DATABASE <db_name> TO
<user_name>; ALTER TABLE <table_name> IF EXISTS Insert data
DROP <column_name>;
Grant permissions on schema INSERT INTO <table_name> VALUES( <value_1>,
Update column to be an auto-incrementing primary key <value_2> );
GRANT USAGE ON SCHEMA public TO <user_name>;
ALTER TABLE <table_name> Update data
Grant permissions to functions ADD COLUMN <column_name> SERIAL PRIMARY KEY;

UPDATE <table_name>
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA Insert into a table, with an auto-incrementing primary key SET <column_1> = <value_1>, <column_2> =
public TO <user_name>; <value_2>
INSERT INTO <table_name> WHERE <column_1> = <value>;
Grant permissions to select, update, insert, delete, on a all VALUES (DEFAULT, <value1>);
tables Delete all data

INSERT INTO <table_name> (<column1_name>,


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

Grant permissions, to select, on a table

GRANT SELECT ON ALL TABLES IN SCHEMA public TO


<user_name>;

- 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 PASSWORD SELECT age(timestamp, timestamp);


SELECT nspname FROM pg_catalog.pg_namespace;
'<password>';
Show current time with time zone
Create schema
Drop user
SELECT current_time;
CREATE SCHEMA IF NOT EXISTS <schema_name>;
DROP USER IF EXISTS <user_name>;
Make dates using integers
Drop schema
Alter user password
SELECT make_date(2021,03,25);
DROP SCHEMA IF EXISTS <schema_name> CASCADE;
ALTER ROLE <user_name> WITH PASSWORD
'<password>';

# PostgreSQL Commands
Tables Query buffer Informational

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

\d+ <table> Describe table with details \ef [FUNC] Edit function definition \dn[S+] List schemas

\dt List tables from current schema \p Show the contents \di[S+] List indexes

\dt *.* List tables from all schemas \r Reset (clear) the query buffer \du[+] List roles

\dt <schema>.* List tables for a schema \s [FILE] Display history or save it to file \ds[S+] List sequences

\dp List table access privileges \w FILE Write query buffer to file \df[antw][S+] List functions

\det[+] List foreign tables \deu[+] List user mappings

\dv[S+] List views

Connection Formatting
\dl List large objects
\c [DBNAME] Connect to new database \a Toggle between unaligned and aligned
\dT[S+] List data types
\encoding [ENCODING] Show or set client encoding \C [STRING] Set table title, or unset if none
\da[S] List aggregates
\password [USER] Change the password \f [STRING] Show or set field separator for unaligned
\db[+] List tablespaces
\conninfo Display information \H Toggle HTML output mode
\dc[S+] List conversions
\t [on|off] Show only rows
\dC[+] List casts
Set or unset HTML <table> tag
\T [STRING]
attributes \ddp List default privileges

\x [on|off] Toggle expanded output \dd[S] Show object descriptions

\dD[S+] List domains

Input/Output Variables
\des[+] List foreign servers
Import/export table \prompt [TEXT] NAME Set variable
\copy ... \dew[+] List foreign-data wrappers
See also: copy
Set variable (or list all if no
\set [NAME [VALUE]]
\echo [STRING] Print string parameters) \dF[+] List text search configurations

\i FILE Execute file \unset NAME Delete variable \dFd[+] List text search dictionaries

\o [FILE] Export all results to file \dFp[+] List text search parsers

\qecho [STRING] String to output stream \dFt[+] List text search templates

\dL[S+] List procedural languages

Misc Large Objects \do[S] List operators


\cd [DIR] Change the directory
\lo_export LOBOID FILE \dO[S+] List collations
\timing [on|off] Toggle timing
\lo_import FILE [COMMENT] \drds List per-database role settings
\! [COMMAND] Execute in shell
\lo_list
\dx[+] List extensions
\! 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.sql $ psql -U postgres -c 'SHOW config_file'

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 -c listen_addresses = '*'

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

-s Dump only the schema, no data -c Drop database before recreating


host all all 0.0.0.0/0 md5
host all all ::/0 md5
-c Drop database before recreating -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 Format (c: custom, d: directory, t: tar, p: plain text
-F $ sudo systemctl restart postgresql
sql(default))
-F Format (c: custom, d: directory, t: tar)

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

- Import/Export CSV

Export table into CSV file

\copy table TO '<path>' CSV


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

Import CSV file into table

\copy table FROM '<path>' CSV


\copy table(col1,col1) FROM '<path>' CSV

See also: Copy

# Also see

You might also like