Queries

DML query builders for SELECT, INSERT, UPDATE, DELETE, and MERGE operations.

Select

class sqlspec.builder.Select[source]

Bases: QueryBuilder, WhereClauseMixin, OrderByClauseMixin, LimitOffsetClauseMixin, SelectClauseMixin, JoinClauseMixin, HavingClauseMixin, SetOperationMixin, CommonTableExpressionMixin, PivotClauseMixin, UnpivotClauseMixin, ExplainMixin

Builder for SELECT queries.

Provides a fluent interface for constructing SQL SELECT statements with parameter binding and validation.

Example

>>> class User(BaseModel):
...     id: int
...     name: str
>>> builder = Select("id", "name").from_("users")
>>> result = driver.execute(builder)
__init__(*columns, **kwargs)[source]

Initialize SELECT with optional columns.

Parameters:
  • *columns (str) – Column names to select (e.g., “id”, “name”, “u.email”)

  • **kwargs (Any) – Additional QueryBuilder arguments (dialect, schema, etc.)

Examples

Select(“id”, “name”) # Shorthand for Select().select(“id”, “name”) Select() # Same as Select() - start empty

with_hint(hint, *, location='statement', table=None, dialect=None)[source]

Attach an optimizer or dialect-specific hint to the query.

Parameters:
  • hint (str) – The raw hint string (e.g., ‘INDEX(users idx_users_name)’).

  • location (str) – Where to apply the hint (‘statement’, ‘table’).

  • table (str | None) – Table name if the hint is for a specific table.

  • dialect (str | None) – Restrict the hint to a specific dialect (optional).

Return type:

Self

Returns:

The current builder instance for method chaining.

build(dialect=None)[source]

Builds the SQL query string and parameters with hint injection.

Parameters:

dialect (Union[str, Dialect, Type[Dialect], None]) – Optional dialect override for SQL generation.

Returns:

A dataclass containing the SQL string and parameters.

Return type:

BuiltQuery

for_update(*, skip_locked=False, nowait=False, of=None)[source]

Add FOR UPDATE clause to SELECT statement for row-level locking.

Parameters:
  • skip_locked (bool) – Skip rows that are already locked (SKIP LOCKED)

  • nowait (bool) – Return immediately if row is locked (NOWAIT)

  • of (str | list[str] | None) – Table names/aliases to lock (FOR UPDATE OF table)

Return type:

Self

Returns:

Self for method chaining

for_share(*, skip_locked=False, nowait=False, of=None)[source]

Add FOR SHARE clause for shared row-level locking.

Parameters:
  • skip_locked (bool) – Skip rows that are already locked (SKIP LOCKED)

  • nowait (bool) – Return immediately if row is locked (NOWAIT)

  • of (str | list[str] | None) – Table names/aliases to lock (FOR SHARE OF table)

Return type:

Self

Returns:

Self for method chaining

for_key_share()[source]

Add FOR KEY SHARE clause (PostgreSQL-specific).

FOR KEY SHARE is like FOR SHARE, but the lock is weaker: SELECT FOR UPDATE is blocked, but not SELECT FOR NO KEY UPDATE.

Return type:

Self

Returns:

Self for method chaining

for_no_key_update()[source]

Add FOR NO KEY UPDATE clause (PostgreSQL-specific).

FOR NO KEY UPDATE is like FOR UPDATE, but the lock is weaker: it does not block SELECT FOR KEY SHARE commands that attempt to acquire a share lock on the same rows.

Return type:

Self

Returns:

Self for method chaining

Select Clause Mixins

class sqlspec.builder.SelectClauseMixin[source]

Bases: object

Mixin providing SELECT clause methods.

select_only(*columns)[source]

Replace currently selected columns with new ones.

Return type:

Self

from_(table, alias=None, as_of=None, as_of_type=None)[source]

Set the FROM clause and optionally attach temporal versioning.

as_of copies the resolved table expression, normalizes aliases, and adds an exp.Version so sqlglot’s generator emits dialect-specific time-travel SQL.

Return type:

Self

class sqlspec.builder.WhereClauseMixin[source]

Bases: object

class sqlspec.builder.OrderByClauseMixin[source]

Bases: object

class sqlspec.builder.LimitOffsetClauseMixin[source]

Bases: object

class sqlspec.builder.HavingClauseMixin[source]

Bases: object

class sqlspec.builder.ReturningClauseMixin[source]

Bases: object

class sqlspec.builder.CommonTableExpressionMixin[source]

Bases: object

with_(name, query, recursive=False, columns=None)[source]

Add a CTE via the WITH clause.

When query is another builder we reuse its expression, merge parameters with unique names, and let sqlglot handle the actual CTE wrapping to avoid duplicating _with_ctes state.

Return type:

Self

class sqlspec.builder.SetOperationMixin[source]

Bases: object

class sqlspec.builder.PivotClauseMixin[source]

Bases: object

class sqlspec.builder.UnpivotClauseMixin[source]

Bases: object

Window Functions

class sqlspec.builder.WindowFunctionBuilder[source]

Bases: object

Helper to fluently construct window function expressions.

__init__(function_name, *function_args)[source]

Case Expressions

class sqlspec.builder.Case[source]

Bases: object

Represent a SQL CASE expression with structured components.

__init__(*ifs, default=None)[source]
class sqlspec.builder.CaseBuilder[source]

Bases: object

Fluent builder for CASE expressions used within SELECT clauses.

Subqueries

class sqlspec.builder.SubqueryBuilder[source]

Bases: object

Helper to build subquery expressions for EXISTS/IN/ANY/ALL operations.

__init__(operation)[source]

Insert

class sqlspec.builder.Insert[source]

Bases: QueryBuilder, ReturningClauseMixin, InsertValuesMixin, InsertFromSelectMixin, InsertIntoClauseMixin, ExplainMixin

Builder for INSERT statements.

Constructs SQL INSERT queries with parameter binding and validation.

__init__(table=None, **kwargs)[source]

Initialize INSERT with optional table.

Parameters:
  • table (str | None) – Target table name

  • **kwargs (Any) – Additional QueryBuilder arguments

get_insert_expression()[source]

Get the insert expression (public API).

Return type:

Insert

values_from_dict(data)[source]

Adds a row of values from a dictionary.

This is a convenience method that automatically sets columns based on the dictionary keys and values based on the dictionary values.

Parameters:

data (Mapping[str, typing.Any]) – A mapping of column names to values.

Return type:

Self

Returns:

The current builder instance for method chaining.

Raises:

SQLBuilderError – If into() has not been called to set the table.

values_from_dicts(data)[source]

Adds multiple rows of values from a sequence of dictionaries.

This is a convenience method for bulk inserts from structured data.

Parameters:

data (Sequence[Mapping[str, typing.Any]]) – A sequence of mappings, each representing a row of data.

Return type:

Self

Returns:

The current builder instance for method chaining.

Raises:

SQLBuilderError – If into() has not been called to set the table, or if dictionaries have inconsistent keys.

on_conflict(*columns)[source]

Adds an ON CONFLICT clause with specified columns.

Parameters:

*columns (str) – Column names that define the conflict. If no columns provided, creates an ON CONFLICT without specific columns (catches all conflicts).

Return type:

ConflictBuilder

Returns:

A ConflictBuilder instance for chaining conflict resolution methods.

Example

```python sql.insert(“users”).values(id=1, name=”John”).on_conflict(

“id”

).do_nothing()

sql.insert(“users”).values(…).on_conflict(

“email”, “username”

).do_update(updated_at=sql.raw(“NOW()”))

sql.insert(“users”).values(…).on_conflict().do_nothing() ```

on_conflict_do_nothing(*columns)[source]

Adds an ON CONFLICT DO NOTHING clause (convenience method).

Parameters:

*columns (str) – Column names that define the conflict. If no columns provided, creates an ON CONFLICT without specific columns.

Return type:

Insert

Returns:

The current builder instance for method chaining.

Note

This is a convenience method. For more control, use on_conflict().do_nothing().

on_duplicate_key_update(**kwargs)[source]

Adds MySQL-style ON DUPLICATE KEY UPDATE clause.

Parameters:

**kwargs (Any) – Column-value pairs to update on duplicate key.

Return type:

Insert

Returns:

The current builder instance for method chaining.

Note

This method creates MySQL-specific ON DUPLICATE KEY UPDATE syntax. For PostgreSQL, use on_conflict() instead.

class sqlspec.builder._insert.ConflictBuilder[source]

Bases: object

Builder for ON CONFLICT clauses in INSERT statements.

Constructs conflict resolution clauses using PostgreSQL-style syntax, which SQLGlot can transpile to other dialects.

__init__(insert_builder, columns)[source]

Initialize ConflictBuilder.

Parameters:
  • insert_builder (Insert) – The parent Insert builder

  • columns (tuple[str, ...]) – Column names that define the conflict

do_nothing()[source]

Add DO NOTHING conflict resolution.

Return type:

Insert

Returns:

The parent Insert builder for method chaining.

Example

```python sql.insert(“users”).values(id=1, name=”John”).on_conflict(

“id”

).do_nothing() ```

do_update(**kwargs)[source]

Add DO UPDATE conflict resolution with SET clauses.

Parameters:

**kwargs (Any) – Column-value pairs to update on conflict.

Return type:

Insert

Returns:

The parent Insert builder for method chaining.

Example

```python sql.insert(“users”).values(id=1, name=”John”).on_conflict(

“id”

).do_update(

name=”Updated Name”, updated_at=sql.raw(“NOW()”)

Update

class sqlspec.builder.Update[source]

Bases: QueryBuilder, WhereClauseMixin, ReturningClauseMixin, UpdateSetClauseMixin, UpdateFromClauseMixin, UpdateTableClauseMixin, ExplainMixin

Builder for UPDATE statements.

Constructs SQL UPDATE statements with parameter binding and validation.

Example

```python update_query = (

Update() .table(“users”) .set_(name=”John Doe”) .set_(email=”john@example.com”) .where(“id = 1”)

)

update_query = (

Update(“users”).set_(name=”John Doe”).where(“id = 1”)

)

update_query = (

Update() .table(“users”) .set_(status=”active”) .where_eq(“id”, 123)

)

update_query = (

Update() .table(“users”, “u”) .set_(name=”Updated Name”) .from_(“profiles”, “p”) .where(“u.id = p.user_id AND p.is_verified = true”)

__init__(table=None, **kwargs)[source]

Initialize UPDATE with optional table.

Parameters:
  • table (str | None) – Target table name

  • **kwargs (Any) – Additional QueryBuilder arguments

join(table, on, alias=None, join_type='INNER')[source]

Add JOIN clause to the UPDATE statement.

Parameters:
  • table (str | Expression | Select) – The table name, expression, or subquery to join.

  • on (str | Expression) – The JOIN condition.

  • alias (str | None) – Optional alias for the joined table.

  • join_type (str) – Type of join (INNER, LEFT, RIGHT, FULL).

Return type:

Self

Returns:

The current builder instance for method chaining.

Raises:

SQLBuilderError – If the current expression is not an UPDATE statement.

build(dialect=None)[source]

Build the UPDATE query with validation.

Parameters:

dialect (Union[str, Dialect, Type[Dialect], None]) – Optional dialect override for SQL generation.

Returns:

The built query with SQL and parameters.

Return type:

BuiltQuery

Raises:

SQLBuilderError – If no table is set or expression is not an UPDATE.

Delete

class sqlspec.builder.Delete[source]

Bases: QueryBuilder, WhereClauseMixin, ReturningClauseMixin, DeleteFromClauseMixin, ExplainMixin

Builder for DELETE statements.

Constructs SQL DELETE statements with parameter binding and validation. Does not support JOIN operations to maintain cross-dialect compatibility.

__init__(table=None, **kwargs)[source]

Initialize DELETE with optional table.

Parameters:
  • table (str | None) – Target table name

  • **kwargs (Any) – Additional QueryBuilder arguments

build(dialect=None)[source]

Build the DELETE query with validation.

Parameters:

dialect (Union[str, Dialect, Type[Dialect], None]) – Optional dialect override for SQL generation.

Returns:

The built query with SQL and parameters.

Return type:

BuiltQuery

Raises:

SQLBuilderError – If the table is not specified.

Merge

class sqlspec.builder.Merge[source]

Bases: QueryBuilder, MergeUsingClauseMixin, MergeOnClauseMixin, MergeMatchedClauseMixin, MergeNotMatchedClauseMixin, MergeIntoClauseMixin, MergeNotMatchedBySourceClauseMixin, ExplainMixin

Builder for MERGE statements.

Constructs SQL MERGE statements (also known as UPSERT in some databases) with parameter binding and validation.

__init__(target_table=None, **kwargs)[source]

Initialize MERGE with optional target table.

Parameters:
  • target_table (str | None) – Target table name

  • **kwargs (Any) – Additional QueryBuilder arguments

build(dialect=None)[source]

Build MERGE statement with dialect validation.

Parameters:

dialect (Union[str, Dialect, Type[Dialect], None]) – Optional dialect override for SQL generation.

Return type:

typing.Any

Returns:

Built statement object.

Explain

class sqlspec.builder.Explain[source]

Bases: object

Builder for EXPLAIN statements with dialect-aware rendering.

Provides a fluent API for constructing EXPLAIN statements with various options that are translated to dialect-specific syntax.

Examples

Basic usage:

explain = Explain(“SELECT * FROM users”).build()

With options:
explain = (

Explain(“SELECT * FROM users”, dialect=”postgres”) .analyze() .format(“json”) .buffers() .build()

)

From QueryBuilder:
explain = (

Explain(select_builder, dialect=”postgres”) .analyze() .verbose() .build()

)

__init__(statement, dialect=None, options=None)[source]

Initialize ExplainBuilder.

Parameters:
  • statement (str | Expression | SQL | SQLBuilderProtocol) – SQL statement to explain (string, expression, SQL object, or builder)

  • dialect (Union[str, Dialect, Type[Dialect], None]) – Target SQL dialect

  • options (ExplainOptions | None) – Initial ExplainOptions (or None for defaults)

analyze(enabled=True)[source]

Enable ANALYZE option (execute statement for real statistics).

Parameters:

enabled (bool) – Whether to enable ANALYZE

Return type:

Self

Returns:

Self for method chaining

verbose(enabled=True)[source]

Enable VERBOSE option (show additional information).

Parameters:

enabled (bool) – Whether to enable VERBOSE

Return type:

Self

Returns:

Self for method chaining

format(fmt)[source]

Set output format.

Parameters:

fmt (ExplainFormat | str) – Output format (TEXT, JSON, XML, YAML, TREE, TRADITIONAL)

Return type:

Self

Returns:

Self for method chaining

costs(enabled=True)[source]

Enable COSTS option (show estimated costs).

Parameters:

enabled (bool) – Whether to show costs

Return type:

Self

Returns:

Self for method chaining

buffers(enabled=True)[source]

Enable BUFFERS option (show buffer usage).

Parameters:

enabled (bool) – Whether to show buffer usage

Return type:

Self

Returns:

Self for method chaining

timing(enabled=True)[source]

Enable TIMING option (show actual timing).

Parameters:

enabled (bool) – Whether to show timing

Return type:

Self

Returns:

Self for method chaining

summary(enabled=True)[source]

Enable SUMMARY option (show summary information).

Parameters:

enabled (bool) – Whether to show summary

Return type:

Self

Returns:

Self for method chaining

memory(enabled=True)[source]

Enable MEMORY option (show memory usage, PostgreSQL 17+).

Parameters:

enabled (bool) – Whether to show memory usage

Return type:

Self

Returns:

Self for method chaining

settings(enabled=True)[source]

Enable SETTINGS option (show configuration parameters, PostgreSQL 12+).

Parameters:

enabled (bool) – Whether to show settings

Return type:

Self

Returns:

Self for method chaining

wal(enabled=True)[source]

Enable WAL option (show WAL usage, PostgreSQL 13+).

Parameters:

enabled (bool) – Whether to show WAL usage

Return type:

Self

Returns:

Self for method chaining

generic_plan(enabled=True)[source]

Enable GENERIC_PLAN option (ignore parameter values, PostgreSQL 16+).

Parameters:

enabled (bool) – Whether to use generic plan

Return type:

Self

Returns:

Self for method chaining

with_options(options)[source]

Replace all options with the provided ExplainOptions.

Parameters:

options (ExplainOptions) – New options to use

Return type:

Self

Returns:

Self for method chaining

property options: ExplainOptions

Get current ExplainOptions.

property dialect: str | Dialect | Type[Dialect] | None

Get current dialect.

property parameters: dict[str, Any]

Get parameters from the underlying statement.

build(dialect=None)[source]

Build the EXPLAIN statement as a SQL object.

Parameters:

dialect (Union[str, Dialect, Type[Dialect], None]) – Optional dialect override

Return type:

SQL

Returns:

SQL object containing the EXPLAIN statement

to_sql(dialect=None)[source]

Build and return just the SQL string.

Parameters:

dialect (Union[str, Dialect, Type[Dialect], None]) – Optional dialect override

Return type:

str

Returns:

EXPLAIN SQL string

__repr__()[source]

String representation.

Return type:

str

Joins

class sqlspec.builder.JoinBuilder[source]

Bases: object

Builder for JOIN operations with fluent syntax.

Example

```python from sqlspec import sql

# sql.left_join_(“posts”).on(“users.id = posts.user_id”) join_clause = sql.left_join_(“posts”).on(

“users.id = posts.user_id”

)

# Or with query builder query = (

sql .select(“users.name”, “posts.title”) .from_(“users”) .join(

sql.left_join_(“posts”).on(

“users.id = posts.user_id”

)

)

__init__(join_type, lateral=False)[source]

Initialize the join builder.

Parameters:
  • join_type (str) – Type of join (inner, left, right, full, cross, lateral)

  • lateral (bool) – Whether this is a LATERAL join

__call__(table, alias=None)[source]

Set the table to join.

Parameters:
  • table (str | Expression) – Table name or expression to join

  • alias (str | None) – Optional alias for the table

Return type:

Self

Returns:

Self for method chaining

as_of(time_expr, kind=None)[source]

Set AS OF clause for the join (Time Travel/Flashback).

Parameters:
  • time_expr (Any) – Timestamp or system time expression

  • kind (str | None) – Type of AS OF clause (SYSTEM TIME, TIMESTAMP). If None, defaults based on dialect.

Return type:

Self

Returns:

Self for method chaining

on(condition)[source]

Set the join condition and build the JOIN expression.

Parameters:

condition (str | Expression) – JOIN condition (e.g., “users.id = posts.user_id”)

Return type:

Expression

Returns:

Complete JOIN expression