SELECT
In Polars SQL, the SELECT statement is used to retrieve data from a table into a DataFrame. The
basic syntax of a SELECT statement in Polars SQL is as follows:
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, etc. are the columns that you want to select from the table. You can
also use the wildcard * to select all columns. table_name is the name of the table or that you
want to retrieve data from. In the sections below we will cover some of the more common SELECT
variants
df = pl.DataFrame(
{
"country": ["USA", "USA", "USA", "USA", "USA", "Netherlands"],
"city": [
"New York",
"Los Angeles",
"Chicago",
"Houston",
"Phoenix",
"Amsterdam",
],
"population": [8399000, 3997000, 2705000, 2320000, 1680000, 900000],
}
)
ctx = pl.SQLContext(population=df, eager=True)
print(ctx.execute("SELECT * FROM population"))
shape: (6, 3)
βββββββββββββββ¬ββββββββββββββ¬βββββββββββββ
β country β city β population β
β --- β --- β --- β
β str β str β i64 β
βββββββββββββββͺββββββββββββββͺβββββββββββββ‘
β USA β New York β 8399000 β
β USA β Los Angeles β 3997000 β
β USA β Chicago β 2705000 β
β USA β Houston β 2320000 β
β USA β Phoenix β 1680000 β
β Netherlands β Amsterdam β 900000 β
βββββββββββββββ΄ββββββββββββββ΄βββββββββββββ
GROUP BY
The GROUP BY statement is used to group rows in a table by one or more columns and compute
aggregate functions on each group.
result = ctx.execute(
"""
SELECT country, AVG(population) as avg_population
FROM population
GROUP BY country
"""
)
print(result)
shape: (2, 2)
βββββββββββββββ¬βββββββββββββββββ
β country β avg_population β
β --- β --- β
β str β f64 β
βββββββββββββββͺβββββββββββββββββ‘
β USA β 3.8202e6 β
β Netherlands β 900000.0 β
βββββββββββββββ΄βββββββββββββββββ
ORDER BY
The ORDER BY statement is used to sort the result set of a query by one or more columns in
ascending or descending order.
result = ctx.execute(
"""
SELECT city, population
FROM population
ORDER BY population
"""
)
print(result)
shape: (6, 2)
βββββββββββββββ¬βββββββββββββ
β city β population β
β --- β --- β
β str β i64 β
βββββββββββββββͺβββββββββββββ‘
β Amsterdam β 900000 β
β Phoenix β 1680000 β
β Houston β 2320000 β
β Chicago β 2705000 β
β Los Angeles β 3997000 β
β New York β 8399000 β
βββββββββββββββ΄βββββββββββββ
JOIN
income = pl.DataFrame(
{
"country": [
"USA",
"USA",
"USA",
"USA",
"Netherlands",
"Netherlands",
"Netherlands",
],
"city": [
"New York",
"Los Angeles",
"Chicago",
"Houston",
"Amsterdam",
"Rotterdam",
"Utrecht",
],
"income": [55000, 62000, 48000, 52000, 42000, 38000, 41000],
}
)
ctx.register_many(income=income)
result = ctx.execute(
"""
SELECT income.*, population.population
FROM population
LEFT JOIN income ON population.city = income.city
"""
)
print(result)
shape: (6, 4)
βββββββββββββββ¬ββββββββββββββ¬βββββββββ¬βββββββββββββ
β country β city β income β population β
β --- β --- β --- β --- β
β str β str β i64 β i64 β
βββββββββββββββͺββββββββββββββͺβββββββββͺβββββββββββββ‘
β USA β Los Angeles β 62000 β 3997000 β
β USA β New York β 55000 β 8399000 β
β USA β Houston β 52000 β 2320000 β
β USA β Chicago β 48000 β 2705000 β
β Netherlands β Amsterdam β 42000 β 900000 β
β null β null β null β 1680000 β
βββββββββββββββ΄ββββββββββββββ΄βββββββββ΄βββββββββββββ
Functions
Polars provides a wide range of SQL functions, including:
- Mathematical functions:
ABS,EXP,LOG,ASIN,ACOS,ATAN, etc. - String functions:
LOWER,UPPER,LTRIM,RTRIM,STARTS_WITH,ENDS_WITH. - Aggregation functions:
SUM,AVG,MIN,MAX,COUNT,STDDEV,FIRSTetc. - Array functions:
EXPLODE,UNNEST,ARRAY_SUM,ARRAY_REVERSE, etc.
For a full list of supported functions go the API documentation. The example below demonstrates how to use a function in a query
result = ctx.execute(
"""
SELECT city, population
FROM population
WHERE STARTS_WITH(country,'U')
"""
)
print(result)
shape: (5, 2)
βββββββββββββββ¬βββββββββββββ
β city β population β
β --- β --- β
β str β i64 β
βββββββββββββββͺβββββββββββββ‘
β New York β 8399000 β
β Los Angeles β 3997000 β
β Chicago β 2705000 β
β Houston β 2320000 β
β Phoenix β 1680000 β
βββββββββββββββ΄βββββββββββββ
Table Functions
In the examples earlier we first generated a DataFrame which we registered in the SQLContext.
Polars also support directly reading from CSV, Parquet, JSON and IPC in your SQL query using table
functions read_xxx.
result = ctx.execute(
"""
SELECT *
FROM read_csv('docs/assets/data/iris.csv')
"""
)
print(result)
shape: (150, 5)
ββββββββββββββββ¬ββββββββββββββ¬βββββββββββββββ¬ββββββββββββββ¬ββββββββββββ
β sepal_length β sepal_width β petal_length β petal_width β species β
β --- β --- β --- β --- β --- β
β f64 β f64 β f64 β f64 β str β
ββββββββββββββββͺββββββββββββββͺβββββββββββββββͺββββββββββββββͺββββββββββββ‘
β 5.1 β 3.5 β 1.4 β 0.2 β Setosa β
β 4.9 β 3.0 β 1.4 β 0.2 β Setosa β
β 4.7 β 3.2 β 1.3 β 0.2 β Setosa β
β 4.6 β 3.1 β 1.5 β 0.2 β Setosa β
β 5.0 β 3.6 β 1.4 β 0.2 β Setosa β
β β¦ β β¦ β β¦ β β¦ β β¦ β
β 6.7 β 3.0 β 5.2 β 2.3 β Virginica β
β 6.3 β 2.5 β 5.0 β 1.9 β Virginica β
β 6.5 β 3.0 β 5.2 β 2.0 β Virginica β
β 6.2 β 3.4 β 5.4 β 2.3 β Virginica β
β 5.9 β 3.0 β 5.1 β 1.8 β Virginica β
ββββββββββββββββ΄ββββββββββββββ΄βββββββββββββββ΄ββββββββββββββ΄ββββββββββββ
The path can also be a glob, or a list of paths or globs, as in
read_parquet(['a.parquet', 'b.parquet']).
read_csv also accepts named options after the path, with the same names and meaning as the options
of scan_csv. Write them as name => value (or name := value):
result = ctx.execute(
"""
SELECT *
FROM read_csv('docs/assets/data/iris.csv', infer_schema => false, skip_rows_after_header => 147)
"""
)
print(result)
shape: (3, 5)
ββββββββββββββββ¬ββββββββββββββ¬βββββββββββββββ¬ββββββββββββββ¬ββββββββββββ
β sepal_length β sepal_width β petal_length β petal_width β species β
β --- β --- β --- β --- β --- β
β str β str β str β str β str β
ββββββββββββββββͺββββββββββββββͺβββββββββββββββͺββββββββββββββͺββββββββββββ‘
β 6.5 β 3 β 5.2 β 2 β Virginica β
β 6.2 β 3.4 β 5.4 β 2.3 β Virginica β
β 5.9 β 3 β 5.1 β 1.8 β Virginica β
ββββββββββββββββ΄ββββββββββββββ΄βββββββββββββββ΄ββββββββββββββ΄ββββββββββββ
The supported options are:
- Layout:
has_header,separator,quote_char,comment_prefix,skip_rows,skip_rows_after_header,skip_lines,encoding. - Names and types:
new_columns,schema,schema_overrides,infer_schema,infer_schema_length,infer_schema_files,try_parse_dates,decimal_comma. - Values and errors:
null_values,ignore_errors. - Ragged rows and multiple files:
truncate_ragged_lines,missing_columns,extra_columns,include_file_paths.
Values are SQL literals:
NULLstands forNone, as ininfer_schema_length => NULLto infer the schema from the whole file, orquote_char => NULLto turn quoting off.- Lists use brackets:
new_columns => ['a', 'b']. schema,schema_overridesand per-columnnull_valuestake a dictionary, with types written as SQL type names:schema_overrides => {'id': 'INT', 'name': 'VARCHAR'}.schema_overridesalso accepts a list of type names, by position.- Escape sequences need an
E''string, as inseparator => E'\t'for tab-separated files.
Unlike scan_csv, read_csv tries to parse dates by default (try_parse_dates => true).
Some options are unstable: those marked as such in the
scan_csv API
reference are unstable in read_csv too, and may be changed at any point without it being
considered a breaking change.
read_ndjson reads newline-delimited JSON (one object per line) and accepts the options of
scan_ndjson in the same way: schema, schema_overrides, infer_schema_length, ignore_errors
and include_file_paths.
result = ctx.execute(
"""
SELECT *
FROM read_ndjson('docs/assets/data/orders.ndjson', schema_overrides => {'date': 'DATE'})
"""
)
print(result)
shape: (3, 4)
βββββββ¬βββββββββββββ¬ββββββββββββββββββ¬ββββββββββββ
β id β date β customer β items β
β --- β --- β --- β --- β
β i64 β date β struct[2] β list[i64] β
βββββββͺβββββββββββββͺββββββββββββββββββͺββββββββββββ‘
β 1 β 2024-03-01 β {"Ann","Ghent"} β [3, 7] β
β 2 β 2024-03-04 β {"Bo","Leuven"} β [1] β
β 3 β 2024-03-09 β {"Cy","Ghent"} β [2, 5, 8] β
βββββββ΄βββββββββββββ΄ββββββββββββββββββ΄ββββββββββββ
- The schema is inferred from the first 100 rows, so a key that first appears later is dropped. Use
infer_schema_length => NULLto infer it from the whole file. - A nested object read as
'VARCHAR'keeps its JSON text. read_jsonreads the same files, but takes only the path. For a JSON array or a pretty-printed JSON document, usepl.read_jsoninstead.
read_parquet accepts the options of scan_parquet in the same way: schema, missing_columns,
extra_columns, hive_partitioning, hive_schema, try_parse_hive_dates and
include_file_paths.
result = ctx.execute(
"""
SELECT id, bool_col, path
FROM read_parquet('docs/assets/data/alltypes_plain.parquet', include_file_paths => 'path')
LIMIT 3
"""
)
print(result)
shape: (3, 3)
βββββββ¬βββββββββββ¬ββββββββββββββββββββββββββββββββββ
β id β bool_col β path β
β --- β --- β --- β
β i32 β bool β str β
βββββββͺβββββββββββͺββββββββββββββββββββββββββββββββββ‘
β 4 β true β docs/assets/data/alltypes_plaiβ¦ β
β 5 β false β docs/assets/data/alltypes_plaiβ¦ β
β 6 β true β docs/assets/data/alltypes_plaiβ¦ β
βββββββ΄βββββββββββ΄ββββββββββββββββββββββββββββββββββ
- Unlike
scan_parquet,read_parquetreads hive partitions by default when given one path, for a glob or a single file too: a path such asdata/k=1/part.parquetadds a columnk. Everykey=valuefolder in such a path counts, so an absolute path can also pick up columns from its parent folders. A list of paths reads them only when it is a single directory, as inscan_parquet. Sethive_partitioningtotrueorfalseto choose either way. - When reading several files, the first one defines the columns, unless
schemais given. Usemissing_columns => 'insert'andextra_columns => 'ignore'for files that differ from it. - As for
read_csv, options marked unstable in thescan_parquetAPI reference are unstable inread_parquettoo.
read_ipc accepts the options of scan_ipc in the same way: hive_partitioning, hive_schema,
try_parse_hive_dates and include_file_paths.
pl.read_csv("docs/assets/data/iris.csv").write_ipc("docs/assets/data/iris.feather")
result = ctx.execute(
"""
SELECT species, sepal_length, path
FROM read_ipc('docs/assets/data/iris.feather', include_file_paths => 'path')
LIMIT 3
"""
)
print(result)
shape: (3, 3)
βββββββββββ¬βββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β species β sepal_length β path β
β --- β --- β --- β
β str β f64 β str β
βββββββββββͺβββββββββββββββͺββββββββββββββββββββββββββββββββ‘
β Setosa β 5.1 β docs/assets/data/iris.feather β
β Setosa β 4.9 β docs/assets/data/iris.feather β
β Setosa β 4.7 β docs/assets/data/iris.feather β
βββββββββββ΄βββββββββββββββ΄ββββββββββββββββββββββββββββββββ
- Hive partitions are read as for
read_parquet: by default for one path, and for a list only when it is a single directory. - As for
read_parquet, options marked unstable in thescan_ipcAPI reference are unstable inread_ipctoo.