/sql:sql-data-modificationfrom sql
Guides the core write statements — INSERT, UPDATE, DELETE — as set-based operations the database serializes, not row-by-row loops. Teaches the INSERT forms (single-row VALUES, multi-row VALUES in ONE statement, INSERT ... SELECT for bulk copy, DEFAULT VALUES) and bans the nightly job that fires 100k single-row INSERTs instead of one. Centers the
Ships in sql. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
"If the
WHEREclause is absent, the effect is to delete all rows in the table. The result is a valid, but empty table." — PostgreSQL — DELETE
"Use of
RETURNINGavoids performing an extra database query to collect the data, and is especially valuable when it would otherwise be difficult to identify the modified rows reliably." — PostgreSQL — Returning Data From Modified Rows
DML is where a query stops being a question and becomes a change to durable state. Two ideas govern everything below. First, every write is set-based: INSERT, UPDATE, and DELETE each operate on a whole set of rows in one statement the engine optimizes and a transaction wraps — not a loop the application drives one row at a time. Second, the scope of a write is decided entirely by its predicate, and a missing predicate means "everything." This skill assumes the set semantics and three-valued logic of sql-relational-and-null-discipline (a WHERE keeps only rows that evaluate to TRUE — which is exactly why a NULL-laden predicate can quietly modify the wrong rows), and it hands upsert / insert-or-update to sql-merge-and-upsert.
INSERT has three set-based forms. The multi-row VALUES form inserts many rows in a single statement — the grammar is VALUES ( ... ) [, ...], the trailing [, ...] meaning "repeat the row" (PostgreSQL — INSERT). SQLite agrees: the VALUES form "creates one or more new rows in an existing table" (SQLite — INSERT).
-- RIGHT — single row
INSERT INTO films (code, title, kind) VALUES ('UA502', 'Bananas', 'Comedy');
-- RIGHT — MANY rows in ONE statement (one round trip, one transaction)
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
-- RIGHT — bulk copy from a query: the engine does the loop, set-based
INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';
-- RIGHT — a row of all defaults
INSERT INTO films DEFAULT VALUES;
DEFAULT is usable per value, and DEFAULT VALUES fills "all columns ... with their default values" (PostgreSQL — INSERT). The anti-pattern is driving inserts from application code one row at a time:
# WRONG — N statements, N round trips, N transactions (unless wrapped); slow
for f in films:
db.execute("INSERT INTO films (code, title) VALUES (?, ?)", [f.code, f.title])
A thousand single-row INSERTs is a thousand network round trips and (without an explicit transaction) a thousand commits. One multi-row VALUES or INSERT ... SELECT collapses that to one. Batch the rows; let the database do the loop.
WHERE — UPDATE/DELETE Without a Predicate Hits Every Row (the centerpiece)This is the single most destructive mistake in DML, and it never errors. UPDATE "changes the values of the specified columns in all rows that satisfy the condition" (PostgreSQL — UPDATE) — and with no condition, every row satisfies. SQLite says it outright: "If the UPDATE statement does not have a WHERE clause, all rows in the table are modified" (SQLite — UPDATE). DELETE is worse: "If the WHERE clause is absent, the effect is to delete all rows in the table" (PostgreSQL — DELETE).
-- WRONG — no WHERE: rewrites EVERY row in the table. Valid SQL. No error. No undo outside a tx.
UPDATE users SET status = 'inactive';
-- WRONG — no WHERE: empties the entire table.
DELETE FROM users;
The instinct that saves you is to treat every UPDATE/DELETE as a three-step ritual: wrap it in an explicit transaction, SELECT the rows the predicate matches first, then run the write and verify the affected-row count before COMMIT.
-- RIGHT — verify scope before you commit to it
BEGIN;
-- 1. See exactly which rows the predicate selects (and how many).
SELECT id, status FROM users WHERE last_login < '2024-01-01';
-- 2. Run the write with the SAME predicate; check the reported row count is what you expected.
UPDATE users SET status = 'inactive' WHERE last_login < '2024-01-01';
-- 3. Wrong count or wrong rows? ROLLBACK. Right? COMMIT.
COMMIT; -- or ROLLBACK;
The SELECT-first step turns the predicate into something you can read before it's something you can't take back. The transaction makes a mistake reversible: an un-COMMIT-ted UPDATE/DELETE rolls back cleanly. Outside a transaction, on autocommit, the wipe is durable the instant the statement returns. Why the transaction is safe (isolation, locking, MVCC) is owned by sql-transactions-and-isolation.
UPDATE ... FROM / DELETE ... USINGUpdating or deleting based on another table tempts you toward a join. Both PostgreSQL and SQLite offer one — UPDATE ... FROM — but it is a vendor extension, not standard SQL. PostgreSQL is explicit: "the FROM and RETURNING clauses are PostgreSQL extensions" (PostgreSQL — UPDATE). SQLite warns the construct "is not part of the SQL standards, each product implements UPDATE-FROM differently" (SQLite — UPDATE). DELETE ... USING is the same story — PostgreSQL flatly states "This syntax is not standard" (PostgreSQL — DELETE).
-- NON-STANDARD (PG/SQLite) — convenient, but syntax varies per engine
UPDATE inventory SET qty = qty - s.amt
FROM sales s WHERE inventory.item_id = s.item_id;
DELETE FROM films USING producers
WHERE producer_id = producers.id AND producers.name = 'foo';
The portable form is a correlated subquery in SET plus a WHERE EXISTS guard. PostgreSQL itself recommends it: "referencing other tables only within sub-selects is safer" (PostgreSQL — UPDATE), and calls the subquery DELETE "a more standard way" (PostgreSQL — DELETE).
-- RIGHT (portable) — correlated subquery sets the value; EXISTS limits which rows are touched
UPDATE inventory
SET qty = qty - (SELECT s.amt FROM sales s WHERE s.item_id = inventory.item_id)
WHERE EXISTS (SELECT 1 FROM sales s WHERE s.item_id = inventory.item_id);
-- RIGHT (portable) — anti-join delete via a subquery, no USING
DELETE FROM films
WHERE producer_id IN (SELECT id FROM producers WHERE name = 'foo');
The WHERE EXISTS is not optional: without it, rows with no matching subquery row get SET col = (SELECT ... ) = NULL (an empty scalar subquery is NULL — see sql-relational-and-null-discipline), silently nulling rows you meant to leave alone.
After an INSERT, you usually need the generated id. The naive path is a second statement (SELECT ... WHERE ...) — an extra round trip and a race, because identifying "the row I just inserted" reliably is itself hard under concurrency. RETURNING solves both: it "avoids performing an extra database query to collect the data, and is especially valuable when it would otherwise be difficult to identify the modified rows reliably" (PostgreSQL — RETURNING).
-- WRONG — extra round trip, and "the new id" is racy to re-identify under concurrency
INSERT INTO users (firstname, lastname) VALUES ('Joe', 'Cool');
SELECT id FROM users WHERE firstname = 'Joe' AND lastname = 'Cool'; -- which Joe Cool?
-- RIGHT — one statement returns the server-generated key
INSERT INTO users (firstname, lastname) VALUES ('Joe', 'Cool') RETURNING id;
RETURNING works on UPDATE and DELETE too, returning a row per affected row — handy for logging what a bulk write actually changed. SQL:2023 standardized a richer form returning both the OLD and NEW content of each modified row; PostgreSQL exposes it as old./new. (PostgreSQL — RETURNING):
-- RIGHT — capture before/after in one statement (SQL:2023 old/new)
UPDATE products SET price = price * 1.10 WHERE price <= 99.99
RETURNING name, old.price AS old_price, new.price AS new_price;
RETURNING is "not standard SQL ... modelled after PostgreSQL" (SQLite — RETURNING) but is widely available (§6). For INSERT ... ON CONFLICT and other upsert spellings, route to sql-merge-and-upsert — that skill owns insert-or-update; this one owns the plain write.
To remove all rows, DELETE FROM t works but scans and logs every row. TRUNCATE "provides a faster mechanism to remove all rows from a table" (PostgreSQL — DELETE) — it deallocates storage instead of deleting row-by-row, and typically resets identity/auto-increment counters. The catch is transactional behavior:
-- DELETE — row-by-row, fully transactional everywhere, fires row triggers, keeps identity counter
DELETE FROM staging_events;
-- TRUNCATE — fast bulk empty; resets identity; transactional on PostgreSQL,
-- but AUTO-COMMITS (cannot roll back) on MySQL and Oracle
TRUNCATE TABLE staging_events;
Reach for TRUNCATE to reset a scratch/staging table; reach for DELETE ... WHERE for any partial removal (TRUNCATE takes no predicate). The transactional divergence is the trap — on PostgreSQL a TRUNCATE inside BEGIN ... ROLLBACK is undone; on MySQL and Oracle it commits immediately and is irreversible. Per-engine specifics route to sql-standard-vs-dialect-map.
| Feature | PostgreSQL | SQLite | MySQL / MariaDB | Oracle |
|---|---|---|---|---|
Multi-row VALUES, INSERT ... SELECT | yes | yes | yes | INSERT ALL / ... SELECT |
RETURNING | yes | 3.35+ | MariaDB yes / MySQL no | yes |
UPDATE ... FROM (join-update) | yes | 3.33+ | different syntax | no — use subquery |
DELETE ... USING (join-delete) | yes | use subquery | different syntax | no — use subquery |
TRUNCATE rolls back in a transaction | yes | no TRUNCATE (use DELETE) | no — auto-commits | no — auto-commits |
The set-based core — multi-row VALUES, INSERT ... SELECT, UPDATE/DELETE with a WHERE, and the correlated-subquery join-update — is portable everywhere. The conveniences are not: RETURNING is absent in MySQL (use LAST_INSERT_ID() there), UPDATE...FROM/DELETE...USING spell differently per engine, and TRUNCATE is non-transactional on MySQL/Oracle. Keep the non-portable spellings behind one well-named function and route dialect detail to sql-standard-vs-dialect-map.
A DML mistake is durable — it changes state, and someone inherits the damage:
UPDATE accounts SET balance = 0 in a prod console, highlighted everything except the WHERE line, and hit execute — rewriting every row in the table. There was no error and no transaction; the rollback they didn't open is the restore-from-backup they now need (§2).INSERTs — 100k round trips — instead of one multi-row VALUES or INSERT ... SELECT that finishes in seconds (§1).INSERT then SELECT ... WHERE email = ? to get the id, and under concurrency occasionally returns another request's row — a bug RETURNING id would have made impossible (§4).UPDATE ... FROM to a new engine and got a syntax error, or worse, silently different rows — because the join-update they relied on was never standard (§3).The WHERE you checked, the transaction you opened, the multi-row VALUES you batched, and the RETURNING you reached for are all gifts to whoever runs this against production.
sql-relational-and-null-discipline — foundation: set semantics, and why a WHERE keeps only TRUE rows (so a NULL in an UPDATE/DELETE predicate silently changes the matched set).sql-merge-and-upsert — insert-or-update / INSERT ... ON CONFLICT / MERGE: the atomic upsert this skill deliberately does not duplicate.sql-transactions-and-isolation — why wrapping a write in BEGIN ... COMMIT makes it reversible and safe under concurrency (§2), and the autocommit trap.sql-constraints-and-integrity — what a write must satisfy: NOT NULL, CHECK, UNIQUE, and foreign-key cascade on DELETE/UPDATE.sql-standard-vs-dialect-map — dialect spellings of RETURNING, UPDATE...FROM/DELETE...USING, and TRUNCATE's per-engine transactional behavior (§3, §5, §6).High-frequency DML anti-patterns in LLM-generated SQL, each with wrong/right code and a primary-source citation:
Source provenance for every claim in this skill:
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ctoth/sql-skills-plugin --plugin sql32 skills in this plugin
/sql-aggregation-and-groupingGuides aggregation correctness — every column in the SELECT list of a grouped query must be either named in GROUP BY or wrapped in an aggregate (the functional-dependency rule), because a non-grouped, non-aggregated column has no single value per group. Bans the "ambiguous groups" antipattern that errors on standard-conformant engines but silently returns an arbitrary row's value on MySQL with ONLY_FULL_GROUP_BY disabled. Auto-invokes when writing or editing GROUP BY/HAVING, aggregate functions (SUM/COUNT/AVG/MIN/MAX), FILTER, LISTAGG/STRING_AGG/GROUP_CONCAT/ARRAY_AGG, ROLLUP/CUBE/GROUPING SETS, percentile/WITHIN GROUP, or any multi-level subtotal report, and on "only_full_group_by" / "must appear in the GROUP BY clause" / "subtotal" / "rollup" requests./sql-constraints-and-integrityGuides database-enforced data integrity — push the rules into the schema as declarative constraints rather than re-checking them in every application that writes. Covers PRIMARY KEY (= UNIQUE + NOT NULL, one per table) vs UNIQUE (many per table, and by default permits multiple NULLs — the SQL:2023 NULLS NOT DISTINCT lever fixes the duplicate-"unique"-emails trap), CHECK constraints and the pitfall that a CHECK passes when it evaluates to UNKNOWN/NULL (so pair it with NOT NULL), NOT. Auto-invokes when writing or editing CREATE TABLE/ALTER TABLE constraints, FOREIGN KEY/REFERENCES, CHECK/UNIQUE/NOT NULL/DEFAULT, or on "enforce this in the DB or the app" / "why are there orphaned rows" / "why did duplicate emails get in" decisions./sql-cte-and-recursionGuides common table expressions for readable query decomposition (`WITH`) and `WITH RECURSIVE` for hierarchies, transitive closure, and series generation — always with a termination or cycle guard so recursion cannot run away. Auto-invokes when writing or editing `WITH`/`WITH RECURSIVE`, hierarchy/tree/graph traversal, transitive-closure or generate-series logic, deeply nested subqueries that want flattening, or on "infinite recursion" / "query runs forever" / "tree query" / "recursive query" requests./sql-data-types-and-numericsGuides standard-SQL type selection so the storage matches the data's meaning — exact `NUMERIC`/`DECIMAL(p,s)` for money and counts (never `FLOAT`/`REAL`/`DOUBLE`, whose binary floating point cannot store 0.1 exactly and whose rounding error compounds when summed), `SMALLINT`/`INTEGER`/`BIGINT` chosen by the value range (the `INTEGER` ceiling is +2,147,483,647), `CHARACTER VARYING` sized to a real domain limit instead of a cargo-culted `VARCHAR(255)`, fixed-width `CHARACTER(n)` only for. Auto-invokes when writing or editing column type declarations, `CREATE TABLE`/`ALTER TABLE` type choices, `CAST` targets, money/currency/price fields, high-precision or large-range numbers, identifier/key column widths, or string-length and boolean columns. Routes dialect spellings (BIT, TINYINT(1), bytea) to sql-standard-vs-dialect-map./sql-datetime-and-intervalsGuides standard temporal handling in SQL — the temporal types (DATE, TIME, TIMESTAMP, and crucially TIMESTAMP WITH TIME ZONE), typed literals (DATE '...', TIMESTAMP '...', INTERVAL '...'), EXTRACT, the standard CURRENT_DATE/CURRENT_TIMESTAMP keywords, and INTERVAL arithmetic — instead of jamming dates into strings or reaching for vendor functions (NOW()/GETDATE()/SYSDATE, DATEADD/DATEDIFF, STRFTIME). Auto-invokes when writing or editing date/time columns or literals, EXTRACT, INTERVAL arithmetic, time-zone-sensitive comparisons, date truncation/bucketing, or age/duration calculations, and on "store a timestamp", "add a day/month", "why is my time off by an hour", or "yesterday's rows" requests./sql-explain-and-set-based-thinkingGuides the two performance habits that matter most — think in sets, not rows, and measure the plan instead of guessing. Replaces the N+1 / RBAR ("row-by-agonizing-row") antipattern — application code looping to issue one query per row, or a correlated per-row subquery — with a single set-based query (`JOIN`/`IN`/`VALUES`/`LATERAL`). Auto-invokes when writing or editing per-row query loops in application code, a correlated per-row subquery, `EXPLAIN`/`EXPLAIN QUERY PLAN` output, or on "why is this slow" / "optimize this query" / "N+1" requests. Routes plan reading and set-thinking for the whole plugin.Other plugins' skills for the same job