Summary
- A relational database keeps data in tables of rows and columns, enforces rules on every change, serves many users at once and makes each transaction all or nothing.
- psql connects to PostgreSQL as a role, runs SQL and meta-commands such as \d, \x and \i, and runs files with -f, where -1 and ON_ERROR_STOP make a file succeed or fail as a whole.
- psql saves each statement at once unless you start a transaction with BEGIN, which lets you check your changes and then COMMIT or ROLLBACK them.
- Good types are the first rules: integer or numeric for money and never floating point, text rather than varchar, timestamptz in the Africa/Johannesburg zone, and identity columns instead of serial.
- CREATE TABLE defines columns with PRIMARY KEY, NOT NULL, UNIQUE, CHECK and DEFAULT, ALTER TABLE changes a design that holds data, and DROP TABLE deletes a table for good.
- A foreign key links a row to a row in another table, and ON DELETE RESTRICT refuses to delete a referenced row while ON DELETE CASCADE deletes the referring rows too.
- INSERT names its columns and can answer with RETURNING, and SELECT chooses rows with WHERE, IN, BETWEEN, LIKE and ILIKE, sorts with ORDER BY and pages with LIMIT and OFFSET.
- NULL means unknown, so comparisons with it are unknown and WHERE drops those rows, which is why you test with IS NULL and show placeholders with COALESCE.
- UPDATE and DELETE without WHERE change every row, so check the WHERE with a SELECT first, work inside BEGIN and read the command tag before you COMMIT.
- PostgreSQL's errors name the broken constraint and give DETAIL, HINT and a SQLSTATE code, which show exactly which rule a change broke.