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;
| Option | Purpose |
|---|---|
| OWNER | Initial owner role |
| ENCODING | Character encoding |
| TEMPLATE | template1 (default) or template0 (clean) |
| TABLESPACE | Default storage location |
| LOCALE_PROVIDER | icu 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;
| Source | Use |
|---|---|
| pg_database | System catalog |
| \l | Quick interactive listing |
3. Connecting to Database
\c shop
\c shop alice
psql -d shop
| Approach | Notes |
|---|---|
| psql -d | Connect at launch |
| \c | Reconnect inside session |
| SET search_path | Switch schema, not DB |
4. Setting Database Owner
ALTER DATABASE shop OWNER TO app_owner;
| Requirement | Detail |
|---|---|
| Caller | Must be member of new owner role |
| Effect | Owner gets all default privileges |
5. Setting Database Encoding
| Encoding | Notes |
|---|---|
| UTF8 | Default, recommended |
| LATIN1 | Legacy single-byte |
| SQL_ASCII | No 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;
| Setting | Effect |
|---|---|
| LC_COLLATE | String sort order |
| LC_CTYPE | Character classification |
| ICU provider | Version-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;
| Scope | Command |
|---|---|
| Database | ALTER DATABASE ... SET ... |
| Role | ALTER ROLE ... SET ... |
| Role-in-DB | ALTER 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
| Function | Returns |
|---|---|
| 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.