Skip to main content

Universal SQL query optimizer to analyze, optimize, and monitor slow queries.

Project description

Query Optimizer Logo

Query Optimizer

An AI-powered SQL query optimizer that analyzes slow database queries and suggests performance improvements. Achieve 10–100× faster queries with intelligent index recommendations, query rewrites, and execution-plan analysis.

CI License: MIT PyPI


Table of Contents


🚀 Features

  • Multi-Database Support — PostgreSQL, MySQL, SQLite
  • Smart Analysis — Identifies missing indexes, inefficient joins, suboptimal WHERE/GROUP patterns, and more
  • Actionable Recommendations — Concrete SQL (e.g. CREATE INDEX ...) and rewritten queries
  • Multiple Access Methods — REST API, CLI tool, Python library
  • Production Ready — Containerized with Docker and CI/CD ready
  • Safety-first — Dry-run mode, explicit --apply flag for changes that mutate schema

💡 Quickstart

Hosted API (Recommended)

Use the hosted API when you want a no-ops, zero-maintenance start:

curl -s -X POST https://query-optimizer.onrender.com/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "query": "SELECT * FROM users WHERE email = \'user@example.com\'",
    "db_type": "postgresql"
  }'

Install CLI Tool

pip install git+https://github.com/makroumi/query-optimizer.git

Usage after install:

# Analyze a single ad-hoc query (no DB connection)
query-optimize "SELECT * FROM users WHERE created_at > '2023-01-01'" --db-type postgresql

# Analyze queries from a file
query-optimize --file slow_queries.sql --db-type mysql

# Connect to your DB for schema-aware analysis (safer + better recommendations)
query-optimize --connection "postgresql://user:pass@localhost/db" --analyze-schema

⚠️ By default the tool runs in read-only analysis mode. Use --apply with care to run any schema-changing recommendations.

Run Locally with Docker

git clone https://github.com/makroumi/query-optimizer.git
cd query-optimizer
docker build -t query-optimizer .
docker run --rm -p 8000:8000 query-optimizer

The web UI + API will be available at http://localhost:8000.


🧭 Usage

API Example

import requests

payload = {
    "query": "SELECT * FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.status = 'pending'",
    "db_type": "postgresql"
}

resp = requests.post("https://query-optimizer.onrender.com/analyze", json=payload)
print(resp.json())

Visit https://query-optimizer.onrender.com/docs for interactive API docs (OpenAPI/Swagger).

CLI Example

# Analyze queries in a file and output JSON recommendations
query-optimize --file slow_queries.sql --db-type sqlite --output recommendations.json

# Analyze a live DB (requires connection string and proper credentials)
query-optimize --connection "postgresql://user:pass@host:5432/dbname" --analyze-schema --file slow_queries.sql

Python Library

from query_optimizer import QueryOptimizer

optimizer = QueryOptimizer(db_type="postgresql")
result = optimizer.analyze("""
    SELECT u.*, COUNT(o.id) as order_count
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    GROUP BY u.id
    HAVING COUNT(o.id) > 10
""")

# programmatic access to recommendations and the optimized query
print(result.recommendations)
print(result.optimized_query)

🧪 Demo

Run the included demo script to see the optimizer in action against a test SQLite DB:

python demo_optimizer.py

What the demo does:

  • creates a sample SQLite database
  • runs intentionally slow queries
  • shows optimization recommendations and SQL to fix them
  • (optionally) applies indexes in a sandbox

📊 Example Output

{
  "original_query": "SELECT * FROM users WHERE email = 'user@example.com'",
  "issues": [
    {
      "type": "missing_index",
      "severity": "high",
      "description": "No index on users.email causing full table scan"
    }
  ],
  "recommendations": [
    {
      "type": "add_index",
      "sql": "CREATE INDEX idx_users_email ON users(email);",
      "impact": "~100x faster for email lookups"
    }
  ],
  "optimized_query": "SELECT id, name, email FROM users WHERE email = 'user@example.com'",
  "estimated_improvement": "95%"
}

🛠️ Development

Clone and set up a dev environment:

git clone https://github.com/makroumi/query-optimizer.git
cd query-optimizer
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -e .
pip install -r requirements.txt

Run tests

pytest -q

Test coverage and linting are included in the CI pipeline. See .github/workflows for details.


🤝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m "Add amazing feature"
  4. Push to your branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Please follow the project's coding standards and add unit tests for new functionality.


🏢 Enterprise & Support

  • Free Tier: 3 API calls/day
  • Pro Tier: Unlimited calls, priority support — $49/month
  • Enterprise: Self-hosted, custom adapters, SLA

Contact: elmehdi.makroumi@gmail.com


📄 License

MIT License — see LICENSE file in repository.


🙏 Acknowledgments

Built with frustration-driven development after too many 3am debugging sessions with slow queries. Thanks to the open-source community and many hours of query plan spelunking.


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

query_optimizer-0.1.0.tar.gz (25.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

query_optimizer-0.1.0-py3-none-any.whl (25.1 kB view details)

Uploaded Python 3

File details

Details for the file query_optimizer-0.1.0.tar.gz.

File metadata

  • Download URL: query_optimizer-0.1.0.tar.gz
  • Upload date:
  • Size: 25.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for query_optimizer-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6f9ec17e57e8c1b48653b16f20d413f4d477a6eff18b7d7f213549f2b263d0b1
MD5 e8214827d18a5ccca7ccc2900bef8eb8
BLAKE2b-256 d1413e8177af6687e9264d68cdc1fbd024876c199907a40c051bda8afbc350d8

See more details on using hashes here.

File details

Details for the file query_optimizer-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for query_optimizer-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 da7306b84dee58758ab9d3f5f40819ca576b50d8e701863624ee0a4121a27e7d
MD5 d24609b7a41767ff03f46bbe5272157e
BLAKE2b-256 ffe89ba94bee3cda4c515f9f5c0a79b715c2fe6a6531a6beac8a0b2c8013a7b5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page