What if you could update, add, and delete data all at once without mistakes?
Why CTE with INSERT, UPDATE, DELETE (writable CTEs) in PostgreSQL? - Purpose & Use Cases
Imagine you have a big spreadsheet where you need to update some rows, add new ones, and remove others all at once. Doing this by hand means flipping back and forth between sheets, copying data, and hoping you don't make mistakes.
Manually changing data like this is slow and risky. You might forget to update a related row or accidentally delete the wrong entry. It's hard to keep track of all changes and ensure everything stays consistent.
Writable CTEs let you group these changes together in one clear, organized command. You can insert, update, and delete rows step-by-step inside a single query, making your work faster and safer.
UPDATE users SET active = false WHERE last_login < '2023-01-01'; INSERT INTO users (name) VALUES ('New User'); DELETE FROM users WHERE banned = true;
WITH updated AS ( UPDATE users SET active = false WHERE last_login < '2023-01-01' RETURNING * ), inserted AS ( INSERT INTO users (name) VALUES ('New User') RETURNING * ), deleted AS ( DELETE FROM users WHERE banned = true RETURNING * ) SELECT * FROM updated UNION ALL SELECT * FROM inserted UNION ALL SELECT * FROM deleted;
This lets you perform multiple data changes in one smooth, reliable step, keeping your database clean and consistent.
A company cleaning up its customer database can deactivate old accounts, add new sign-ups, and remove banned users all in one go without juggling multiple commands.
Manual data changes are slow and error-prone.
Writable CTEs group insert, update, and delete in one query.
This makes database updates safer, clearer, and faster.