SQL#

class polars.SQLContext[source]#

Run SQL queries against DataFrame/LazyFrame data.

__init__(
frames: Mapping[str, DataFrame | LazyFrame] | None = None,
*,
register_globals: bool | int = False,
eager_execution: Literal[False] = False,
**named_frames: DataFrame | LazyFrame,
) None[source]#
__init__(
frames: Mapping[str, DataFrame | LazyFrame] | None = None,
*,
register_globals: bool | int = False,
eager_execution: Literal[True],
**named_frames: DataFrame | LazyFrame,
) None

Initialise a new SQLContext.

Parameters:
frames

A {name:frame, ...} mapping.

register_globals

Register all eager/lazy frames found in the globals, automatically mapping their variable name to a table name. If given an integer then only the most recent “n” frames found will be registered.

eager_execution

Return query execution results as DataFrame instead of LazyFrame. (Note that the query itself is always executed in lazy-mode; this parameter impacts whether execute() returns an eager or lazy result frame).

**named_frames

Named eager/lazy frames, provided as kwargs.

Examples

>>> lf = pl.LazyFrame({"a": [1, 2, 3], "b": ["x", None, "z"]})
>>> res = pl.SQLContext(frame=lf).execute(
...     "SELECT b, a*2 AS two_a FROM frame WHERE b IS NOT NULL"
... )
>>> res.collect()
shape: (2, 2)
┌─────┬───────┐
│ b   ┆ two_a │
│ --- ┆ ---   │
│ str ┆ i64   │
╞═════╪═══════╡
│ x   ┆ 2     │
│ z   ┆ 6     │
└─────┴───────┘

Note: can be used as a context manager.

__enter__() SQLContext[FrameType][source]#

Track currently registered tables on scope entry; supports nested scopes.

__exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) None[source]#

Unregister any tables created within the given scope on context exit.

See also

unregister

Methods#

SQLContext.execute()

Parse the given SQL query and execute it against the registered frame data.

SQLContext.register(name, frame)

Register a single frame as a table, using the given name.

SQLContext.register_globals([n])

Register all frames (lazy or eager) found in the current globals scope.

SQLContext.register_many([frames])

Register multiple eager/lazy frames as tables, using the associated names.

SQLContext.unregister(names)

Unregister one or more eager/lazy frames by name.

SQLContext.tables()

Return a list of the registered table names.