PostgreSQL/Cheat sheet
Last edited by dave on 01/12/2025, 13:19:18 UTC
Contents
Check out the other cheat sheets!
Do you prefer building with Prisma ORM? Check out Prisma ORM cheat sheet for PostgreSQL!
Your one-stop quick reference for mastering PostgreSQL โ from setup and SQL essentials to performance tuning and admin magic! ๐
โ๏ธ Setup & Connection
Install (Linux)
sudo apt install postgresql postgresql-contrib
Start & Enable Service
sudo systemctl start postgresql sudo systemctl enable postgresql
Switch to Postgres User
sudo -i -u postgres
Enter the psql Shell
psql
Connect to a Database
psql -U username -d dbname -h localhost -p 5432
Exit psql
\q
๐๏ธ Database Management
| Command | Description |
|---|---|
\l | List all databases |
CREATE DATABASE dbname; | Create a new database |
\c dbname | Connect to a database |
DROP DATABASE dbname; | Delete a database |
ALTER DATABASE name RENAME TO newname; | Rename database |
๐ค Users & Roles
| Command | Description |
|---|---|
\du | List all roles |
CREATE USER name WITH PASSWORD 'pass'; | Create a user |
CREATE ROLE role_name; | Create a role |
ALTER USER name WITH SUPERUSER; | Grant superuser privileges |
GRANT ALL PRIVILEGES ON DATABASE db TO user; | Give user full access |
DROP USER name; | Remove user |
Role-Based Access
GRANT SELECT, INSERT ON table TO role; REVOKE UPDATE ON table FROM role;
๐งฑ Tables
| Command | Description |
|---|---|
\dt | List tables |
CREATE TABLE name (...); | Create table |
\d table | Describe table structure |
DROP TABLE name; | Delete table |
ALTER TABLE name ADD COLUMN new_col TEXT; | Add a column |
ALTER TABLE name DROP COLUMN col; | Remove column |
ALTER TABLE name RENAME TO newname; | Rename table |
TRUNCATE TABLE name; | Remove all data |
Example
CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE, created_at TIMESTAMP DEFAULT NOW() );
๐พ Data Manipulation (CRUD)
Insert
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');
Select
SELECT * FROM users; SELECT name, email FROM users WHERE id = 1;
Update
UPDATE users SET email = 'new@email.com' WHERE id = 1;
Delete
DELETE FROM users WHERE id = 1;
Returning Clause
INSERT INTO users (name) VALUES ('Bob') RETURNING id;
๐ Filtering & Sorting
SELECT * FROM products WHERE price > 50; SELECT * FROM users WHERE name LIKE 'A%'; SELECT * FROM orders ORDER BY created_at DESC; SELECT * FROM employees WHERE department IN ('HR', 'IT'); SELECT * FROM logs WHERE created_at BETWEEN '2024-01-01' AND '2025-01-01';
๐ Joins
SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id;
| Type | Syntax | Description |
|---|---|---|
| INNER | JOIN | Match both tables |
| LEFT | LEFT JOIN | Keep left, even if no match |
| RIGHT | RIGHT JOIN | Keep right |
| FULL | FULL OUTER JOIN | Keep all rows |
๐งฎ Aggregations
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department ORDER BY avg_salary DESC;
| Function | Description |
|---|---|
COUNT() | Number of rows |
SUM() | Total |
AVG() | Average |
MIN() / MAX() | Minimum / Maximum |
HAVING Clause
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
๐ช Constraints
| Constraint | Description |
|---|---|
PRIMARY KEY | Unique identifier |
UNIQUE | No duplicates |
NOT NULL | Must have value |
CHECK | Validate condition |
FOREIGN KEY | Link to another table |
Example:
CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id), total NUMERIC CHECK (total >= 0) );
๐งฉ Indexes
CREATE INDEX idx_users_email ON users(email); DROP INDEX idx_users_email;
| Type | Use Case |
|---|---|
BTREE | Default |
GIN | JSONB / full-text |
GiST | Geometric / range |
BRIN | Large sequential data |
๐ง JSON & Arrays
JSON
CREATE TABLE profiles ( id SERIAL PRIMARY KEY, data JSONB ); INSERT INTO profiles (data) VALUES ('{"name":"Alice","age":25}'); SELECT data->>'name' FROM profiles;
Arrays
CREATE TABLE tags ( id SERIAL, keywords TEXT[] ); INSERT INTO tags (keywords) VALUES (ARRAY['tech','postgres']); SELECT * FROM tags WHERE 'tech' = ANY(keywords);
๐งฐ Views
CREATE VIEW active_users AS SELECT name, email FROM users WHERE active = true; SELECT * FROM active_users; DROP VIEW active_users;
๐ Transactions
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- or ROLLBACK;
Atomic, safe, and drama-free.
๐งฉ Extensions
| Extension | Function |
|---|---|
postgis | GIS & mapping |
uuid-ossp | Generate UUIDs |
pg_stat_statements | Track slow queries |
citext | Case-insensitive text |
hstore | Key-value storage |
pgcrypto | Cryptographic functions |
Enable:
CREATE EXTENSION IF NOT EXISTS postgis;
๐ Window Functions
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) FROM employees;
| Function | Purpose |
|---|---|
RANK() | Rank with gaps |
DENSE_RANK() | Rank without gaps |
ROW_NUMBER() | Sequential numbering |
LAG() / LEAD() | Previous/next row value |
๐งฎ Common Table Expressions (CTEs)
WITH sales AS ( SELECT * FROM orders WHERE created_at > '2025-01-01' ) SELECT COUNT(*) FROM sales;
Recursive example:
WITH RECURSIVE countdown(n) AS ( SELECT 5 UNION ALL SELECT n-1 FROM countdown WHERE n > 1 ) SELECT * FROM countdown;
๐งพ Backup & Restore
Dump a Database
pg_dump dbname > backup.sql
Restore
psql dbname < backup.sql
Compressed Dump
pg_dump -Fc dbname > backup.dump pg_restore -d dbname backup.dump
๐ง Performance Tuning
| Setting | Description |
|---|---|
shared_buffers | Memory cache for data |
work_mem | Per query sort memory |
effective_cache_size | Estimated OS-level cache |
maintenance_work_mem | Used by vacuum/indexing |
max_connections | Limit concurrent sessions |
Analyze Query Performance
EXPLAIN ANALYZE SELECT * FROM big_table WHERE id=42;
Vacuum & Analyze
VACUUM; ANALYZE;
๐ Security
- Role-based access control
- SSL/TLS connections
- Row-Level Security (RLS)
Example
ALTER TABLE users ENABLE ROW LEVEL SECURITY; CREATE POLICY user_policy ON users FOR SELECT USING (id = current_user_id());
๐งฐ psql Shortcuts
| Command | Description |
|---|---|
\l | List databases |
\c dbname | Connect to database |
\dt | List tables |
\d table | Describe table |
\df | List functions |
\di | List indexes |
\du | List roles |
\timing | Show query time |
\x | Expanded view |
\! command | Run shell command |
\i file.sql | Run SQL file |
๐งญ Troubleshooting
| Problem | Fix |
|---|---|
| Can't connect | Check pg_hba.conf or firewall |
| Permission denied | GRANT ALL ON table TO user; |
| Database full | Check pg_stat_activity for idle connections |
| Query slow | Use EXPLAIN ANALYZE, create index |
| Locks | SELECT * FROM pg_locks; |
๐งฉ TL;DR Mind Map
| Area | Command / Tool | Description |
|---|---|---|
| Schema | CREATE TABLE | Define structure |
| Data | INSERT, UPDATE, DELETE | CRUD |
| Querying | SELECT, JOIN, WHERE | Fetch data |
| Admin | CREATE ROLE, GRANT | Manage users |
| Index | CREATE INDEX | Speed up queries |
| Backup | pg_dump, pg_restore | Data safety |
| Tuning | EXPLAIN ANALYZE | Performance |
| Extensions | CREATE EXTENSION | Add power |
| CLI | psql | Command-line interface |
Backlinks (3)
- General
- User
No backlinks yet.
- Redirects
No backlinks yet.
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'PostgreSQL/Cheat sheet' article โ
No comments yet. Be the first to comment!