Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

sqlglot

> 数据库
Open source

Python SQL Parser and Transpiler

9.5K stars0 likes1 views
WebsiteGitHub

About

Python SQL Parser and Transpiler

SQLGlot is a no-dependency SQL parser, transpiler, optimizer, and engine. It can be used to format SQL or translate between over 30 dialects like DuckDB, Presto / Trino, Spark / Databricks, Snowflake, and BigQuery. It aims to read a wide variety of SQL inputs and output syntactically and semantically correct SQL in the targeted dialects.

It is a very comprehensive generic SQL parser with a robust test suite. It is also quite performant, while being written purely in Python.

You can easily customize the parser, analyze queries, traverse expression trees, and programmatically build SQL.

SQLGlot can detect a variety of syntax errors, such as unbalanced parentheses, incorrect usage of reserved keywords, and so on. These errors are highlighted and dialect incompatibilities can warn or raise depending on configurations.

Learn more about SQLGlot in the API documentation and the expression tree primer.

Contributions are very welcome in SQLGlot; read the contribution guide and the onboarding document to get started!

Table of Contents

  • Install
  • Versioning
  • Get in Touch
  • FAQ
  • Examples
    • Formatting and Transpiling
    • Metadata
    • Parser Errors
    • Unsupported Errors
    • Build and Modify SQL
    • SQL Optimizer
    • AST Introspection
    • AST Diff
    • Custom Dialects
    • SQL Execution
  • Used By
  • Documentation
  • Run Tests and Lint
  • Benchmarks
  • Optional Dependencies
  • Supported Dialects

Install

From PyPI:

bash
# Pure python version
pip3 install sqlglot

# C extensions compiled with mypyc
# prebuilt wheel if available for your platform, otherwise builds from source
pip3 install "sqlglot[c]"

Or with a local checkout:

# Optionally prefix with UV=1 to use uv for the installation
make install

Requirements for development (optional):

# Optionally prefix with UV=1 to use uv for the installation
make install-dev

Versioning

Given a version number MAJOR.MINOR.PATCH:

  • PATCH is incremented for backwards-compatible changes.
  • MINOR is incremented for backwards-incompatible changes.
  • MAJOR is incremented for significant backwards-incompatible changes.

Get in Touch

We'd love to hear from you. Join our community Slack channel!

FAQ

I tried to parse SQL that should be valid, but it failed. Why?

You probably didn't specify the source dialect. Without it, parse_one assumes the "SQLGlot dialect", which is designed to be a superset of all supported dialects. Always pass the dialect when you know it, e.g. parse_one(sql, dialect="spark"). If parsing still fails, please file an issue.

The generated SQL is not in the correct dialect!

The target dialect must also be specified explicitly. For example, to transpile a query from Spark SQL to DuckDB, do parse_one(sql, dialect="spark").sql(dialect="duckdb"), or transpile(sql, read="spark", write="duckdb").

Why does SQLGlot parse my invalid SQL without complaining?

The parser is intentionally lenient, so it can accept queries that a real engine would reject. SQLGlot is a transpiler, not a validator. A query that parses successfully may still fail at execution time.

Why doesn't the output preserve my formatting, casing or quoting?

SQLGlot parses queries into an AST and generates SQL back from it, so it preserves the meaning of a query rather than its exact text. Cosmetic details can change in the process. Use pretty=True for formatted output and identify=True to quote all identifiers. Comments are preserved on a best-effort basis.

How can I make parsing faster?

Install the version compiled with mypyc: pip3 install "sqlglot[c]". It is roughly 3-5x faster than the pure Python version (see Benchmarks).

My dialect isn't supported. What are my options?

You can subclass an existing dialect (Custom Dialects), or ship one as a separate package (Creating a Dialect Plugin). Keep in mind that subclassing may not work properly with sqlglot[c] installed, so custom dialects may require the pure Python version.

Examples

Formatting and Transpiling

Easily translate from one dialect to another. For example, date/time functions vary between dialects and can be hard to deal with:

python
import sqlglot
sqlglot.transpile("SELECT EPOCH_MS(1618088028295)", read="duckdb", write="hive")[0]
sql
'SELECT FROM_UNIXTIME(1618088028295 / POW(10, 3))'

SQLGlot can even translate custom time formats:

python
import sqlglot
sqlglot.transpile("SELECT STRFTIME(x, '%y-%-m-%S')", read="duckdb", write="hive")[0]
sql
"SELECT DATE_FORMAT(x, 'yy-M-ss')"

Identifier delimiters and data types can be translated as well:

python
import sqlglot

# Spark SQL requires backticks (`) for delimited identifiers and uses `FLOAT` over `REAL`
sql = """WITH baz AS (SELECT a, c FROM foo WHERE a = 1) SELECT f.a, b.b, baz.c, CAST("b"."a" AS REAL) d FROM foo f JOIN bar b ON f.a = b.a LEFT JOIN baz ON f.a = baz.a"""

# Translates the query into Spark SQL, formats it, and delimits all of its identifiers
print(sqlglot.transpile(sql, write="spark", identify=True, pretty=True)[0])
sql
WITH `baz` AS (
  SELECT
    `a`,
    `c`
  FROM `foo`
  WHERE
    `a` = 1
)
SELECT
  `f`.`a`,
  `b`.`b`,
  `baz`.`c`,
  CAST(`b`.`a` AS FLOAT) AS `d`
FROM `foo` AS `f`
JOIN `bar` AS `b`
  ON `f`.`a` = `b`.`a`
LEFT JOIN `baz`
  ON `f`.`a` = `baz`.`a`

Comments are also preserved on a best-effort basis:

python
sql = """
/* multi
   line
   comment
*/
SELECT
  tbl.cola /* comment 1 */ + tbl.colb /* comment 2 */,
  CAST(x AS SIGNED), # comment 3
  y               -- comment 4
FROM
  bar /* comment 5 */,
  tbl #          comment 6
"""

# Note: MySQL-specific comments (`#`) are converted into standard syntax
print(sqlglot.transpile(sql, read='mysql', pretty=True)[0])
sql
/* multi
   line
   comment
*/
SELECT
  tbl.cola /* comment 1 */ + tbl.colb /* comment 2 */,
  CAST(x AS SIGNED), /* comment 3 */
  y /* comment 4 */
FROM bar /* comment 5 */, tbl /*          comment 6 */

Metadata

You can explore SQL with expression helpers to do things like find columns and tables in a query:

python
from sqlglot import parse_one, exp

# print all column references (a and b)
for column in parse_one("SELECT a, b + 1 AS c FROM d").find_all(exp.Column):
    print(column.alias_or_name)

# find all projections in select statements (a and c)
for select in parse_one("SELECT a, b + 1 AS c FROM d").find_all(exp.Select):
    for projection in select.expressions:
        print(projection.alias_or_name)

# find all tables (x, y, z)
for table in parse_one("SELECT * FROM x JOIN y JOIN z").find_all(exp.Table):
    print(table.name)

Read the ast primer to learn more about SQLGlot's internals.

Parser Errors

When the parser detects an error in the syntax, it raises a ParseError:

python
import sqlglot
sqlglot.transpile("SELECT foo FROM (SELECT baz FROM t")
sqlglot.errors.ParseError: Expecting ). Line 1, Col: 34.
  SELECT foo FROM (SELECT baz FROM t
                                   ~

Structured syntax errors are accessible for programmatic use:

python
import sqlglot.errors
try:
    sqlglot.transpile("SELECT foo FROM (SELECT baz FROM t")
except sqlglot.errors.ParseError as e:
    print(e.errors)
python
[{
  'description': 'Expecting )',
  'line': 1,
  'col': 34,
  'start_context': 'SELECT foo FROM (SELECT baz FROM ',
  'highlight': 't',
  'end_context': '',
  'into_expression': None
}]

Unsupported Errors

It may not be possible to translate some queries between certain dialects. For these cases, SQLGlot may emit a warning and will proceed to do a best-effort translation by default:

python
import sqlglot
sqlglot.transpile("SELECT APPROX_DISTINCT(a, 0.1) FROM foo", read="presto", write="hive")
sql
Argument 'accuracy' is not supported for expression 'ApproxDistinct' when targeting Hive.
'SELECT APPROX_COUNT_DISTINCT(a) FROM foo'

This behavior can be changed by setting the unsupported_level attribute. For example, we can set it to either RAISE or IMMEDIATE to ensure an exception is raised instead:

python
import sqlglot
sqlglot.transpile("SELECT APPROX_DISTINCT(a, 0.1) FROM foo", read="presto", write="hive", unsupported_level=sqlglot.ErrorLevel.RAISE)
sqlglot.errors.UnsupportedError: Argument 'accuracy' is not supported for expression 'ApproxDistinct' when targeting Hive.

Some queries need additional information to be transpiled accurately, such as the schemas of the referenced tables. This is because certain transformations are type-sensitive and depend on type inference. The qualify and annotate_types optimizer rules can provide this information, but they are not used by default because they add overhead and complexity.

Transpilation is a hard problem, so SQLGlot solves it incrementally. Some dialect pairs may lack support for certain inputs, but coverage improves over time. We highly appreciate well-documented and tested issues or PRs, so feel free to reach out if you need guidance!

Build and Modify SQL

SQLGlot supports incrementally building SQL expressions:

python
from sqlglot import select, condition

where = condition("x=1").and_("y=1")
select("*").from_("y").where(where).sql()
sql
'SELECT * FROM y WHERE x = 1 AND y = 1'

It's possible to modify a parsed tree:

python
from sqlglot import parse_one
parse_one("SELECT x FROM y").from_("z").sql()
sql
'SELECT x FROM z'

Parsed expressions can also be transformed recursively by applying a mapping function to each node in the tree:

python
from sqlglot import exp, parse_one

expression_tree = parse_one("SELECT a FROM x")

def transformer(node):
    if isinstance(node, exp.Column) and node.name == "a":
        return parse_one("FUN(a)")
    return node

transformed_tree = expression_tree.transform(transformer)
transformed_tree.sql()
sql
'SELECT FUN(a) FROM x'

SQL Optimizer

SQLGlot can rewrite queries into an "optimized" form. It performs a variety of techniques to create a new canonical AST. This AST can be used to standardize queries or provide the foundations for implementing an actual engine. For example:

python
import sqlglot
from sqlglot.optimizer import optimize

print(
    optimize(
        sqlglot.parse_one("""
            SELECT A OR (B OR (C AND D))
            FROM x
            WHERE Z = date '2021-01-01' + INTERVAL '1' month OR 1 = 0
        """),
        schema={"x": {"A": "INT", "B": "INT", "C": "INT", "D": "INT", "Z": "STRING"

Issues· 9 open

View all issuesOpen on GitHub
  • #8462

    Postgres Dialect : LATERAL UNNEST drops WITH ORDINALITY alias column

    Updated Sep 29, 2026
  • #8443

    MySQL: `--` only starts a comment when followed by whitespace or a control character

    Updated Sep 28, 2026
  • #8399

    Snowflake: PUT with an unquoted source falls back to exp.Command

    Updated Sep 19, 2026
  • #8392

    MySQL round-trip silently changes semantics: DATE() stripped from DATE_ADD argument

    Updated Sep 18, 2026
  • #8390

    parsing bug with intersect, dialect: postgres

    Updated Sep 18, 2026
  • #8380

    simplify: collapsing a CASE under an arithmetic operator drops the grouping of the branch

    Updated Sep 17, 2026

> Tags

Pythonbigqueryclickhousedatabricksduckdb

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库