PostgreSQL Reference

Kip Landergren

(Updated: )

Contents#

Install Location / Data Directory / Data Area#

macOs /Library/PostgreSQL/16/
Debian /var/lib/postgresql/

Postgres Utilities#

createdb#

Creates a new PostgreSQL database. The database user who executes this command becomes the owner of the new database, unless -O/--owner is specified.

createdb [connection-option...] [option...] [dbname [description]]
-U --username connect as the postgres user username
-O --owner specifies the database user who will own the new database
-e --echo echo the commands that createdb generates and sends to the server
createdb --username postgres --echo mydb
Password:
SELECT pg_catalog.set_config('search_path', '', false);
CREATE DATABASE mydb;

dropdb#

Destroys an existing PostgreSQL database. Wrapper around DROP DATABASE.

dropdb [connection-option...] [option...] dbname

initdb#

Creates a new PostgreSQL database cluster. Use this to create the directories where cluster data will live, etc.

From the initdb(1) man page:

initdb must be run as the user that will own the server process, because the server needs to have access to the files and directories that initdb creates. Since the server cannot be run as root, you must not run initdb as root either. (It will in fact refuse to do so.)

--pwprompt prompts for a password to give the bootstrap superuser
-A --auth the default authentication method for local users used in pg_hba.conf
-D --pgdata the directory where the database cluster should be stored
-k --data-checksums use checksums on data pages to help detect corruption by the I/O system (may incur noticeable performance penalty)

For macOS:

mkdir path/to/data
chown -R postgres:daemon path/to/data
sudo -u postgres initdb --data-checksums --auth scram-sha-256 --pwprompt --pgdata path/to/data

Notes:

pg_config#

pg_config provides information about the installed version of PostgreSQL.

pg_config [OPTION]...

With no arguments, all known items are shown.

--sysconfdir show location of system-wide configuration files

pg_ctl#

Initialize, start, stop, or control a PostgreSQL server.

-D --pgdata the directory where the database cluster should be stored
-l --log (strongly recommended) append the server log output to filename
-s --silent print only errors
sudo -u postgres pg_ctl init --pgdata path/to/data
sudo -u postgres pg_ctl start --pgdata path/to/data --log path/to/postgres.log
sudo -u postgres pg_ctl stop --pgdata path/to/data

pg_dump#

Therefore, it is wise to run ANALYZE after restoring from a dump file to ensure optimal performance; see Section 24.1.3 and Section 24.1.6 for more information.

pg_restore#

postgres#

PostgreSQL database server

-D the file system location of the database configuration files

psql#

PostgreSQL interactive terminal. Reads from ~/.psqlrc on startup, if it exists.

Options#

-d --dbname=dbname database name to connect to
-h --host=hostname hostname to connect to
-p --port=port port; usually defaults to 5432
-U --username=username connect as the postgres user username
-c --command=command command to execute
-f --file=filename execute commands from file, then exit
-s --single-step user will be prompted before each command is sent to server; useful for debugging

Connect to the local cluster as user postgres:

psql --username postgres

Connect to the local cluster as user postgres, connecting to database mydb:

psql --username postgres --dbname mydb

Meta-Commands#

Help

help show psql help
\q \quit quit
\h \help list all SQL commands
\h COMMAND \help COMMAND help for COMMAND
\? help with psql commands

Option Suffixes, affixed to selected commands for more information

S show system options
+ show additional detail

Informational

\list[+] or \l[+] list databases
\d[S+] equivalent to \dtvmsE; list tables, views, and sequences
\d[S+] NAME describe table, view, sequence, or index
\dt[S+] [PATTERN] list tables (describe tables)

Connection

\connect or \c connect to a database

List tables in mydb:

mydb=# \dt
          List of relations
 Schema |  Name   | Type  |  Owner
--------+---------+-------+----------
 public | cities  | table | postgres
 public | weather | table | postgres
(2 rows)

List tables in mydb with additional detail:

mydb=# \dt+
                                      List of relations
 Schema |  Name   | Type  |  Owner   | Persistence | Access method |    Size    | Description
--------+---------+-------+----------+-------------+---------------+------------+-------------
 public | cities  | table | postgres | permanent   | heap          | 8192 bytes |
 public | weather | table | postgres | permanent   | heap          | 8192 bytes |
(2 rows)

postgres-common Utilities#

pg_conftool#

pg_createcluster#

pg_ctlcluster#

Start, stop, restart, reload a PostgreSQL cluster.

You have to start this program as the user who owns the database cluster or as root.

status checks whether a server is running
stop stops the server of a given cluster
start starts a server and creates a log file, if needed
restart stops the server (if it is running) and starts it again
reload reread configuration files without a full shutdown of the server

pg_dropcluster#

pg_lsclusters#

pg_renamecluster#

pg_upgradecluster#

pg_virtualenv#

3rd Party Tools#

pgbackrest#

Recovery Time Objective (RTO) vs. Recovery Point Objective (RPO) is a great way to consider the question of: “What should be my backup strategy?”.

Selected Global Options#

--config-include-path
--config
--log-level-console
--log-path
--stanza

backup#

Options:

--type

Create a diff backup:

sudo -u postgres pgbackrest             \
  --config=/path/to/pgbackrest.conf     \
  --config-include-path=/path/to/conf.d \
  --log-level-console=info              \
  --log-path=/path/to/log/pgbackrest    \
  --stanza=demo                         \
  --type=diff

info#

Gives info on current state of backups for a stanza:

sudo -u postgres pgbackrest             \
  --config=/path/to/pgbackrest.conf     \
  --config-include-path=/path/to/conf.d \
  --log-level-console=info              \
  --stanza=demo                         \
  info

Resources#

pgFormatter / pg_format#

Important

I now use sqlfluff.

SQL formatter / beautifier.

Selected Options#

-b --comma-start in a parameters list, start with the comma (see -e)
-e --comma-end in a parameters list, end with the comma (default)

Resources#

Environment Variables#

PGDATA file system location of the database configuration files
PGHOST name of the host to connect to; if it looks like an absolute path then this is the directory in which the socket file is stored
PGUSER postgres user name to connect as; defaults to the same as the operating system name of the user running the application
PGDATABASE database name; defaults to be the same as the user name

Tips#

On relation names:

On role names:

Resources#

Frequently Asked Questions (FAQs)#

Why does INSERT return lines INSERT 0 1?#

This is a command tag of the form:

INSERT oid count

Where oid refers to the deprecated object identifier and count refers to the number of rows inserted. See more detail in the INSERT documentation.

Why is it called “Postgres”? Where did the name “Postgres” come from? Where did the name “PostgreSQL” originate?#

Chronological sequence:

How to stop the postgres process and disable it from running at startup on macOS?#

Determine the .plist defining the launchd service:

ls -halt /Library/LaunchDaemons/

Let’s assume it is /Library/LaunchDaemons/postgresql-16.plist.

Tell launchd to stop the service and remove it from the current boot session:

sudo launchctl bootout system /Library/LaunchDaemons/postgresql-16.plist

Tell launchd to prevent the service from running at next boot session:

sudo launchctl disable system/postgresql-16

Confirm it worked:

sudo launchctl print-disabled system

How can I tell what locale my database is in?#

SELECT datname, datcollate, datctype
FROM pg_database
WHERE datname = current_database();

Terminology#

ACID#
1.
aggregate function#
1.

Reduces multiple inputs to a single output value; computes a single result from multiple input rows.

Related:

alias#
1.

A temporary name assigned to a table or column.

atomic#
1.

Either happens completely or not at all.

Related:

atomic type#
1.

An indivisable kind of data; e.g. a boolean.

Related:

attributes#
1.

The columns; or the divisions of data kinds.

Related:

catalog#
1.

Database; used in the SQL standard.

Compare:

cluster#
1.

A collection of databases managed by a single PostgreSQL server instance.

cluster#
1.

A collection of databases.

column reference#
1.

Correlation.columnname.

Related:

command#
1.
constraint#
1.
covering index#
1.
cross join#
1.
Data Definition Language (DDL)#
1.
dangling tuple#
1.

Tuple from a join that does not have a match.

Related:

data directory#
1.
data integrity#
1.
data type#
1.
database#
1.
delimited identifier#
1.

A sequence of characters enclosed by double quotes and treated as case sensitive; is always considered an identifier and never a key word.

Also: quoted identifier

Broader:

disaster recovery (DR)#
1.
domain#
1.
dump#
1.

Generate a file with SQL commands that, when fed back into the server, will recreate the database in the same state as it was at the time of the dump.

durability#
1.

A guarantee of the recording of committed transactions even if the server crashes or loses power.

Related:

execution plan#
1.

The actual sequence of steps necessary to execute the SQL statement.

Related:

extensibility#
1.
FROM#
1.

Specifies the relation(s) on which the select projects.

Related:

foreign key constraint#
1.
GROUP BY#
1.

Allows partitioning relations into groups by values of a given attribute or set of attributes; when used in conjuncture with aggregations like min or max, those aggregations will be computed independently.

Related:

HAVING#
1.

Allows apply conditions to the results of the aggregate values; applies to the group generated by the group by (whereas the where applies to single rows at a time)

Related:

heap#
1.

The table’s main data area.

Related:

host-based authentication (HBA)#
1.
hot standby server#
1.

A standby server that can accept connections and serve read-only queries.

Related:

identifier#
1.

Tokens that name the tables, columns, or other database objects within a command.

Broader:

Narrower:

index#
1.
index#
1.
index-only scan#
1.

an operation that does not have to access the heap

Related:

inner join#
1.
insert#
1.
instance#
1.

The data stored in the relations (which are described by the schema) at any given point.

Related:

JOIN#
1.

Returns a relation generated from combinations of tuples based on the provided conditions.

Compare:

join#
1.
join#
1.

Queries that access multiple tables (or multiple instances of the same table) at one time.

— https://www.postgresql.org/docs/16/tutorial-join.html

Related:

key#
1.

Attribute whose value is unique in each tuple (note: could also be a set of attributes)

Related:

key word#
1.

Tokens that have a fixed meaning in SQL (e.g. SELECT, UPDATE, or VALUES)

Broader:

lock#
1.
multiversion concurrency control (MVCC)#
1.
operand#
1.
operator#
1.
outer join#
1.
parameter#
1.
partition#
1.

Splitting a single table into smaller tables.

partition#
1.
pgdg (Postgres Development Group)#
1.

Maintains the Postgres packages.

positional parameter#
1.
qualify#
1.

Adding more specificity to a field or query; e.g. using SELECT tbl1.foo instead of SELECT foo; or adding a clause to a query (like WHERE) that restricts the results.

query#
1.

How to retrieve data from a table.

2.

The process of retrieving, or the command to retrieve, data from a database.

query plan#
1.
query planner#
1.

Component of DBMS that determines sequence of steps necessary to execute the SQL statement.

Related:

recovery point objective (RPO)#
1.

How much data can be afforded to lose.

Related:

recovery time objective (RTO)#
1.

How long the system can be down.

Related:

referential integrity#
1.
relation#
1.

Essentially: the mathematical term for a table.

Compare:

relations#
1.

The tables; or the structures that store related data.

Compare:

Related:

reliability#
1.
replication#
1.
rewrite rules#
1.
role#
1.

A database user, or a group of database users (depending on how the role is set up)

rule#
1.
SELECT#
1.

Specifies the attributes to be projected from a relation and returned.

Related:

SQL Standard#
1.
scalar#
1.

The result of a value expression.

Related:

schema#
1.

Contains tables and other named objects (data types, functions, and operators). schemas are analogous to directories at the operating system level (but cannot be nested).

schema#
1.

Structural description of relations; the name, the attributes, and the types of those attributes.

Related:

secondary index#
1.

Each index is stored separately from the table’s main data area.

Related:

self join#
1.
sequential scan#
1.
sequential scan#
1.
serializable snapshot isolation (SSI)#
1.
statement#
1.

The SQL being executed by the DBMS.

Related:

stored function#
1.
stored procedure#
1.
structured type#
1.

A composed kind of data, possibly user-defined; e.g. a PersonType

Related:

subquery#
1.
suffix truncation#
1.
table#
1.

A named collection of rows.

Related:

table expression#
1.

An expression that computes a table.

Related:

table partitioning#
1.
tablespaces#
1.
token#
1.

Can be a key word, an identifier, a quoted identifier, a literal (or constant), or a special character symbol.

Narrower:

transaction (xact)#
1.

Bundles multiple steps into a single, all-or-nothing operation.

Related:

transaction block#
1.

A group of statements surrounded by BEGIN and COMMIT.

Related:

transaction isolation level#
1.
transactional integrity#
1.
trigger#
1.
trigger#
1.
tuples#
1.

The rows; or records of data across attributes.

Related:

type#
1.

The domains; or the kind of data stored in each attribute.

Related:

update#
1.

Modifying data that is already present in the database.

vacuum#
1.
value expression#
1.
view#
1.
view#
1.
visibility map#
1.
WHERE#
1.

Applies a condition to individual tuples from the specified relation(s)

Related:

warm standby server#
1.

A standby server that cannot accept connections until promoted.

Related:

window frame#
1.
window function#
1.

Performs a calculation across a set of table rows that are somehow related to the current row.

Related:

write ahead log (WAL)#
1.

A record of every change made to the database's data files.

postgres-study#

README.md#

# postgres-study

personal study area for Postgres

queries/delete.sql#

DELETE FROM t1
WHERE
  col_a = 1;

queries/insert.sql#

INSERT INTO t1 (col_a)
VALUES
('foo')
, ('bar')
, ('baz');

queries/select-like.sql#

SELECT col_a
FROM
  t1
WHERE
  col_a LIKE '%pattern%';