SQL interface
Daft's SQL interface turns SQL text into expressions or lazy logical plans, then lets the normal DataFrame workflow optimize and execute those plans. It also reads from and writes to external SQL databases, so SQL can serve as either a query language over Daft data or a boundary to database data. This page is a child of Query planning and optimization and relates to Logical plans and optimizer.
SQL entry points
The interface has separate entry points for SQL expressions, queries over Daft objects, and direct database reads. Each entry point keeps work lazy where possible and hands the result to the same DataFrame and logical-plan path.
SQL expressions
daft.sql_expr parses one SQL expression and returns a Daft Expression. The expression can be combined with normal DataFrame expressions, which gives users a small SQL syntax layer without changing the surrounding DataFrame operation. String predicates in some DataFrame methods use this same path automatically.
References: daft/…/sql.py• L18-73 daft/…/dataframe.py• L3200-3230
SQL queries
daft.sql resolves SQL table names against DataFrames in the caller's Python scope and against explicit bindings. It returns a lazy DataFrame backed by the SQL-produced logical plan, while Session.sql resolves names against the session's tables, catalogs, temporary tables, and views. Explicit bindings take precedence over discovered global DataFrames in daft.sql.
References: daft/…/sql.py• L76-180 daft/session.py• L86-170 daft/session.py• L176-255
Database reads and writes
daft.read_sql creates a lazy DataFrame from a query that runs in an external SQL database. A DataFrame can also write to a database with write_sql; the write returns a DataFrame with aggregate write metrics. These APIs form a separate database boundary from daft.sql, which plans SQL over Daft-managed relations.
References: daft/…/_sql.py• L25-123 daft/…/dataframe.py• L910-1014
SQL parsing and translation
The SQL planner parses SQL text, resolves its names in the active session, and maps supported SQL operations to Daft logical-plan operations. The translation ends before physical execution, so the resulting plan can use the normal optimizer and execution engines.
Statement planning
The planner accepts one SQL statement at a time and reports parse errors with the input location. It plans query statements into logical plans and passes supported session or catalog statements to execution: USE changes the active catalog and namespace, SHOW TABLES produces a table-valued result, and supported CREATE TABLE forms update a catalog. SET is rejected during execution. Unsupported SQL features fail during planning instead of reaching execution with an unclear meaning.
References: src/…/planner.rs• L317-398 src/…/statement.rs• L10-24 src/…/statement.rs• L62-105 src/…/exec.rs• L20-121 src/…/exec.rs• L140-197
Relational translation
For a query, the planner builds the source relation first and then applies the SQL clauses as logical operations. The main path covers sources, joins, projection, filtering, grouping, ordering, distinct results, limits, offsets, sampling, and supported set operations. Common table expressions become named plan bindings that can feed later parts of the query. Derived table relations and supported scalar or predicate subqueries create child plan scopes within the same logical-plan model.
References: src/…/planner.rs• L398-475 src/…/planner.rs• L476-613 src/…/planner.rs• L913-1120 src/…/planner.rs• L1703-1717 src/…/planner.rs• L1905-1923
Expression translation
SQL expressions map to Daft expressions and use the same type and function model as DataFrame expressions. A standalone expression has no source schema, so its column names remain unresolved until a later DataFrame operation supplies the relation. Query expressions resolve against the current relation and join sides, which allows SQL aliases and qualified column names to participate in normal plan construction.
Expressions can also contain supported casts, date parts, string operations, conditional expressions, list or map access, and subquery predicates. The planner keeps these as expression nodes until the surrounding logical plan resolves and executes them.
References: src/…/python.rs• L62-66 src/…/planner.rs• L1374-1482 src/…/planner.rs• L1640-1924 src/…/planner.rs• L2231-2285 src/…/planner.rs• L2456-2482
SQL function resolution
SQL function calls resolve case-insensitively against session functions first and then the built-in SQL function registry. Built-in names are normalized when they enter the registry, so their registration form does not change SQL lookup. The registry connects SQL names to Daft scalar functions and SQL-specific forms, so calls such as concat and coalesce become normal Daft expressions. Window syntax also becomes a Daft window expression. Unsupported argument forms or function clauses fail during planning.
SQL also exposes configuration constructors such as S3Config, HTTPConfig, AzureConfig, GCSConfig, and TosConfig. These functions accept named SQL arguments and produce literal configuration values for storage and file-access operations. The planner later converts those values to the corresponding I/O configuration, so the accepted argument names and value types are part of the SQL-to-scan contract.
References: src/…/functions.rs• L68-99 src/…/functions.rs• L415-491 src/…/functions.rs• L536-557 src/…/config.rs• L12-21 src/…/config.rs• L31-136 src/…/config.rs• L457-542
SQL data types
SQL type text is converted to Daft data types when SQL defines a schema or uses a type cast. This conversion is the contract between SQL syntax and the DataFrame schema system; unsupported or ambiguous SQL types are rejected during planning.
References: src/…/schema.rs• L17-43 src/…/schema.rs• L67-90 src/…/planner.rs• L1602-1616 src/…/planner.rs• L2430-2453
Session and relation resolution
SQL name resolution connects SQL text to the data objects that a plan can read. A session supplies the catalog state and current namespace, while query-local bindings supply temporary names for DataFrames and common table expressions.
DataFrame bindings
daft.sql can add DataFrame variables from the caller's local and global scope to a temporary query catalog. Callers can disable that discovery and pass explicit bindings instead. A DataFrame binding is used as a plan source rather than copied into a separate materialized table, so SQL and DataFrame operations can remain part of one lazy workflow.
References: daft/…/sql.py• L147-172 daft/session.py• L249-255
Catalog names
Session.sql resolves table names through attached catalogs and temporary relations. Names may be unqualified, namespace-qualified, or catalog-qualified. The current catalog and namespace control how short names resolve, while a fully qualified name selects its catalog directly. USE sets the current catalog and optional namespace. SHOW TABLES reads the named catalog or current catalog, while CREATE TABLE uses catalog and namespace qualification to choose where to create the table.
References: src/…/planner.rs• L270-280 src/…/planner.rs• L1331-1372 src/…/exec.rs• L44-105 src/…/exec.rs• L140-155 tests/…/test_sess_sql.py• L58-114
Common table expressions
Common table expressions, or CTEs, are named query plans scoped to one SQL statement. The planner aliases each binding for name resolution, plans each CTE before the outer query, and rejects recursive or duplicate CTE definitions.
References: src/…/planner.rs• L229-237 src/…/planner.rs• L290-313 tests/…/test_sql.py• L396-453
SQL database scans
The database read path treats an external query as a lazy scan source. Daft learns the result schema, estimates the input size, and creates scan tasks that the selected execution engine can run later.
Connection boundary
SQLConnection normalizes either a database URL or a SQLAlchemy connection factory into a connection description with a dialect and driver. Daft uses ConnectorX for eligible URL-based databases and SQLAlchemy for connection factories or other cases. It also builds dialect-aware source queries when a scan needs projections, filters, limits, or partition bounds. Connection URLs are omitted from object representations and execution errors so credentials are not echoed in diagnostics.
References: daft/…/sql_connection.py• L19-65 daft/…/sql_connection.py• L67-113 daft/…/sql_connection.py• L115-174 daft/…/recordbatch_io.py• L141-170
Schema discovery
read_sql infers the query schema by running a bounded schema read unless the caller supplies a definitive schema. A supplied schema can also act as a hint after inference. The scan uses this schema to validate and cast batches as they enter the DataFrame workflow.
References: daft/…/_sql.py• L25-50 daft/…/sql_scan.py• L155-169 daft/…/recordbatch_io.py• L159-170
Query pushdowns
The scan can add a DataFrame projection, filter, or limit to the source SQL query. This reduces the data returned by the database before it reaches Daft. If a pushdown cannot be expressed for the source or pushdowns are disabled, the scan keeps the source query unchanged and applies the remaining work after the read.
References: daft/…/sql_connection.py• L67-113 daft/…/sql_scan.py• L274-312 daft/…/recordbatch_io.py• L159-170
Scan partitioning
Large database reads can split into several scan tasks by a numeric or temporal column. Daft chooses equal ranges from minimum and maximum values or uses discrete percentiles when that strategy is selected. If bounds cannot be computed or have no useful range, the read falls back to one scan task.
References: daft/…/sql_scan.py• L95-144 daft/…/sql_scan.py• L171-267 daft/context.py• L233-234 daft/context.py• L282-283
DataFrame and logical-plan workflow
SQL is an input language for the same lazy plan system used by the DataFrame API. A SQL result does not bypass planning: it becomes a DataFrame whose logical plan can be extended with DataFrame methods and later materialized by the usual execution path.
Query-to-plan flow
The following flow shows how SQL over Daft relations becomes a DataFrame and then follows normal planning and execution.
flowchart LR
A[SQL text] --> B[Parse and validate]
B --> C[Resolve session tables and CTEs]
C --> D[Build logical plan]
D --> E[DataFrame]
E --> F[Optimize and execute]
F --> G[Result batches]
daft.sql and Session.sql stop after building the lazy DataFrame for query statements. The later collect, show, or write operation drives optimization and execution. USE and CREATE TABLE update session or catalog state and return no DataFrame, while SHOW TABLES returns a DataFrame built from catalog metadata.
References: src/…/python.rs• L37-60 src/…/exec.rs• L23-45 src/…/exec.rs• L50-121 src/…/exec.rs• L140-197 daft/…/sql.py• L170-180 daft/session.py• L153-170
External-query flow
The following flow shows how read_sql inserts a database scan into the same logical-plan workflow.
flowchart LR
A[SQL query and connection] --> B[Create SQL scan]
B --> C[Infer or accept schema]
C --> D[Build scan tasks]
D --> E[Push down filters columns and limits]
E --> F[Read Arrow batches from database]
F --> G[Daft DataFrame plan]
The scan is lazy, but schema and size planning can query the database before the final DataFrame is materialized. Each task carries the source SQL, connection description, schema, and any range bound needed for its part of the read.
References: daft/…/_sql.py• L104-123 daft/…/sql_scan.py• L53-75 daft/…/sql_scan.py• L95-144 daft/…/sql_scan.py• L274-312
DataFrame-to-database flow
DataFrame.write_sql sends materialized DataFrame batches to a SQL table through a sink. The sink applies append, overwrite, or fail table semantics once at start, then writes batches and returns total row and byte counts as a one-row DataFrame. Non-primitive Daft values are converted to text or bytes unless the caller selects an error policy.
References: daft/…/dataframe.py• L911-947 daft/…/_sql.py• L258-323 daft/…/_sql.py• L325-390
SQL surface and boundaries
The SQL planner supports a Daft-focused SQL surface rather than every dialect feature. Its boundaries are part of the user contract because they determine whether a statement becomes a logical plan, updates session state, or fails during planning or execution.
Supported relation sources
SQL can read session tables, temporary DataFrame views, CTEs, attached catalog tables, derived table queries, supported file paths, and table functions. File paths are mapped to SQL table functions for formats such as CSV, JSON, and Parquet. read_iceberg maps Iceberg metadata to a logical scan and can select a snapshot, branch, or tag. Table sampling can turn a source into a sampled logical plan. External database queries use read_sql when the source is a database connection rather than a Daft SQL relation.
References: src/…/planner.rs• L1027-1120 src/…/planner.rs• L1122-1171 src/…/mod.rs• L32-39 src/…/read_iceberg.rs• L14-25 src/…/read_iceberg.rs• L27-92 daft/session.py• L404-446
Unsupported constructs
The planner or executor rejects unsupported statements and query features during translation or execution. Important boundaries include one statement per call, no recursive CTEs, no VALUES or top-level DML query forms, unsupported query clauses and table factors, unsupported SET statements, and only the supported SQL function argument forms. Derived tables and supported EXISTS, IN subqueries, and scalar subqueries are valid scoped forms; unsupported subquery shapes still fail during planning. Error messages include the SQL location for parse failures, which helps distinguish invalid syntax from a valid but unsupported feature.
References: src/…/planner.rs• L317-387 src/…/planner.rs• L398-469 src/…/planner.rs• L1064-1107 src/…/planner.rs• L1703-1719 src/…/planner.rs• L1905-1924 src/…/planner.rs• L2326-2428 src/…/functions.rs• L169-187 src/…/functions.rs• L505-555 src/…/exec.rs• L46-48 tests/…/test_sql.py• L214-345
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the SQL parser's statement and expression rules aligned with the logical-plan builders that consume the translated result.
- Keep SQL name resolution aligned with session catalog state, DataFrame bindings, CTE aliases, nested query scopes, and current catalog or namespace behavior.
- Keep SQL function lookup order, lower-case registry keys, and registry entries aligned with session UDFs and the Daft function registry.
- When adding a SQL function or type, update the SQL-to-Daft mapping and the schema or expression contract used by downstream plans.
- Keep SQL I/O configuration constructors aligned with
expr_to_iocfg: variant names, named arguments, literal types, and default handling must match. - Keep table-valued function and file-path argument rules aligned with the logical scan builder and its public API.
- When changing relation aliases or join resolution, preserve qualified names, ambiguity checks, and
USINGoutput column order. - When changing subquery or CTE planning, preserve child-scope visibility and statement-local binding cleanup.
- When changing database pushdowns, preserve the fallback path that applies filters or limits after a database read.
- When changing SQL scan partitioning, keep bound-query construction, schema types, task estimates, and inclusive range edges consistent.
- When changing connection support, check both URL-based ConnectorX reads and SQLAlchemy factory reads. Preserve the rule that connection secrets are not echoed in diagnostics.
- When changing SQL writes, preserve the table-mode initialization and the metrics schema returned to DataFrame callers.
- When changing session statement execution, keep catalog and namespace updates, catalog qualification, table-list result schemas, and
IF NOT EXISTSbehavior aligned with the catalog contract.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| SQL contains more than one statement | Planning fails before a DataFrame is returned. | Submit one statement per SQL call. |
| A table name is absent from the session, catalog, CTEs, or bindings | Name resolution fails during logical-plan construction. | Attach the relation or pass an explicit binding with the intended name. |
| A qualified identifier uses an unsupported quote style | Planning rejects the relation or column name. | Use unquoted names or double-quoted delimited identifiers. |
| A SQL query uses an unsupported feature or function form | Planning stops with an unsupported-feature error rather than producing a partial plan. | Use the supported SQL surface or compose the equivalent DataFrame operations. |
| A function name is not registered in the session or built-in SQL registry | The SQL expression cannot become a Daft expression. | Register the function or use a supported function name. |
| A built-in function is registered under a mixed-case key outside the normal registration path | Lookup does not find the function after SQL lowercases its name. | Register through the SQL function registry, which normalizes names. |
| A configuration constructor receives an unknown named argument or a value with the wrong literal type | Planning rejects the configuration before the related file or table operation runs. | Use the constructor's supported named arguments and expected literal types. |
| A configuration literal has a missing or invalid variant | Conversion to IOConfig fails before the I/O operation starts. | Use a registered configuration constructor and keep its variant contract intact. |
A SET statement is submitted | Execution rejects the statement instead of changing session settings. | Use a supported session statement or configure the relevant session behavior through its supported interface. |
USE or SHOW TABLES runs without a current catalog when no catalog is named | The session operation fails because there is no catalog to update or inspect. | Set a catalog with USE or provide a catalog-qualified operation. |
An unqualified CREATE TABLE runs without a current catalog | Table creation fails before the catalog receives the request. | Set a current catalog or use a catalog-qualified table name. |
A table already exists and CREATE TABLE does not use IF NOT EXISTS | Catalog creation fails with an already-exists error. | Use IF NOT EXISTS when an existing table is an acceptable result. |
| A derived table alias has a different number of names than its output columns | Planning fails before the outer query can resolve the alias columns. | Match the alias column list to the derived relation schema. |
SELECT without FROM runs without the Python feature | The planner cannot create the singleton source plan. | Run with the Python feature or provide a relation. |
| A table path is not single-quoted or has an unsupported extension | Relation planning fails instead of creating a file scan. | Use a single-quoted CSV, JSON, JSONL, or Parquet path. |
| Schema inference is disabled without a schema | read_sql cannot define the DataFrame schema. | Provide a schema or enable inference. |
| A source dialect is not supported for dialect-aware query construction | Schema discovery or a scan pushdown fails before the database read completes. | Use a supported dialect or avoid the external SQL scan path. |
| A requested SQL partition column is not numeric or temporal | Daft cannot derive range bounds and the read cannot use that partition scheme. | Choose a numeric or temporal column or use one scan task. |
| SQL pushdown cannot express a DataFrame filter | The source query may read more rows and Daft applies the filter after the read. | Keep the fallback path enabled and account for database-side work versus in-memory work. |
read_iceberg has no metadata path or runs without the required Python feature | Planning fails instead of producing an Iceberg scan. | Supply the path and enable the Python feature for this table function. |
A non-primitive DataFrame column reaches write_sql with error handling enabled | The write fails before the values reach the SQL driver. | Cast or drop the column, or choose text or bytes handling. |
Key files
| File | Why to read it |
|---|---|
| daft/…/sql.py | Public SQL query and expression entry points over DataFrames. |
| daft/session.py | Session-scoped SQL execution, relation attachment, temporary views, and catalog state. |
| src/…/planner.rs | Core parsing, name resolution, scoped subqueries, relation sources, and SQL-to-logical-plan translation. |
| src/…/functions.rs | SQL function lookup, registration, argument handling, and window-function translation. |
| src/…/config.rs | SQL constructors and conversion for storage and web I/O configuration values. |
| src/…/read_iceberg.rs | Iceberg table-function arguments and their logical scan boundary. |
| src/…/statement.rs | Supported top-level SQL statement forms and their planning boundary. |
| src/…/exec.rs | Conversion from planned SQL statements to logical-plan results or session and catalog actions. |
| daft/…/_sql.py | Public database reads and the SQL write sink boundary. |
| daft/…/sql_connection.py | Database connection selection, dialect-aware query construction, result reads, and safe diagnostics. |
| daft/…/sql_scan.py | Schema, pushdown, size, and partition planning for database scans. |
| src/…/schema.rs | SQL type parsing and conversion to Daft data types. |
| daft/…/dataframe.py | DataFrame write-to-SQL contract and returned write metrics. |