← All guides

Programmer’s Reference

SQL · PostgreSQL

Learn PostgreSQL queries, psql, transactions, and logical backups.

PostgreSQL SQL and psql commands are separate from terminal commands. Use a disposable demo database and a provisioned demo user. Query examples assume a demo sites table (id, name, enabled) and checks table (id, site_id, result); schema-change examples use separate demo_sites fixtures.

19 entries · Essentials first · Reviewed October 5, 2026

Glossary: commands, keywords & terms

Select a term for its definition, syntax, example, and common mistakes.

Query keywords and terms

AND / OR / NOT

Combine or negate conditions.

SQL code
SELECT id, name FROM sites
WHERE enabled = TRUE AND (name = 'Demo' OR name = 'Example');

Practical useUse this construct in your own practice project.

Common mistakesAND binds more tightly than OR; parentheses make intent clear.

Source: www.postgresql.org documentation

ORDER BY / ASC / DESC

Sort the result by one or more expressions.

SQL code
SELECT id, name FROM sites ORDER BY name ASC, id DESC;

Practical useUse this construct in your own practice project.

Common mistakesWithout ORDER BY, returned row order is not guaranteed.

Source: www.postgresql.org documentation

LIMIT / OFFSET

Limit rows and skip an initial number of rows.

SQL code
SELECT id, name FROM sites ORDER BY id LIMIT 10 OFFSET 20;

Practical useUse this construct in your own practice project.

Common mistakesUse a deterministic order; large offsets can be expensive.

Source: www.postgresql.org documentation

CASE / WHEN / THEN / ELSE / END

Return a value selected by conditions.

SQL code
SELECT name, CASE WHEN enabled = TRUE THEN 'Ready' ELSE 'Disabled' END AS state
FROM sites;

Practical useUse this construct in your own practice project.

Common mistakesCASE is an expression, not a procedural goto or if statement.

Source: www.postgresql.org documentation

GROUP BY / HAVING

Group rows and filter groups using aggregate conditions.

SQL code
SELECT result, COUNT(*) AS total
FROM checks GROUP BY result HAVING COUNT(*) > 1;

Practical useUse this construct in your own practice project.

Common mistakesWHERE filters rows before grouping; HAVING filters groups afterward.

Source: www.postgresql.org documentation

Essentials

psql table and connection commands

Inspect the current connection, list tables, describe a table, and quit. Backslash commands belong in psql, not Bash.

psql commands
\conninfo
\dt
\d sites
\q

Practical useConfirm the database before inspecting demo inventory.

Common mistakesDo not add SQL semicolons to psql meta-commands. \dt lists visible tables according to the search path.

Source: www.postgresql.org documentation

Schema and indexes

Identity columns and CREATE TABLE

Define an automatically generated identifier and required fields.

SQL code
CREATE TABLE demo_sites (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL,
    enabled BOOLEAN NOT NULL DEFAULT TRUE
);

Practical useDefine a portable-looking inventory with PostgreSQL-specific identity syntax.

Common mistakesAUTO_INCREMENT is not PostgreSQL syntax. Quote identifiers only when necessary; unquoted names fold to lowercase.

Source: www.postgresql.org documentation

EXPLAIN and indexes

Show a query plan without executing the SELECT, then define an index on a demo foreign-key column.

⚠ Caution: Index creation changes the schema and may block writes.

SQL code
EXPLAIN SELECT * FROM checks WHERE site_id = 7;
CREATE INDEX demo_checks_site_id_idx ON checks (site_id);

Practical useEvaluate a slow inventory lookup on staging.

Common mistakesEXPLAIN ANALYZE runs the statement. A normal CREATE INDEX can block writes; plan live maintenance separately.

Source: www.postgresql.org documentation (1) · www.postgresql.org documentation (2)

Changing data

INSERT with RETURNING

Insert a record and return its generated ID in one statement.

⚠ Caution: Adds a database row.

SQL code
INSERT INTO demo_sites (name)
VALUES ('Demo')
RETURNING id;

Practical useCapture a new demo site ID.

Common mistakesDo not assume the ID sequence is gapless. Bind external values through the application’s database client.

Source: www.postgresql.org documentation

BEGIN, UPDATE, and ROLLBACK

Group a change in a transaction and discard it at the end of this example.

⚠ Caution: Updates rows temporarily and can block concurrent work until rollback.

SQL code
BEGIN;
SELECT id, name FROM demo_sites WHERE id = 7;
UPDATE demo_sites SET enabled = FALSE WHERE id = 7;
ROLLBACK;

Practical usePractice a project change without keeping it.

Common mistakesTransactions keep locks until completion. After a statement error, roll back before continuing.

Source: www.postgresql.org documentation

DELETE with RETURNING

Delete a selected record, show the affected identifier, then roll back the practice transaction.

⚠ Caution: Deletes data if committed; locks persist until transaction completion.

SQL code
BEGIN;
DELETE FROM demo_sites WHERE id = 7 RETURNING id;
ROLLBACK;

Practical usePractice deleting a demo inventory item.

Common mistakesNo WHERE means every row. A future COMMIT makes the deletion permanent; back up and preview first.

Source: www.postgresql.org documentation

Queries and reports

LEFT JOIN and counts

Include sites with no checks and count matching check IDs.

SQL code
SELECT s.id, s.name, COUNT(c.id) AS checks
FROM sites AS s
LEFT JOIN checks AS c ON c.site_id = s.id
GROUP BY s.id, s.name
ORDER BY s.name;

Practical useReport demo sites that have no check history.

Common mistakesCOUNT(*) would count the preserved outer row even when there is no check. A WHERE filter on the right table can remove unmatched rows.

Source: www.postgresql.org documentation

Backups and maintenance

pg_dump and pg_restore

Make a custom-format dump and restore into a separate existing empty demo database.

⚠ Caution: Dump can replace the output file; restore creates objects and writes data in the target database.

Terminal
pg_dump -U demo_user -d demo_db -Fc -f demo-db.dump
pg_restore -U demo_user -d demo_restore --no-owner demo-db.dump

Practical useTest recovery of a disposable staging database.

Common mistakesUse compatible tool/server versions. Confirm the restore target; do not add --clean to a live database. Role and global-object backups are separate.

Source: www.postgresql.org documentation (1) · www.postgresql.org documentation (2)

Back to top ↑