4. Advanced CRUD: Handle Conflict & UPSERT
The Art of the Query
CRUD (Create, Read, Update, Delete) is the baseline. Professional backend engineering requires handling race conditions, bulk imports, and efficient data retrieval without making multiple network calls.
The UPSERT Pattern (ON CONFLICT)
In modern web development, you often have a Sync task: 'Add this user if they are new, but if they exist, update their last seen time.' Doing a SELECT then an INSERT/UPDATE is slow and prone to race conditions. Postgres handles this in one atomic operation.
INSERT INTO user_activity (email, last_seen) VALUES ('john@voidxhq.com', NOW()) ON CONFLICT (email) DO UPDATE SET last_seen = EXCLUDED.last_seen, visit_count = user_activity.visit_count + 1;
EXCLUDED keyword refers to the values you tried to insert that caused the conflict.Bulk Operations & COPY
Never run 1,000 individual INSERT statements in a loop. Every statement has overhead (network, logging, locks). Instead, use Multi-row Inserts or the COPY command for massive datasets.
-- Bulk Insert (Efficient) INSERT INTO logs (level, message) VALUES ('INFO', 'User logged in'), ('WARN', 'Slow query detected'), ('ERROR', 'DB connection lost');
The RETURNING Clause
When you insert a row, you usually need the auto-generated ID or the default timestamp for your frontend. Don't do a second SELECT. Use RETURNING.
INSERT INTO orders (user_id, total) VALUES (42, 199.99) RETURNING id, status, created_at; -- Returns these fields instantly!
Knowledge Check
Ready to test your understanding of 4. Advanced CRUD: Handle Conflict & UPSERT?