One page

SQL and PostgreSQL cheat sheet

What to keep at hand. If a line is not clear, go back to the matching lesson in the course.

Open the course: SQL and PostgreSQL

Reading data

WhatHow
SelectSELECT id, name FROM users
FilterWHERE status = 'paid' AND total >= 100
PageORDER BY created_at DESC LIMIT 20 OFFSET 40
JoinJOIN users u ON u.id = o.user_id
GroupsGROUP BY status HAVING COUNT(*) > 10

Changing data

WhatHow
InsertINSERT INTO users (email, name) VALUES ($1, $2) RETURNING id
UpdateUPDATE users SET name = $1 WHERE id = $2
TransactionBEGIN; … COMMIT;
IndexCREATE INDEX ON orders (user_id)

Schema and complex queries

WhatHow
Constraintsemail text NOT NULL UNIQUE
Foreign keyuser_id bigint REFERENCES users (id)
Named stepWITH spent AS (SELECT …) SELECT … FROM spent
Query planEXPLAIN ANALYZE SELECT …
Create or updateON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name
Number within a groupROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)

Other cheat sheets