I just ran across this rather powerful PostgreSQL example statement from the manual. It reads
Increment the sales count of the salesperson who manages the account for Acme Corporation, and record the whole updated row along with current time in a log table:
WITH upd AS ( UPDATE employees SET sales_count = sales_count + 1 WHERE id = ( SELECT sales_person FROM accounts WHERE name = 'Acme Corporation' ) RETURNING * ) INSERT INTO employees_log SELECT *, current_timestamp FROM upd;
This database keeps amazing me. A single statement allows for updating one table, taking the updated record(s) including all generated values as input for an insert into another table. But at the same time, PostgreSQL does not yet implement the SQL:2003 MERGE statement.
Crazy database…
Filed under: sql Tagged: Common Table Expression, cte, MERGE, PostgreSQL, sql, WITH clause Image may be NSFW.
Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.
