PostgreSQL Reference
Kip Landergren
(Updated: )
Contents#
- Install Location / Data Directory / Data Area
- Postgres Utilities
- postgres-common Utilities
- 3rd Party Tools
- Environment Variables
- Tips
- Resources
- Frequently Asked Questions (FAQs)
- Terminology
- postgres-study
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:
- we change the ownership of path/to/data because we want postgres to own the server process and therefore have access to the files and directories that
initdb creates - --auth and --pwprompt are passed just to have sensible defaults; you will likely modify your pg_hba.conf file after init appropriate to your usage
- --data-checksums is used on advice that the performance cost (seen referenced to be ~1-2%) is worth the peace of mind
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#
- for a single database
- use the format option (and choose the one that works with pg_restore
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#
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#
- darold/pgFormatter GitHub repository
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:
- prefer prefix t_ for tables (this also avoids key word / reserved word collisions)
- prefer prefix vw_ for views
On role names:
- prefer underscores to dashes to prevent need of quoting
- consider pattern: {app}_{service}_{access}; e.g. foo_grpc_rw
Resources#
- Releases / Release Notes
- Official Postgres Wiki
- Official Postgres Frequently Asked Questions (FAQ)
- Don’t Do This A short list of common mistakes.
- THE DESIGN OF POSTGRES (PDF) by Michael Stonebraker and Lawrence A. Rowe
- The POSTGRES Data Model (PDF) by Lawrence A. Rowe and Michael Stonebraker
- THE DESIGN OF THE POSTGRES STORAGE SYSTEM by Michael Stonebraker
- 3rd Party
- Implementing UUIDs v7 in pure SQL
- dverite/postgres-uuidv7-sql
- UUIDs vs serials for keys
- UUID, serial or identity columns for PostgreSQL auto-generated primary keys?
- Identity Crisis: Sequence v. UUID as Primary Key
- Postgres UUIDv7 + per-backend monotonicity
- 0065_uuid_v7_and_partitioning_timescaledb.md
- kjmph/A_UUID_v7_for_Postgres.sql
- fabiolimace/UUIDv6.sql
- Goodbye integers. Hello UUIDv7!
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:
- Ingres: INteractive Graphics REtrieval System.
- Postgres, or post inGRES (after inGRES)
- Postgres95, which was the cleaned up ANSI C version released to the web
- PostgreSQL, reflecting the connection / support of SQL
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#(term ACID)
- 1.
- aggregate function#(term aggregate function)
- 1.
Reduces multiple inputs to a single output value; computes a single result from multiple input rows.
Related:
- alias#(term alias)
- 1.
A temporary name assigned to a table or column.
- atomic#(term atomic)
- 1.
Either happens completely or not at all.
Related:
- atomic type#(term atomic type)
- 1.
An indivisable kind of data; e.g. a
boolean.Related:
- attributes#(term attributes)
- 1.
The columns; or the divisions of data kinds.
Related:
- catalog#(term catalog)
- 1.
Database; used in the SQL standard.
Compare:
- cluster#(term cluster)
- 1.
A collection of databases managed by a single PostgreSQL server instance.
- cluster#(term cluster)
- 1.
A collection of databases.
- column reference#(term column reference)
- 1.
Correlation.columnname.
Related:
- command#(term command)
- 1.
- constraint#(term constraint)
- 1.
- covering index#(term covering index)
- 1.
- cross join#(term cross join)(term cartesian product)
- 1.
- Data Definition Language (DDL)#(term Data Definition Language)(term DDL)
- 1.
- dangling tuple#(term dangling tuple)
- 1.
Tuple from a join that does not have a match.
Related:
- data directory#(term data directory)(term data area)
- 1.
- data integrity#(term data integrity)
- 1.
- data type#(term data type)
- 1.
- database#(term database)
- 1.
- delimited identifier#(term delimited identifier)(term quoted 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)#(term disaster recovery)(term DR)
- 1.
- domain#(term domain)
- 1.
- dump#(term 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#(term durability)
- 1.
A guarantee of the recording of committed transactions even if the server crashes or loses power.
Related:
- execution plan#(term execution plan)
- 1.
The actual sequence of steps necessary to execute the SQL statement.
Related:
- extensibility#(term extensibility)
- 1.
- FROM#(term FROM)
- 1.
Specifies the relation(s) on which the select projects.
Related:
- foreign key constraint#(term foreign key constraint)
- 1.
- GROUP BY#(term 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
minormax, those aggregations will be computed independently.Related:
- HAVING#(term HAVING)
- 1.
Allows apply conditions to the results of the aggregate values; applies to the group generated by the
group by(whereas thewhereapplies to single rows at a time)Related:
- heap#(term heap)
- 1.
The table’s main data area.
Related:
- host-based authentication (HBA)#(term host-based authentication)(term HBA)
- 1.
- hot standby server#(term hot standby server)
- 1.
A standby server that can accept connections and serve read-only queries.
Related:
- identifier#(term identifier)
- 1.
Tokens that name the tables, columns, or other database objects within a command.
Broader:
Narrower:
- index#(term index)
- 1.
- index#(term index)
- 1.
- index-only scan#(term index-only scan)
- 1.
an operation that does not have to access the heap
Related:
- inner join#(term inner join)
- 1.
- insert#(term insert)
- 1.
- instance#(term instance)
- 1.
The data stored in the relations (which are described by the schema) at any given point.
Related:
- JOIN#(term JOIN)
- 1.
Returns a relation generated from combinations of tuples based on the provided conditions.
Compare:
- join#(term join)
- 1.
- join#(term join)
- key#(term key)
- 1.
Attribute whose value is unique in each tuple (note: could also be a set of attributes)
Related:
- key word#(term key word)
- 1.
Tokens that have a fixed meaning in SQL (e.g. SELECT, UPDATE, or VALUES)
Broader:
- lock#(term lock)
- 1.
- multiversion concurrency control (MVCC)#(term multiversion concurrency control)(term MVCC)
- 1.
- operand#(term operand)
- 1.
- operator#(term operator)
- 1.
- outer join#(term outer join)
- 1.
- parameter#(term parameter)
- 1.
- partition#(term partition)
- 1.
Splitting a single table into smaller tables.
- partition#(term partition)
- 1.
- pgdg (Postgres Development Group)#(term pgdg)(term Postgres Development Group)
- 1.
Maintains the Postgres packages.
- positional parameter#(term positional parameter)
- 1.
- qualify#(term 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#(term 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#(term query plan)
- 1.
- query planner#(term query planner)
- 1.
Component of DBMS that determines sequence of steps necessary to execute the SQL statement.
Related:
- recovery point objective (RPO)#(term recovery point objective)(term RPO)
- 1.
How much data can be afforded to lose.
Related:
- recovery time objective (RTO)#(term recovery time objective)(term RTO)
- 1.
How long the system can be down.
Related:
- referential integrity#(term referential integrity)
- 1.
- relation#(term relation)
- 1.
Essentially: the mathematical term for a table.
Compare:
- relations#(term relations)
- 1.
The tables; or the structures that store related data.
Compare:
Related:
- reliability#(term reliability)
- 1.
- replication#(term replication)
- 1.
- rewrite rules#(term rewrite rules)
- 1.
- role#(term role)
- 1.
A database user, or a group of database users (depending on how the role is set up)
- rule#(term rule)
- 1.
- SELECT#(term SELECT)
- 1.
Specifies the attributes to be projected from a relation and returned.
Related:
- SQL Standard#(term SQL Standard)
- 1.
- scalar#(term scalar)
- 1.
The result of a value expression.
Related:
- schema#(term 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#(term schema)
- 1.
Structural description of relations; the name, the attributes, and the types of those attributes.
Related:
- secondary index#(term secondary index)
- 1.
Each index is stored separately from the table’s main data area.
Related:
- self join#(term self join)
- 1.
- sequential scan#(term sequential scan)
- 1.
- sequential scan#(term sequential scan)
- 1.
- serializable snapshot isolation (SSI)#(term serializable snapshot isolation)(term SSI)
- 1.
- statement#(term statement)
- 1.
The SQL being executed by the DBMS.
Related:
- stored function#(term stored function)
- 1.
- stored procedure#(term stored procedure)
- 1.
- structured type#(term structured type)
- 1.
A composed kind of data, possibly user-defined; e.g. a
PersonTypeRelated:
- subquery#(term subquery)
- 1.
- suffix truncation#(term suffix truncation)
- 1.
- table#(term table)
- 1.
A named collection of rows.
Related:
- table expression#(term table expression)
- 1.
An expression that computes a table.
Related:
- table partitioning#(term table partitioning)
- 1.
- tablespaces#(term tablespaces)
- 1.
- token#(term token)
- 1.
Can be a key word, an identifier, a quoted identifier, a literal (or constant), or a special character symbol.
Narrower:
- transaction (xact)#(term transaction)(term xact)
- 1.
Bundles multiple steps into a single, all-or-nothing operation.
Related:
- transaction block#(term transaction block)
- 1.
A group of statements surrounded by BEGIN and COMMIT.
Related:
- transaction isolation level#(term transaction isolation level)
- 1.
- transactional integrity#(term transactional integrity)
- 1.
- trigger#(term trigger)
- 1.
- trigger#(term trigger)
- 1.
- tuples#(term tuples)
- 1.
The rows; or records of data across attributes.
Related:
- type#(term type)
- 1.
The domains; or the kind of data stored in each attribute.
Related:
- update#(term update)
- 1.
Modifying data that is already present in the database.
- vacuum#(term vacuum)
- 1.
- value expression#(term value expression)
- 1.
- view#(term view)
- 1.
- view#(term view)
- 1.
- visibility map#(term visibility map)
- 1.
- WHERE#(term WHERE)
- 1.
Applies a condition to individual tuples from the specified relation(s)
Related:
- warm standby server#(term warm standby server)
- 1.
A standby server that cannot accept connections until promoted.
Related:
- window frame#(term window frame)
- 1.
- window function#(term 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)#(term write ahead log)(term 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%';