Every backend I have worked on eventually hit the same wall: a page that was fast in development becomes slow in production. When you dig in, the cause is almost never exotic. It is an N+1 query hidden inside a .map(), a find({}) with no limit, a case-insensitive $regex, or OFFSET pagination that gets slower with every page.
These problems are easy to spot once you know where they are, and easy to miss in code review. So I built querydig, an open-source, zero-config CLI that finds slow, N+1 and unoptimized database queries in your code before they reach production.
npx querydig
That's it. No account, no server, no config. Your code never leaves your machine.
What is querydig?
querydig is a static analysis tool for database queries. It parses your source code and flags query anti-patterns for MongoDB and SQL databases (Postgres, MySQL and others). Each finding comes with:
- a severity (critical / high / medium / low)
- the exact file, line and column
- why the query is slow
- how to fix it, often with the exact index to create
It works across JavaScript, TypeScript, Python, Go, Java, Ruby and PHP, and understands the ORMs and drivers people actually use:
| Database | Supported libraries |
|---|---|
| MongoDB | Mongoose, Node.js driver, PyMongo / Motor, mongo-go-driver, Java driver, Spring Data MongoDB, Mongoid, MongoDB PHP library |
| SQL | Prisma, TypeORM, Sequelize, pg / mysql2 / knex raw SQL, Django ORM, SQLAlchemy, GORM, database/sql, Spring Data JPA, Hibernate, JDBC, jOOQ, ActiveRecord, Sequel, Laravel Eloquent, Doctrine, PDO |
It is also fast. Parsing uses Tree-sitter (WASM) in a worker pool, so it scans about 2,000 files in under a second.
querydig requires Node.js 22.12 or later.
What a finding looks like
Here is real output from a Node.js + Mongoose project:
CRITICAL QD002 Nested query over another query's results (N² risk) [mongodb]
src/orders.service.ts:7:20
│ o.user = await User.findById(o.userId);
`User.findById()` is executed for every row of `orders`, which itself came from the database (loop at line 6).
fix: Collect the _id values first and run a single `User.find({ _id: { $in: values } })`, then match results in memory with a Map.
MEDIUM MQ005 sort() without limit() [mongodb]
src/search.ts:25:10
│ return User.find({ status }).sort({ createdAt: -1 }).lean();
fix: Add .limit(n) and an index matching filter + sort (ESR order), e.g. createIndex({ status: 1, createdAt: -1 }).
Summary
CRITICAL 6 HIGH 16 MEDIUM 7 LOW 12
Query health: F (0/100)
Each run also gives the project a query health score and grade, which makes it easy to track progress over time.
The N+1 query problem, and how querydig catches it
The N+1 problem is the most common database performance bug in web apps. You run one query to fetch a list, then one more query for each item in that list:
// ❌ 1 query for orders + N queries for users
const orders = await Order.find({ status: 'paid' });
for (const o of orders) {
o.user = await User.findById(o.userId);
}
With 10 orders this is fine. With 10,000 it is 10,001 round trips to the database. querydig flags this as QD002 (critical) because the inner query runs once per row of another query's results. The fix it suggests is to batch the lookup:
// ✅ 2 queries total
const orders = await Order.find({ status: 'paid' }).lean();
const users = await User.find({ _id: { $in: orders.map(o => o.userId) } }).lean();
const byId = new Map(users.map(u => [String(u._id), u]));
for (const o of orders) o.user = byId.get(String(o.userId));
The same detection works for ORMs that lazy-load relations. Accessing book.author.name inside a loop without select_related (Django), includes (Rails), with() (Laravel) or JOIN FETCH (JPA) is reported as QD004.
The rules
querydig ships with rules for general patterns, MongoDB and SQL. A few highlights:
Any database
- QD001: query inside a loop,
.mapor comprehension (N+1) - QD002: query per row of another query's results (N²)
- QD003: insert / update / delete inside a loop (use bulk APIs instead)
- QD004: lazy-loaded relation accessed in a loop
- QD005: a new
PrismaClient,MongoClient,PoolorSequelizecreated inside a request handler (a new connection pool per request)
MongoDB
- MQ001:
find({})with no limit (full collection scan) - MQ002: unanchored or case-insensitive
$regex - MQ003:
$where,$function,mapReduce - MQ004:
skip()pagination - MQ005:
sort()withoutlimit(), with an ESR index suggestion - MQ006:
$lookup/$unwind/$groupplaced before$match - MQ007: nested or many
populate()calls - MQ011: Mongoose reads without
.lean()
SQL
- SQ001:
findMany()/findAll()/objects.all()with no where or limit - SQ003:
LIKE '%term'(cannot use an index) - SQ004:
UPDATE/DELETEwithoutWHERE - SQ005:
OFFSETpagination - SQ006:
WHERE LOWER(col) = …(non-sargable) - SQ007:
ORDER BY RAND() - SQ008:
NOT IN (SELECT …)
Run npx querydig rules for the full list, or npx querydig explain QD001 to see why a rule matters with a before / after example.
Static analysis tools are only useful if they don't drown you in noise. querydig skips polling loops, batching loops that already paginate, array helpers like arr.find(x => …), and tests, fixtures, migrations and seeds by default.
Live mode: real evidence from your database
Static analysis tells you a pattern might be slow. Live mode tells you whether it actually is. Point querydig at a read-only MongoDB or Postgres replica:
QUERYDIG_DB_URI="postgres://reader:***@replica-host/shop" npx querydig
querydig then reads collection sizes, existing indexes and query plans, and adjusts the report:
- An N+1 whose inner query is a full scan of a large table is promoted to critical ("N × full scan of 4.2M docs") with the missing index.
- An unbounded read on a tiny lookup table is demoted to low.
- New live-only findings appear: COLLSCAN / Seq Scan on 10k+ rows, in-memory sorts, slow queries from the MongoDB profiler or
pg_stat_statements(traced back to the line of code), unused indexes, and Postgres foreign keys without an index.
Safety comes first. By default, queries are planned, never executed. Postgres statements run in a read-only transaction with a 5 second timeout, MongoDB reads use secondaryPreferred with maxTimeMS: 5000, and passwords are redacted from all output.
You can even generate a reviewed script of every missing index:
npx querydig --uri "$QUERYDIG_DB_URI" --emit-indexes
// orders: fixes LV001 src/orders.ts:5, LV003 src/orders.ts:5, QD002 src/report.ts:15
db.orders.createIndex({ status: 1, createdAt: -1 });
Safe auto-fix
Some fixes are mechanical and safe, so querydig can apply them for you:
npx querydig --fix --dry-run # preview
npx querydig --fix # apply, then review with git diff
Examples: adding .lean() to Mongoose reads that never call .save(), turning qs.count() > 0 into qs.exists() in Django, Model.all.each into find_each in Rails, and Model::all() into Model::lazy() in Laravel. querydig never rewrites N+1 loops or changes query results on its own. Those findings come with a fix for you (or your AI assistant) to apply.
Add it to CI with the GitHub Action
The best time to catch a slow query is in the pull request that introduces it:
name: querydig
on: [pull_request]
jobs:
querydig:
runs-on: ubuntu-latest
permissions: { contents: read, security-events: write, pull-requests: write }
steps:
- uses: actions/checkout@v7
- uses: milankatira/querydig@v0
with:
fail-on: high
On a pull request, the action scans only changed files, annotates the diff, posts a single PR comment that updates on every push, uploads SARIF to GitHub code scanning, and fails the build at your chosen severity.
Already have a big codebase with existing issues? Record a baseline so only new problems fail the build:
npx querydig --update-baseline
npx querydig --baseline .querydig-baseline.json --fail-on high
It also works in GitLab CI, pre-commit hooks, Husky and lefthook, and can output HTML, JSON, Markdown and SARIF reports.
ESLint plugin: see slow queries as you type
For JavaScript and TypeScript projects, querydig ships an ESLint plugin, so findings show up right in your editor:
// eslint.config.js (ESLint 9+)
import querydig from 'querydig/eslint';
export default [querydig.configs.recommended];
MCP server: let your AI assistant fix slow queries
querydig includes a Model Context Protocol (MCP) server, so Claude Code, Claude Desktop, Cursor, VS Code and other MCP clients can find slow queries, rewrite them and verify their own fixes:
claude mcp add querydig -- npx -y querydig mcp
The assistant gets tools like scan_queries, get_finding_context, analyze_snippet (check a rewrite before writing it to disk), apply_safe_fixes and suggest_indexes. The built-in optimize_queries prompt runs the whole loop: scan, apply safe fixes, rewrite the worst findings one by one, re-verify each with querydig, and summarize. querydig does the detection and verification; the assistant does the rewrite. No API key needed, and your code stays local.
How querydig compares
Runtime tools like Bullet (Rails) and nplusone (Django / SQLAlchemy) catch N+1 queries while your app or tests run, so they only see the code paths you exercise. querydig is static: it checks every code path at PR time, across six languages and 20+ ORMs, covers MongoDB as well as SQL, and can add live database evidence. The two approaches work well together.
Get started
npx querydig # scan the current directory
npx querydig --format html # self-contained, filterable HTML report
npx querydig --fail-on high # CI gate
npm i -D querydig # add to your project
- 📦 npm: npmjs.com/package/querydig
- 💻 GitHub: github.com/milankatira/querydig
- 📖 Docs: milankatira.github.io/querydig
querydig is MIT-licensed and open source. On the roadmap: live mode for MySQL, Kotlin and C# support, and a test-runner mode to confirm static findings at runtime. If it finds something slow in your codebase, I'd love to hear about it. Open an issue or star the repo on GitHub.

