---
name: executing-batch-operations
description: Safely execute operations affecting multiple records with dry-run, sample, execute, verify workflow. Use for database migrations, bulk updates/deletes, data transformations, any operation on more than 10 records. Triggers on "batch", "bulk", "migrate", "update all", "delete multiple", "mass update".
license: MIT
title: executing-batch-operations
canonical_url: https://skilld.dev/gh/ayushjj/skills/executing-batch-operations
last_updated: 2026-10-26T13:15:43.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [scripts/batch-template.ts](https://skilld.dev/api/skills-raw/ayushjj/skills/executing-batch-operations/scripts/batch-template.ts).
>
> If the user asked to install this Skill, run `npx skilld install ayushjj/skills/executing-batch-operations`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/executing-batch-operations`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/ayushjj/skills/executing-batch-operations) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/executing-batch-operations`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/executing-batch-operations --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/executing-batch-operations --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Executing Batch Operations

Use this skill for ANY operation affecting multiple records. Prevents catastrophic data loss.

## Before You Start

- The operation affects more than 10 records.
- You have a spec, or a clear understanding of what needs to change.
- A database backup exists or can be created.

The commands below use `pnpm tsx` to run a TypeScript script. Substitute your project's own script runner (`npx tsx`, `bun`, `python`, a Rails runner, and so on).

## The Golden Rule

**Dry-run -> Sample Review -> Execute -> Verify**

Never skip steps. Every step exists because of past pain.

<critical_sequence enforce_order="strict">

<step number="1" required="true" blocking="true">
## Step 1: Create Dry-Run Script

Add a `--dry-run` flag that:
- Shows what WOULD change without changing it
- Outputs affected record IDs
- Counts total affected records

For a full template with dry-run, rollback, and confirmation, read `scripts/batch-template.ts`.

<validation_gate name="dry-run-implemented" blocking="true">
**BLOCK if not implemented:**
- [ ] Script has --dry-run flag
- [ ] Dry-run shows count of affected records
- [ ] Dry-run shows sample of affected IDs
- [ ] Dry-run makes NO changes to data

Do NOT proceed until dry-run works correctly.
</validation_gate>
</step>

<step number="2" required="true" depends_on="1" blocking="true">
## Step 2: Dry-Run on a Sample

```bash
pnpm tsx scripts/batch-operation.ts --dry-run --limit 10
```

Use 10% of the records or 10, whichever is smaller.

Review output manually:
- Are the right records selected?
- Is the transformation correct?
- Any unexpected cases?

<validation_gate name="sample-reviewed" blocking="true">
**BLOCK if sample not reviewed:**
- [ ] Ran with --limit flag (10% or 10 records, whichever smaller)
- [ ] Manually reviewed each record in output
- [ ] Confirmed transformation logic is correct
- [ ] No unexpected records included

Do NOT proceed to full dry-run until sample looks correct.
</validation_gate>
</step>

<step number="3" required="true" depends_on="2" blocking="true">
## Step 3: Full Dry-Run

```bash
pnpm tsx scripts/batch-operation.ts --dry-run > dry-run-output.txt
```

Review the full output:
- Total count matches expectation?
- Edge cases handled?
- No unexpected records included?

<validation_gate name="full-dry-run-reviewed" blocking="true">
**BLOCK if not reviewed:**
- [ ] Full dry-run output saved to file
- [ ] Total count matches expectation
- [ ] Spot-checked random records in output
- [ ] Edge cases verified

Save this file - you'll need it for audit.
</validation_gate>
</step>

<step number="4" required="true" depends_on="3" blocking="true">
## Step 4: Create Rollback File

Before execution, save current state (see `scripts/batch-template.ts` for rollback pattern).

<validation_gate name="rollback-created" blocking="true">
**BLOCK if not created:**
- [ ] Rollback file exists with original values
- [ ] File is named with date for identification
- [ ] Rollback restore script ready (if needed)

You WILL need this rollback file. Create it.
</validation_gate>
</step>

<step number="5" required="true" depends_on="4" blocking="true">
## Step 5: Execute with Confirmation

```bash
pnpm tsx scripts/batch-operation.ts
```

Script must have confirmation prompt (see `scripts/batch-template.ts` for pattern).

<validation_gate name="execution-confirmed" blocking="true">
**BLOCK if not ready:**
- [ ] Confirmation prompt exists in script
- [ ] User has typed 'yes' to proceed
- [ ] Execution is logged for audit

This is the point of no return. Confirm everything is ready.
</validation_gate>
</step>

<step number="6" required="true" depends_on="5" blocking="true">
## Step 6: Verify with Audit Query

After execution, run verification immediately. Six check classes:

```sql
-- 1. Record count (compare before/after against dry-run expectation)
SELECT COUNT(*) FROM table WHERE condition;

-- 2. Orphans (references pointing at nothing)
SELECT * FROM child WHERE parent_id IS NOT NULL
  AND parent_id NOT IN (SELECT id FROM parent);

-- 3. Duplicates on unique fields
SELECT field, COUNT(*) FROM table GROUP BY field HAVING COUNT(*) > 1;

-- 4. Timestamp consistency (future dates, inverted pairs)
SELECT * FROM table WHERE created_at > NOW() OR updated_at < created_at;

-- 5. FK integrity: repeat check 2 for EVERY relation the operation touched

-- 6. Business-rule compliance: assert the operation's domain invariants
--    (legal status transitions, required-field combinations) — define per project
```

<validation_gate name="audit-passed" blocking="true">
**BLOCK if audit fails:**
- [ ] Record count matches expected
- [ ] No orphaned records created
- [ ] No duplicate records created
- [ ] Timestamps consistent (no future/inverted)
- [ ] FK integrity holds on every touched relation
- [ ] Business-rule invariants hold
- [ ] Spot-check shows correct values

If ANY check fails, STOP and investigate before proceeding.
</validation_gate>

### Query-correctness validation (when the operation changes search/query behavior)

The audit above proves *integrity*, not *correctness of results*. If the operation changes what a search/query/matching path returns:

1. Define expected behavior BEFORE running: expected count range, must-include cases, must-exclude cases
2. Run the query on real data; save results to a file
3. Classify each result correct/incorrect against the expectations
4. Compute precision (of returned, % correct) and recall (of expected, % returned)
5. Write a short report: query, counts, precision/recall, misclassified examples

Verify with real queries on real data: manual spot-checks check the experience, not correctness.
</step>

<step number="7" required="true" depends_on="6">
## Step 7: Document Results

Update `implementation.md` or create new documentation:

```markdown
## Batch Operation: {name}
- Date: {date}
- Records affected: {count}
- Dry-run file: dry-run-output.txt
- Rollback file: rollback-{operation}-{date}.json
- Verification: [PASSED/FAILED]
```
</step>

</critical_sequence>

## Safety Checklist

Before executing any batch operation:

- [ ] Dry-run flag implemented
- [ ] Sample (10%) reviewed manually
- [ ] Full dry-run output saved
- [ ] Rollback file created
- [ ] Confirmation prompt added
- [ ] Audit queries written
- [ ] Results documented

<success_criteria>
## Batch Operation Complete When ALL Are True

- [ ] Dry-run completed and reviewed
- [ ] Rollback file exists
- [ ] Execution confirmed by user
- [ ] Audit queries all pass
- [ ] Results documented
- [ ] No orphans or duplicates created
</success_criteria>

<decision_gate wait_for_user="true">
## Batch Operation Complete

Affected records: [count]
Audit status: [PASSED/FAILED]

What's next?
1. Re-run the Step 6 audit taxonomy as a full-table health check (recommended)
2. Proceed to next step in implementation
3. Rollback changes (if issues found)
4. Write down what you learned
5. Other

Choose (1-5): _
</decision_gate>

## Anti-Patterns

- Running batch operations in production without dry-run
- Skipping sample review "because it's simple"
- No rollback file (you WILL need it)
- Verification after, not during (catch issues early)
- Not saving dry-run output (needed for audit)

<integration_protocol>
## Integration Points

**Invoked by:**
- `/creating-specifications` skill (when implementation involves bulk changes)
- Manual invocation for data migrations
- Auto-suggested when user mentions bulk operations

**Invokes:**
- Nothing external — Step 6's audit taxonomy and query-correctness validation are part of this skill

**Handoff expectations:**
Creates rollback file and dry-run output.
Step 6 audit uses these to verify integrity.
</integration_protocol>
