Python API#

SQLContext#

Polars provides a SQL interface to query frame data; this is available through the SQLContext object, detailed below, as well as the DataFrame sql() and LazyFrame sql() methods (which make use of SQLContext internally).

class polars.SQLContext[source]#

Run SQL queries against DataFrame/LazyFrame data.

__init__(
frames: Mapping[str, CompatibleFrameType | None] | None = None,
*,
register_globals: bool | int = False,
eager: bool = False,
**named_frames: CompatibleFrameType | None,
) None[source]#

Initialize a new SQLContext.

Parameters:
frames

A {name:frame, ...} mapping which can include Polars frames and pandas DataFrames, Series and pyarrow Table and RecordBatch objects.

register_globals

Register compatible objects (polars DataFrame, LazyFrame, and Series) found in the globals, automatically mapping their variable name to a table name. To register other objects (pandas/pyarrow data) pass them explicitly, or call the execute_global classmethod. If given an integer then only the most recent “n” objects found will be registered.

eager

If True, returns 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(query, *[, eager])

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, all_compatible])

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.