sqlparse: A Powerful Non-Validating SQL Parser for Python

This repository profile is provided by osrepos.com, an open source repository discovery platform.

sqlparse: A Powerful Non-Validating SQL Parser for Python

Summary

sqlparse is a robust, non-validating SQL parser module for Python, designed to tokenize SQL text and group its components into a structured tree. It serves as a foundational tool for building formatters, linters, and query analysis applications. Developers can leverage its capabilities to split SQL scripts, format statements, and deeply inspect their token trees.

Repository Information

Analyzed by OSRepos on July 30, 2026

Topics

Click on any tag to explore related repositories

Use at your own risk

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of code from these repositories is the user's own responsibility. Always review the repository, source code, dependencies, licenses, and security implications before running or installing anything. OSRepos is not responsible for issues, damages, or losses resulting from third-party repositories.

Introduction

sqlparse is a non-validating SQL parser for Python, offering powerful capabilities to process SQL text. It excels at splitting scripts into individual statements, formatting them according to various styles, and allowing users to traverse their intricate token trees.

This library tokenizes SQL text, organizing the recognized parts into a hierarchical structure of statements, clauses, identifiers, and expressions. A key advantage of sqlparse is its flexibility: it accepts any input without validation and makes no assumptions about specific SQL dialects. This makes it highly adaptable for handling vendor extensions and templated SQL, serving as an essential building block for formatters, linters, editors, and advanced query analysis tools.

Installation

Getting started with sqlparse is straightforward. You can install it using pip:

pip install sqlparse

Examples

sqlparse provides three primary module-level functions to cover most common needs: split(), format(), and parse().

Split a script into statements

Easily break down a SQL script containing multiple statements into a list of individual statements:

import sqlparse

sqlparse.split("select * from foo; select * from bar;")
# ['select * from foo;', 'select * from bar;']

Format a statement

Enhance the readability of your SQL queries with sqlparse's formatting capabilities. You can specify options like reindentation and keyword casing:

print(sqlparse.format("select id,name from users where active=1",
                      reindent=True, keyword_case="upper"))

This will produce:

SELECT id,
       name
FROM users
WHERE active=1

The format() function supports various options, including reindent, keyword_case, strip_comments, and indent_width, similar to its command-line counterpart.

Parse and inspect a statement

For deeper analysis, sqlparse allows you to parse a statement and inspect its token tree. This is invaluable for understanding the structure of complex queries:

statement = sqlparse.parse("select id, name from users where active = 1")[0]

print(statement.get_type())
for token in statement.tokens:
    if not token.is_whitespace:
        print(f"{token.ttype or type(token).__name__!s:20} {token!s}")

Output will resemble:

SELECT
Token.Keyword.DML    select
IdentifierList       id, name
Token.Keyword        from
Identifier           users
Where                where active = 1

Tokens with a ttype are leaf nodes, while others represent groups that can be further explored. This hierarchical representation is how nested constructs, such as subqueries and CASE expressions, are managed. For more details on traversing the API, refer to the Analyzing SQL statements documentation.

Why Use sqlparse?

sqlparse stands out as an indispensable tool for anyone working with SQL in Python due to several key features:

  • Flexibility: Its non-validating nature and dialect-agnostic approach mean it can parse virtually any SQL, including vendor-specific extensions and templated queries.
  • Foundation for Tools: It provides the core parsing logic needed to build sophisticated SQL formatters, linters, editors, and advanced query analysis applications.
  • Simple API: Common tasks like splitting, formatting, and parsing SQL are made easy with intuitive module-level functions.
  • Command-Line Utility: The sqlformat command-line tool offers quick formatting directly from your terminal, supporting in-place file modifications.
  • Pre-commit Integration: Seamlessly integrate sqlparse into your development workflow using pre-commit hooks to ensure consistent SQL formatting across your projects.

Links

Explore sqlparse further with these official resources:

Related repositories

Similar repositories that may be relevant next.

Open Index: A Deterministic Memory Layer for Your AI Agents

Open Index: A Deterministic Memory Layer for Your AI Agents

September 16, 2026

Open Index is a powerful tool for building domain-specific, accurate, and structured data that AI agents can effectively operate on. It enables the creation of a "brain," a searchable and continuously improving context graph tailored to any domain. This system ensures agents have access to reliable, up-to-date information, enhancing their capabilities and decision-making processes.

AI AgentsKnowledge GraphAgent Memory
tooltrim: Drastically Reduce LLM Agent Tool Output Tokens, Improve Accuracy

tooltrim: Drastically Reduce LLM Agent Tool Output Tokens, Improve Accuracy

September 16, 2026

tooltrim provides drop-in compression for LLM agent tool outputs, drastically cutting tokens while often improving answer accuracy. This provider-agnostic solution offers content-aware compression, faithfulness benchmarks, and seamless integration with popular frameworks or as an OpenAI-compatible proxy.

PythonLLM AgentsContext Compression
AgentShield: Python Firewall for AI Agent Spend Control

AgentShield: Python Firewall for AI Agent Spend Control

September 16, 2026

AgentShield is a pure Python library designed to prevent runaway AI agents from exceeding budget limits. It offers 10 composable spend rules, evaluated in under 1ms, providing robust cost control. Although its core development has transitioned to sipi.bot, the AgentShield Python package remains available for existing users and its test fixtures are open-source.

PythonAI AgentsCost Control
DA-Forge: Streamlining Declarative Agent Creation for Copilot Notebooks

DA-Forge: Streamlining Declarative Agent Creation for Copilot Notebooks

September 12, 2026

DA-Forge is a Python-based tool by Microsoft designed to automate the creation and deployment of Declarative Agents for Copilot Notebooks. It significantly reduces the manual effort and time required to set up AI assistants with specific grounding references, transforming an 85-minute process into just a few minutes. This tool is essential for developers and researchers working with Copilot Notebooks and Declarative Agents.

PythonMicrosoft 365Copilot

Source repository

Open the original repository on GitHub.

11 counted GitHub visits

View on GitHub
OS
OSRepos

Analysis and discovery of open source repositories. Find interesting projects and follow their updates.

Monitor your website with YourWebsiteScore

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of third-party repository code is at your own risk. Always review source code, dependencies, licenses, and security implications before running anything.

© 2025 OSRepos. Built with Nuxt 3 and lots of ❤️