Production-focused offline SQL static analyzer.
Catch security vulnerabilities, performance regressions, reliability issues, compliance risks, cost inefficiencies, and code quality problems before they reach production.
Offline-First Analysis. Catch bugs without ever connecting to a live database. SlowQL works entirely on SQL source files, making it safe to run anywhere.
Custom Rule Engine. Define your own organizational SQL conventions via YAML rules or Python plugins. Custom rules integrate seamlessly with the built-in catalog and support full reporting and suppression.
282 Built-in Rules. Covers security, performance, reliability, compliance, cost, and quality. Each rule includes impact documentation, fix guidance, and severity classification.
Dead SQL Detection. Safely identify unused database objects and redundant code. SlowQL detects unused views, stored procedures, and functions by analyzing definitions and usages across your entire project. It also flags unreachable code paths in procedures (e.g., after RETURN) and near-duplicate queries that should be consolidated.
Cross-File SQL Analysis. Detect breaking changes across multiple files. SlowQL understands relationships between DDL, views, and procedures, flagging when a schema change in one file (e.g., DROP COLUMN) breaks a query in another.
dbt & Jinja Support. Natively parses dbt models and SQL templates containing Jinja tags ({{ ref() }}, {% if %}, {% for %}). Enforces dbt best practices including missing references and hardcoded schema detection.
Migration Framework Support. Natively supports Alembic, Django migrations, Flyway, Liquibase, Prisma Migrate, and Knex. SlowQL understands the ordering, dependencies, and context of migration files to catch destructive changes before they break your existing queries.
14 SQL Dialects. Dialect-aware analysis for PostgreSQL, MySQL, SQL Server (T-SQL), Oracle, SQLite, Snowflake, BigQuery, Redshift, ClickHouse, DuckDB, Presto, Trino, Spark, and Databricks. Universal rules fire on all dialects; dialect-specific rules only fire when relevant.
Schema-Aware Validation. Optionally validate against your DDL files to catch missing tables, columns, and suggest indexes.
Safe Autofix. Conservative, exact-text-replacement fixes with FixConfidence.SAFE. No guessing, no heuristic rewrites. Preview with --diff, apply with --fix.
CI/CD Native. GitHub Actions, SARIF, pre-commit hooks, JSON/HTML/CSV exports. Exit codes based on severity thresholds.
Editor Integration. VS Code extension via slowql-vscode and foundational LSP server for other editors.
Application Code SQL Extraction. Automatically extract and analyze SQL strings embedded in Python, TypeScript/JavaScript, Java, Go, Ruby, and MyBatis XML mapper files. SlowQL uses languageβspecific heuristics (AST for Python, regex for others) and a dedicated MyBatis XML parser to find SQL, flagging potential injection risks in dynamic constructions. It distinguishes safe #{param} parameterization from unsafe ${param} interpolation and marks queries using dynamic MyBatis tags (<if>, <where>, <set>, etc.) as dynamic.
pipx install slowqlpip install slowqldocker run --rm -v $(pwd):/src makroumi/slowql /src/queries.sqlRequirements: Python 3.11+, Linux / macOS / Windows.
slowql queries.sqlAnalyze application code (extracts SQL strings automatically):
slowql src/app.py src/services/Analyze with schema validation:
slowql queries.sql --schema schema.sqlRun in CI mode with failure thresholds:
slowql init --dialect postgresql --fail-on high
slowql src/ --fail-on highslowql src/main/resources/mapper/UserMapper.xml
slowql src/main/resources/mapper/ --schema db/schema.sqlPreview and apply safe fixes:
slowql queries.sql --diff
slowql queries.sql --fix --fix-report fix-report.jsonList all built-in rules dynamically or get detailed documentation for a specific rule:
slowql --list-rules
slowql --explain PERF-SCAN-001Integrate SlowQL directly into your Python scripts with three lines of code:
import slowql
result = slowql.analyze("SELECT * FROM users")SlowQL performs optional schema-aware validation by inspecting your DDL files. This catches structural issues that generic static analysis misses.
Tables and Columns. Detect references to non-existent tables or columns.
Index Suggestions. Identify filtered columns that lack corresponding indexes.
slowql queries.sql --schema database/schema.sql
slowql migrations/ --schema schema.sql --fail-on criticalSchema findings:
| Rule | Description |
|---|---|
SCHEMA-TBL-001 |
Table referenced but not defined in schema |
SCHEMA-COL-001 |
Column referenced but not present in table definition |
SCHEMA-IDX-001 |
Missing index suggested for filtered column |
SlowQL ships with 282 rules across six dimensions:
| Dimension | Focus | Rules |
|---|---|---|
| Security | SQL injection, privilege escalation, credential exposure, SSRF | 61 |
| Performance | Full scans, indexing, joins, locking, sorting, pagination | 73 |
| Reliability | Data loss prevention, transactions, race conditions, idempotency | 44 |
| Quality | Naming, complexity, null handling, style, dbt, dead SQL | 51 |
| Cost | Cloud warehouse optimization, storage, compute, network | 33 |
| Compliance | GDPR, HIPAA, PCI-DSS, SOX, CCPA | 18 |
MyBatis is a popular Java/Spring ORM framework that uses XML mapper files to define SQL statements. SlowQL now parses these mapper files and applies all existing SQL rules.
<select>,<insert>,<update>,<delete>,<sql>- Dynamic tags:
<if>,<where>,<set>,<foreach>,<choose>,<when>,<otherwise>,<trim>
- Safe:
#{param}β uses preparedβstatement style parameterization. - Unsafe:
${param}β direct string interpolation, flagged as potential SQL injection.
Queries containing any dynamic tags are marked is_dynamic = True and are analyzed for injection and performance issues.
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.example.UserMapper">
<!-- Safe -->
<select id="findUserById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
<!-- Unsafe -->
<select id="searchUsers" resultType="User">
SELECT * FROM users WHERE name LIKE ${searchTerm}
</select>
<!-- Dynamic -->
<update id="updateUser">
UPDATE users
<set>
<if test="name != null">name = #{name},</if>
<if test="email != null">email = #{email},</if>
</set>
WHERE id = #{id}
</update>
</mapper>SlowQL will extract three statements, flag SELECT * (PERFβSCANβ001), flag unsafe ${} (SECβINJβ001), and mark the update as dynamic.
SECβINJβ001β¦SECβINJβ011β injection patterns.PERFβSCANβ001βSELECT *.QUALβDBTβ001β hardβcoded table names.
107 rules are dialect-aware, firing only on the relevant database engine:
| Dialect | Specific Rules | Examples |
|---|---|---|
| PostgreSQL | 12 | pg_sleep detection, SECURITY DEFINER without search_path, CREATE INDEX without CONCURRENTLY |
| MySQL | 15 | LOAD DATA LOCAL INFILE, utf8 vs utf8mb4, ORDER BY RAND(), MyISAM detection |
| T-SQL (SQL Server) | 23 | OPENROWSET, sp_OACreate, @@IDENTITY, MERGE without HOLDLOCK, SET NOCOUNT ON |
| Oracle | 11 | UTL_HTTP/UTL_FILE, EXECUTE IMMEDIATE injection, CONNECT BY without NOCYCLE |
| Snowflake | 9 | COPY INTO credentials, VARIANT in WHERE, CLONE without COPY GRANTS |
| BigQuery | 6 | SELECT * cost, DISTINCT on UNNEST, repeated subqueries |
| SQLite | 6 | ATTACH DATABASE file access, PRAGMA foreign_keys = OFF, AUTOINCREMENT overhead |
| Redshift | 7 | COPY with embedded credentials, COPY without MANIFEST, DISTSTYLE ALL |
| ClickHouse | 7 | url() SSRF, mutations, SELECT without FINAL, JOIN without GLOBAL |
| DuckDB | 3 | COPY without FORMAT, large IN lists, old-style casts |
| Presto / Trino | 4 | Implicit cross-joins, INSERT OVERWRITE without partition, ORDER BY without LIMIT |
| Spark / Databricks | 5 | BROADCAST on large table, UDF in WHERE, CACHE TABLE without filter |
The remaining 175 rules are universal and fire on all dialects.
SlowQL provides conservative, zero-risk autofixes for rules where the replacement is 100% semantically equivalent:
slowql queries.sql --diff
slowql queries.sql --fix
slowql queries.sql --fix --fix-report fixes.jsonAutofix principles:
- Only exact text replacements. No schema inference, no heuristic rewrites.
- Every fix is tagged with
FixConfidence.SAFE, meaning the output is functionally identical to the input. - A
.bakbackup is always created before writing. - Fixes can be previewed as a unified diff before applying.
Examples of safe autofixes:
| Rule | Before | After |
|---|---|---|
QUAL-NULL-001 |
WHERE x = NULL |
WHERE x IS NULL |
QUAL-STYLE-002 |
EXISTS (SELECT * FROM t) |
EXISTS (SELECT 1 FROM t) |
QUAL-MYSQL-003 |
LOCK IN SHARE MODE |
FOR SHARE |
QUAL-TSQL-001 |
SET ANSI_NULLS OFF |
SET ANSI_NULLS ON |
QUAL-ORA-002 |
SELECT 1 FROM DUAL |
SELECT 1 |
Rules can be silenced on a per-line, per-block, or per-file basis using directives written directly in SQL comments. No configuration file changes are required.
SELECT * FROM archive; -- slowql-disable-line PERF-SCAN-001
-- slowql-disable-next-line SEC-INJ-001
SELECT id, token FROM sessions WHERE id = $1;
-- slowql-disable PERF-SCAN
SELECT * FROM event_stream;
SELECT * FROM session_log;
-- slowql-enable PERF-SCAN
-- slowql-disable-file REL-001| Directive | Scope |
|---|---|
-- slowql-disable-line RULE-ID |
Current line only |
-- slowql-disable-next-line RULE-ID |
Next non-blank line |
-- slowql-disable RULE-ID |
Open block until matching enable or EOF |
-- slowql-enable RULE-ID |
Closes an open block |
-- slowql-disable-file RULE-ID |
Entire file |
The rule ID may be an exact identifier, a prefix, comma-separated values, or omitted entirely to suppress all rules for that scope. Matching is case-insensitive.
Baseline Mode allows you to adopt SlowQL on an existing, chaotic codebase without drowning in thousands of initial warnings. This is similar to SonarQube's "New Code Period."
-
Create a baseline: Store all your current issues in a
.slowql-baselinefile.slowql queries/ --update-baseline
-
Run against the baseline: Now, SlowQL will only flag new issues introduced after the baseline was created.
slowql queries/ --baseline
Because issues are fingerprinted via content hashes, standard edits like appending blank lines won't suddenly "un-suppress" your baseline issues. See the full Baseline Docs for CI/CD setup.
In CI environments, running static analysis over thousands of files on every commit is slow and unnecessary. SlowQL supports git-aware analysis to cleanly skip untouched files.
# Only analyze files that are changed, staged, or untracked
slowql . --git-diff
# Analyze files changed since branching off main
slowql . --since main--input-file Path to SQL file or directory
--schema Path to DDL schema file
--baseline Path to baseline file (suppress known issues)
--update-baseline Update/create the baseline file
--fail-on Failure threshold: critical, high, medium, low, info, never
--interactive Opt-in to full interactive experience (animations, menus) when no inputs are provided
--select-dialect Opt-in to prompt for dialect selection interactively
--non-interactive (deprecated, now the default) Explicitly disable interactive mode
--git-diff Only analyze files changed in the current workspace
--since Analyze files changed since a specific git revision (e.g. main)
--cache-dir Directory to store cache files (default: .slowql_cache)
--no-cache Disable query result caching
--clear-cache Clear cache directory before analysis
--jobs, -j Number of parallel workers for analyzing multiple files. (0 = auto)
--compare Enable query comparison mode
--format Primary output: console, github-actions, sarif
--export Export to disk: json, html, csv, sarif
--out Directory for exported reports
--diff Preview safe autofix diff
--fix Apply safe autofixes (single file, creates .bak)
--fix-report Write JSON report of fixes
--list-rules List all 282 rules with severity, dimension, and dialect
--list-rules --filter-dimension Filter by dimension (security, performance, etc.)
--list-rules --filter-dialect Filter by dialect (postgresql, mysql, etc.)
--explain RULE-ID Show full documentation for a specific rule
0 No issues found or issues below failure threshold
2 Issues found meet or exceed --fail-on threshold
3 Runtime error or tool failure
SlowQL discovers configuration from slowql.toml, .slowql.toml, slowql.yaml, .slowql.yaml, or pyproject.toml (under [tool.slowql]).
severity:
fail_on: high
warn_on: medium
analysis:
dialect: postgresql
enabled_dimensions:
- security
- performance
- reliability
disabled_rules:
- PERF-SCAN-001
severity_overrides:
PERF-SCAN-001: info
QUAL-NULL-001: critical
# Configuration is discovered from the analyzed directory or any parent.
# This allows project-specific and per-directory configuration.
schema:
path: db/schema.sql
output:
format: console
verbose: false
show_fixes: true
cost:
cloud_provider: none
compliance:
frameworks:
- gdpr- uses: slowql/slowql-action@v1
with:
path: "./sql/**/*.sql"
schema: "db/schema.sql"
fail-on: high
format: github-actions- name: SlowQL Analysis
run: |
pip install slowql
slowql --input-file sql/ --schema db/schema.sql --fail-on high --format github-actionsrepos:
- repo: https://github.com/slowql/slowql
rev: v1.6.2
hooks:
- id: slowql
args: [--fail-on, high]Install slowql-vscode from the VS Code Marketplace for real-time SQL analysis in your editor. The extension uses the SlowQL LSP server for diagnostics.
SlowQL now provides a numerical complexity score (0-100) for every analyzed query, helping teams enforce quality policies and track complexity trends.
- Spectral Analysis: Scores are calculated based on structural patterns like joins, subqueries, and aggregations.
- Visual Feedback: Terminal output highlights query complexity to help identify candidates for optimization.
You can enable/disable complexity scoring and set thresholds for "optimal", "complex", and "critical" queries in your .slowql.yml:
complexity:
enabled: true
threshold_optimal: 40
threshold_complex: 70SlowQL is a modular pipeline:
SQL Files β Parser (sqlglot) β AST β Analyzers β Rules β Issues β Reporters
β β
Schema Inspector AutoFixer
(DDL parsing) (safe text fixes)
Parser. Uses sqlglot for multi-dialect SQL parsing. Handles statement splitting, dialect detection, and AST generation.
Engine. Orchestrates parsing, analyzer execution, schema validation, and result aggregation.
Analyzers. Six domain-specific analyzers (Security, Performance, Reliability, Compliance, Cost, Quality), each loading rules from the catalog.
Custom Rules. Dynamic plugin system that loads user-defined rules from YAML files (regex-based) or Python modules (AST-based) at runtime.
Rules. 282 detection rules implemented as PatternRule (regex), ASTRule (sqlglot AST traversal), or custom Rule subclasses.
Schema Inspector. Parses DDL files into a schema model. Enables table/column existence checks and index suggestions.
Reporters. Console (rich TUI), GitHub Actions annotations, SARIF 2.1.0, JSON, HTML, CSV.
AutoFixer. Conservative text-based fix engine. Span-based and exact-text replacements only.
git clone https://github.com/slowql/slowql.git
pip install -e ".[dev]"
pytest
ruff check .
mypy src/slowqlApache License 2.0. See LICENSE.
Issues: github.com/slowql/slowql/issues
Discussions: github.com/slowql/slowql/discussions