Python API#


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.

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

Initialize a new SQLContext.


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


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.


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 eager/lazy frames, provided as kwargs.


>>> 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.

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



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.


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


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


Unregister one or more eager/lazy frames by name.


Return a list of the registered table names.