Working with Databases

1. Creating Database

CREATE DATABASE shop;
CREATE DATABASE shop
  WITH OWNER = app_owner
       ENCODING = 'UTF8'
       LC_COLLATE = 'en_US.UTF-8'
       LC_CTYPE   = 'en_US.UTF-8'
       LOCALE_PROVIDER = 'icu' ICU_LOCALE = 'en-US'
       TEMPLATE = template0
       CONNECTION LIMIT = 200;
OptionPurpose
OWNERInitial owner role
ENCODINGCharacter encoding
TEMPLATEtemplate1 (default) or template0 (clean)
TABLESPACEDefault storage location
LOCALE_PROVIDERicu NEW or libc

2. Listing Databases

\l                  -- psql shortcut
\l+                 -- include sizes
SELECT datname, pg_catalog.pg_get_userbyid(datdba) AS owner,
       pg_size_pretty(pg_database_size(datname)) AS size
  FROM pg_database ORDER BY datname;
SourceUse
pg_databaseSystem catalog
\lQuick interactive listing

3. Connecting to Database

\c shop
\c shop alice
psql -d shop
ApproachNotes
psql -dConnect at launch
\cReconnect inside session
SET search_pathSwitch schema, not DB

4. Setting Database Owner

ALTER DATABASE shop OWNER TO app_owner;
RequirementDetail
CallerMust be member of new owner role
EffectOwner gets all default privileges

5. Setting Database Encoding

EncodingNotes
UTF8Default, recommended
LATIN1Legacy single-byte
SQL_ASCIINo validation (avoid)
Warning: Encoding cannot be changed after creation; must dump & reload.

6. Setting Database Collation

CREATE DATABASE shop
  LC_COLLATE = 'en_US.UTF-8'
  LC_CTYPE   = 'en_US.UTF-8'
  TEMPLATE   = template0;
SettingEffect
LC_COLLATEString sort order
LC_CTYPECharacter classification
ICU providerVersion-stable cross-platform collation

7. Renaming Database

ALTER DATABASE shop RENAME TO shop_old;
Note: Cannot rename a database while connected to it; connect to postgres or another DB first.

8. Setting Database Parameters

ALTER DATABASE shop SET work_mem = '64MB';
ALTER DATABASE shop SET search_path = app, public;
ALTER DATABASE shop RESET work_mem;
ScopeCommand
DatabaseALTER DATABASE ... SET ...
RoleALTER ROLE ... SET ...
Role-in-DBALTER ROLE x IN DATABASE shop SET ...

9. Viewing Database Details

\l+ shop
SELECT * FROM pg_database WHERE datname = 'shop';
SELECT datname, datcollate, datctype, encoding, datconnlimit
  FROM pg_database WHERE datname = 'shop';

10. Checking Database Size

FunctionReturns
pg_database_size('shop')Bytes
pg_size_pretty(...)Human-readable
pg_total_relation_size('t')Table + indexes + TOAST
SELECT datname, pg_size_pretty(pg_database_size(datname)) AS size
  FROM pg_database ORDER BY pg_database_size(datname) DESC;

11. Dropping Database

DROP DATABASE IF EXISTS shop_old;
DROP DATABASE shop WITH (FORCE);   -- terminates other sessions (PG 13+)
Warning: Cannot be undone. Cannot drop a database you are connected to.