Full answer
A CTE in front of a data change keeps the logic readable, for example "give a 5 percent raise to everyone below their department's average".
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT);
CREATE TABLE orders_archive (id INTEGER PRIMARY KEY, status TEXT);
INSERT INTO orders VALUES (1,'shipped'),(2,'cancelled'),(3,'cancelled');sql
WITH dept_avg AS (
SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id
)
UPDATE employees
SET salary = CAST(salary * 1.05 AS INTEGER)
WHERE salary < (SELECT avg_sal FROM dept_avg WHERE dept_avg.dept_id = employees.dept_id);
SELECT name, salary FROM employees ORDER BY id;| name | salary |
|---|---|
| Asha | 120000 |
| Ravi | 99750 |
| Mei | 99750 |
| Tom | 70000 |
| Sara | 65100 |
| Diego | 55000 |
| Lena | NULL |
| Omar | 50400 |
The CTE computes the averages, and the UPDATE uses them. Ravi, Mei, Sara and Omar were below their department averages and got the raise.
PostgreSQL goes further: the CTE itself can change data, and RETURNING passes the changed rows on. This archives and deletes cancelled orders in one statement:
sql
WITH moved AS (
DELETE FROM orders WHERE status = 'cancelled' RETURNING id, status
)
INSERT INTO orders_archive SELECT id, status FROM moved;
SELECT (SELECT COUNT(*) FROM orders) AS left_in_orders,
(SELECT COUNT(*) FROM orders_archive) AS archived;| left_in_orders | archived |
|---|---|
| 1 | 2 |
SQLite does not accept a DELETE inside a WITH clause:
sql
WITH moved AS (DELETE FROM orders WHERE status = 'cancelled' RETURNING id)
SELECT * FROM moved;
-- error on purposetext
Error: near "DELETE": syntax errorIn SQLite, the same job takes two statements in one transaction: INSERT INTO the archive with a SELECT, then DELETE.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT);
CREATE TABLE orders_archive (id INTEGER PRIMARY KEY, status TEXT);
INSERT INTO orders VALUES (1,'shipped'),(2,'cancelled'),(3,'cancelled');
WITH dept_avg AS (
SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id
)
UPDATE employees
SET salary = CAST(salary * 1.05 AS INTEGER)
WHERE salary < (SELECT avg_sal FROM dept_avg WHERE dept_avg.dept_id = employees.dept_id);
SELECT name, salary FROM employees ORDER BY id;
-- error on purpose
WITH moved AS (DELETE FROM orders WHERE status = 'cancelled' RETURNING id)
SELECT * FROM moved;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- WITH can precede INSERT, UPDATE and DELETE
- The CTE supplies a named intermediate result to the change
- PostgreSQL allows DML inside CTEs with RETURNING
- SQLite needs separate statements in a transaction for the same effect
Common mistakes
- Computing averages after some rows have already been updated, in a multi-step script
- Assuming DML-in-CTE syntax works on SQLite
Follow-ups
- How would you preview which rows the UPDATE will change?
- Why is the data-modifying CTE in PostgreSQL atomic?
Tips
- Preview the affected rows with the same CTE and a SELECT before running the UPDATE