Scope. PostgreSQL and psql command-line use. Authentication and operating-system user configuration are installation-specific.
Console
$ psql #logs in to default database & default user
$ sudo -u <rolename:postgres> psql #logs in with a particular user
Replace each
Command
- List roles:
\du - List tables:
\dt - List databases:
\l - Connect to a database:
\c <database> - Describe a table:
\d <table>or\d+ <table> - Quit:
\q
Create a database
$ createdb databasename
Transactional example
BEGIN;
CREATE TEMP TABLE items (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price numeric(10,2) CHECK (price >= 0)
);
INSERT INTO items (name, price) VALUES ('Notebook', 4.50);
SELECT id, name, price FROM items WHERE price < 10 ORDER BY id;
UPDATE items SET price = 5.00 WHERE name = 'Notebook';
SELECT count(*) AS total FROM items;
ROLLBACK;
ROLLBACK discards this example's table and changes. NULL checks use IS NULL, not = NULL.
Query planning
EXPLAIN SELECT ... shows an estimated plan. EXPLAIN ANALYZE actually executes the statement; avoid applying it casually to writes. Parameterize application queries instead of interpolating user input.