Query Clauses#

Function

Description

SELECT

Retrieves specific column data from one or more tables.

DISTINCT

Returns unique values from a query.

DISTINCT ON

Returns the first row for each unique combination of the specified columns.

FROM

Specify the table(s) from which to retrieve or delete data. Can also be used as the leading clause.

JOIN

Combine rows from two or more tables based on a related column.

PIVOT

Turn the values of a column into columns, aggregating the rows of each.

UNPIVOT

Turn columns into rows of a name column and a value column.

WHERE

Filter rows returned from the query based on the given conditions.

GROUP BY

Aggregate row values based on one or more key columns.

GROUP BY ALL

Automatically group by all non-aggregate columns in the projection.

HAVING

Filter groups in a GROUP BY based on the given conditions.

WINDOW

Define named window specifications for window functions.

QUALIFY

Filter rows in a query based on window function results.

ORDER BY

Sort the query result based on one or more specified columns.

ORDER BY ALL

Sort the query result by all selected columns.

OFFSET

Skip a specified number of rows.

LIMIT

Specify the number of rows returned.

FETCH

Limit the number of rows returned (alternative to LIMIT).

SELECT#

Select the columns to be returned by the query.

Example:

df = pl.DataFrame(
  {
    "a": [1, 2, 3],
    "b": ["zz", "yy", "xx"],
  }
)
df.sql("""
  SELECT a, b FROM self
""")
# shape: (3, 2)
# ┌─────┬─────┐
# │ a   ┆ b   │
# │ --- ┆ --- │
# │ i64 ┆ str │
# ╞═════╪═════╡
# │ 1   ┆ zz  │
# │ 2   ┆ yy  │
# │ 3   ┆ xx  │
# └─────┴─────┘

A SELECT item can read the alias of an item before it. An input column of the same name comes before the alias. A window function cannot read an alias that holds a window function or RANDOM().

df.sql("""
  SELECT a * 2 AS x, x + 1 AS y FROM self
""")
# shape: (3, 2)
# ┌─────┬─────┐
# │ x   ┆ y   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 2   ┆ 3   │
# │ 4   ┆ 5   │
# │ 6   ┆ 7   │
# └─────┴─────┘

Note

Use of bare FROM tbl is also supported, as shorthand for SELECT * FROM tbl; see the FROM clause for more detail.

DISTINCT#

Returns unique values from a query.

Example:

df = pl.DataFrame(
  {
    "a": [1, 2, 2, 1],
    "b": ["xx", "yy", "yy", "xx"],
  }
)
df.sql("""
  SELECT DISTINCT * FROM self
""")
# shape: (2, 2)
# ┌─────┬─────┐
# │ a   ┆ b   │
# │ --- ┆ --- │
# │ i64 ┆ str │
# ╞═════╪═════╡
# │ 1   ┆ xx  │
# │ 2   ┆ yy  │
# └─────┴─────┘

DISTINCT ON#

Returns the first row for each unique combination of the specified columns. When used with ORDER BY, this keeps the first row per group according to the given ordering.

Note

DISTINCT ON only supports column names (not arbitrary expressions).

Example:

df = pl.DataFrame(
  {
    "category": ["A", "A", "A", "B", "B", "B"],
    "value": [30, 10, 20, 50, 40, 60],
    "label": ["x", "y", "z", "p", "q", "r"],
  }
)
df.sql("""
  SELECT DISTINCT ON (category)
    category,
    value,
    label
  FROM self
  ORDER BY category, value DESC
""")
# shape: (2, 3)
# ┌──────────┬───────┬───────┐
# │ category ┆ value ┆ label │
# │ ---      ┆ ---   ┆ ---   │
# │ str      ┆ i64   ┆ str   │
# ╞══════════╪═══════╪═══════╡
# │ A        ┆ 30    ┆ x     │
# │ B        ┆ 60    ┆ r     │
# └──────────┴───────┴───────┘

FROM#

Specifies the table(s) from which to retrieve or delete data.

In addition to the usual SELECT ... FROM tbl syntax, the FROM clause can also be used as the leading clause in a query, supporting the following variations:

  • FROM tbl - equivalent to SELECT * FROM tbl.

  • FROM tbl SELECT ... - a reordered SELECT with explicit projections.

  • FROM tbl1, tbl2 ... - multiple comma-separated tables; see the JOIN clause for implicit join syntax.

Example:

df = pl.DataFrame(
  {
    "a": [1, 2, 3],
    "b": ["zz", "yy", "xx"],
  }
)
for query in (
  "SELECT * FROM self",
  "FROM self SELECT *",
  "FROM self",
):
  df.sql(query)
  # shape: (3, 2)
  # ┌─────┬─────┐
  # │ a   ┆ b   │
  # │ --- ┆ --- │
  # │ i64 ┆ str │
  # ╞═════╪═════╡
  # │ 1   ┆ zz  │
  # │ 2   ┆ yy  │
  # │ 3   ┆ xx  │
  # └─────┴─────┘

Using FROM as the leading clause, with SELECT:

df.sql("""
  FROM self SELECT b, a
""")
# shape: (3, 2)
# ┌─────┬─────┐
# │ b   ┆ a   │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ zz  ┆ 1   │
# │ yy  ┆ 2   │
# │ xx  ┆ 3   │
# └─────┴─────┘

Files: a path in single quotes is read as a file when it ends in the extension of a file format: .csv, .parquet, .ipc / .arrow / .feather, or .ndjson / .jsonl. The path can be a glob or a cloud URL, and a leading ~ is the home directory. The file is read with the defaults of the read_csv, read_parquet, read_ipc or read_ndjson table function; call that function to pass options, or to read a path that does not end in such an extension. A table of the same name comes first, and any other name in quotes is looked up as a table. To run untrusted SQL, turn off reading and writing files and URLs with SQLContext(allow_file_reads=False, allow_file_writes=False).

SELECT * FROM 'data/events.parquet'
SELECT region, COUNT(*) FROM 'data/sales_*.csv' GROUP BY region

Time travel: a table of an attached catalog (see SQLContext.register_catalog()) can be read as of a snapshot, a branch or tag, or a time. The clause follows the table name or its alias, and takes a literal. Tags and branches are made with ALTER TABLE.

  • [FOR] VERSION AS OF <version> or AT (VERSION => <version>): an integer is a snapshot id, a string a branch or tag.

  • [FOR] TIMESTAMP AS OF <ts>, FOR SYSTEM_TIME AS OF <ts> or AT (TIMESTAMP => <ts>): the snapshot current on the main branch at that time, by the commit times in the table’s metadata log. A time without a time zone is UTC. For a UTC offset, use TIMESTAMPTZ '...' or a string.

Every spelling means the same. The snapshot’s schema is used. A time is refused when its snapshot has expired, or when it is older than the metadata log (write.metadata.previous-versions-max). Only reads can travel: a MERGE that reads its own table as of a version uses those rows as they were, so it can bring back deleted rows or overwrite newer values.

SELECT * FROM lake.sales.orders FOR VERSION AS OF 4348393417211393838
SELECT * FROM lake.sales.orders FOR VERSION AS OF 'end-of-quarter'
SELECT * FROM lake.sales.orders o AT (TIMESTAMP => TIMESTAMP '2026-01-01 00:00:00')

JOIN#

Combines rows from two or more tables based on a related column.

Join Types

  • CROSS JOIN

  • [NATURAL] FULL [OUTER] JOIN

  • [NATURAL] INNER [OUTER] JOIN

  • [NATURAL] LEFT [OUTER] JOIN

  • [NATURAL] RIGHT [OUTER] JOIN

  • [LEFT | RIGHT] ANTI JOIN

  • [LEFT | RIGHT] SEMI JOIN

  • ASOF JOIN ... MATCH_CONDITION (...) (see ASOF joins)

  • POSITIONAL JOIN (see positional joins)

Example:

df1 = pl.DataFrame(
  {
    "foo": [1, 2, 3],
    "ham": ["a", "b", "c"],
  }
)
df2 = pl.DataFrame(
  {
    "apple": ["x", "y", "z"],
    "ham": ["a", "b", "d"],
  }
)
pl.sql("""
  SELECT foo, apple, COALESCE(df1.ham, df2.ham) AS ham
  FROM df1 FULL JOIN df2
  USING (ham)
""").collect()
# shape: (4, 3)
# ┌──────┬───────┬─────┐
# │ foo  ┆ apple ┆ ham │
# │ ---  ┆ ---   ┆ --- │
# │ i64  ┆ str   ┆ str │
# ╞══════╪═══════╪═════╡
# │ 1    ┆ x     ┆ a   │
# │ 2    ┆ y     ┆ b   │
# │ null ┆ z     ┆ d   │
# │ 3    ┆ null  ┆ c   │
# └──────┴───────┴─────┘

pl.sql("""
  SELECT * FROM df1 NATURAL INNER JOIN df2
""").collect()
# shape: (2, 3)
# ┌─────┬───────┬─────┐
# │ foo ┆ apple ┆ ham │
# │ --- ┆ ---   ┆ --- │
# │ i64 ┆ str   ┆ str │
# ╞═════╪═══════╪═════╡
# │ 1   ┆ x     ┆ a   │
# │ 2   ┆ y     ┆ b   │
# └─────┴───────┴─────┘

Implicit (comma) joins

Tables can also be combined using the older comma-separated FROM syntax, with the join conditions given in the WHERE clause. Cross-table equality predicates are lifted into the join keys (resulting in an INNER join), while any remaining predicates are applied as filters. If no predicate bridges two tables they are combined as a CROSS JOIN.

pl.sql("""
  SELECT foo, apple, df1.ham
  FROM df1, df2
  WHERE df1.ham = df2.ham
""").collect()
# shape: (2, 3)
# ┌─────┬───────┬─────┐
# │ foo ┆ apple ┆ ham │
# │ --- ┆ ---   ┆ --- │
# │ i64 ┆ str   ┆ str │
# ╞═════╪═══════╪═════╡
# │ 1   ┆ x     ┆ a   │
# │ 2   ┆ y     ┆ b   │
# └─────┴───────┴─────┘

Note

For an implicit join, the comparison columns should be qualified with their table name or alias on both sides (eg: WHERE df1.ham = df2.ham). Unqualified comparisons are treated as ordinary filters rather than join keys.

Non-equi join conditions

Join conditions are not restricted to equality; the <, <=, >, >=, and != operators are also supported (in both explicit ON clauses and implicit joins), and can be freely combined with equi-conditions using AND.

df3 = pl.DataFrame({"value": [5, 25, 45]})
df4 = pl.DataFrame({"lo": [0, 20], "hi": [20, 50]})
pl.sql("""
  SELECT value, lo, hi
  FROM df3 INNER JOIN df4
  ON df3.value >= df4.lo AND df3.value < df4.hi
""").collect()
# shape: (3, 3)
# ┌───────┬─────┬─────┐
# │ value ┆ lo  ┆ hi  │
# │ ---   ┆ --- ┆ --- │
# │ i64   ┆ i64 ┆ i64 │
# ╞═══════╪═════╪═════╡
# │ 5     ┆ 0   ┆ 20  │
# │ 25    ┆ 20  ┆ 50  │
# │ 45    ┆ 20  ┆ 50  │
# └───────┴─────┴─────┘

LATERAL derived tables

A derived table in a join, or in a comma-separated FROM, can read the columns of the tables before it. The LATERAL keyword is optional. Some shapes are not supported yet, such as a derived table with LIMIT or a window function.

customers = pl.DataFrame({"name": ["a", "b", "c"]})
orders = pl.DataFrame({"customer": ["a", "a", "b"], "amount": [10, 20, 5]})
pl.sql("""
  SELECT name, s.total, s.n
  FROM customers, LATERAL (
    SELECT SUM(amount) AS total, COUNT(*) AS n
    FROM orders
    WHERE orders.customer = customers.name
  ) s
  ORDER BY name
""").collect()
# shape: (3, 3)
# ┌──────┬───────┬─────┐
# │ name ┆ total ┆ n   │
# │ ---  ┆ ---   ┆ --- │
# │ str  ┆ i64   ┆ i64 │
# ╞══════╪═══════╪═════╡
# │ a    ┆ 30    ┆ 2   │
# │ b    ┆ 5     ┆ 1   │
# │ c    ┆ null  ┆ 0   │
# └──────┴───────┴─────┘

ASOF joins

An ASOF JOIN pairs each row of the left table with the closest row of the right table that satisfies the MATCH_CONDITION, which compares one column (or expression) of each table with >=, >, <=, or <. An optional ON (or USING) clause gives equality conditions that matching rows must also satisfy. Every left row is kept; if there is no matching right row, the right columns are null.

population = pl.DataFrame(
  {
    "date": [date(2016, 3, 1), date(2018, 8, 1), date(2019, 1, 1)],
    "population": [82.19, 82.66, 83.12],
  }
)
gdp = pl.DataFrame(
  {
    "date": [date(2016, 1, 1), date(2017, 1, 1), date(2018, 1, 1), date(2019, 1, 1)],
    "gdp": [4164, 4411, 4566, 4696],
  }
)
pl.sql("""
  SELECT p.date, population, gdp
  FROM population p
  ASOF JOIN gdp g MATCH_CONDITION (p.date >= g.date)
  ORDER BY p.date
""").collect()
# shape: (3, 3)
# ┌────────────┬────────────┬──────┐
# │ date       ┆ population ┆ gdp  │
# │ ---        ┆ ---        ┆ ---  │
# │ date       ┆ f64        ┆ i64  │
# ╞════════════╪════════════╪══════╡
# │ 2016-03-01 ┆ 82.19      ┆ 4164 │
# │ 2018-08-01 ┆ 82.66      ┆ 4566 │
# │ 2019-01-01 ┆ 83.12      ┆ 4696 │
# └────────────┴────────────┴──────┘

Positional joins

A POSITIONAL JOIN pairs the rows of two tables by their position: the first row with the first row, and so on. It takes no join condition. If one table has fewer rows, its columns are null for the remaining rows. The result depends on the order of the rows, so join tables whose order is known, such as tables that were not joined or grouped first.

df1 = pl.DataFrame({"foo": [1, 2, 3]})
df2 = pl.DataFrame({"bar": ["a", "b"]})
pl.sql("SELECT * FROM df1 POSITIONAL JOIN df2").collect()
# shape: (3, 2)
# ┌─────┬──────┐
# │ foo ┆ bar  │
# │ --- ┆ ---  │
# │ i64 ┆ str  │
# ╞═════╪══════╡
# │ 1   ┆ a    │
# │ 2   ┆ b    │
# │ 3   ┆ null │
# └─────┴──────┘

PIVOT#

Turns the values of a column into columns. <table> PIVOT (<aggregates> FOR <column> IN (<values>)) groups the rows by the columns of the table that the PIVOT doesn’t read, and gives a column per value with the aggregate over the rows of the group whose <column> has that value (a NULL value matches NULL).

A column is named by its value, or by the value’s alias. With an aliased aggregate, or more than one aggregate, it is named <value>_<aggregate alias> (or <value>_<aggregate> for an aggregate without an alias). The values must be given as a list.

Example:

sales = pl.DataFrame(
  {
    "region": ["north", "north", "south", "south"],
    "quarter": ["q1", "q2", "q1", "q2"],
    "amount": [10, 20, 30, 40],
  }
)
pl.sql("""
  SELECT * FROM sales
  PIVOT (SUM(amount) FOR quarter IN ('q1', 'q2'))
  ORDER BY region
""").collect()
# shape: (2, 3)
# ┌────────┬─────┬─────┐
# │ region ┆ q1  ┆ q2  │
# │ ---    ┆ --- ┆ --- │
# │ str    ┆ i64 ┆ i64 │
# ╞════════╪═════╪═════╡
# │ north  ┆ 10  ┆ 20  │
# │ south  ┆ 30  ┆ 40  │
# └────────┴─────┴─────┘

UNPIVOT#

Turns columns into rows. <table> UNPIVOT (<value> FOR <name> IN (<columns>)) gives, for each row and listed column, a row with the other columns, the column’s name (or its alias) in <name>, and its value in <value>. Rows whose value is null are left out, unless UNPIVOT INCLUDE NULLS is used.

Example:

wide = pl.DataFrame(
  {
    "region": ["north", "south"],
    "q1": [10, 30],
    "q2": [20, None],
  }
)
pl.sql("""
  SELECT * FROM wide
  UNPIVOT (amount FOR quarter IN (q1, q2))
  ORDER BY region, quarter
""").collect()
# shape: (3, 3)
# ┌────────┬─────────┬────────┐
# │ region ┆ quarter ┆ amount │
# │ ---    ┆ ---     ┆ ---    │
# │ str    ┆ str     ┆ i64    │
# ╞════════╪═════════╪════════╡
# │ north  ┆ q1      ┆ 10     │
# │ north  ┆ q2      ┆ 20     │
# │ south  ┆ q1      ┆ 30     │
# └────────┴─────────┴────────┘

WHERE#

Filter rows returned from the query based on the given conditions.

df = pl.DataFrame(
  {
    "foo": [30, 40, 50],
    "ham": ["a", "b", "c"],
  }
)
df.sql("""
  SELECT * FROM self WHERE foo > 42
""")
# shape: (1, 2)
# ┌─────┬─────┐
# │ foo ┆ ham │
# │ --- ┆ --- │
# │ i64 ┆ str │
# ╞═════╪═════╡
# │ 50  ┆ c   │
# └─────┴─────┘

GROUP BY#

Group rows that have the same values in specified columns into summary rows.

Example:

df = pl.DataFrame(
    {
      "foo": ["a", "b", "b"],
      "bar": [10, 20, 30],
    }
  )
df.sql("""
  SELECT foo, SUM(bar) FROM self GROUP BY foo
""")
# shape: (2, 2)
# ┌─────┬─────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ b   ┆ 50  │
# │ a   ┆ 10  │
# └─────┴─────┘

GROUP BY ALL#

Automatically groups by all columns in the SELECT projection that are not wrapped in an aggregate function, a window expression, or a literal value. This is a convenience shorthand that avoids having to manually repeat column names in the GROUP BY clause.

Example:

df = pl.DataFrame(
  {
    "category": ["A", "A", "B", "B"],
    "sub": ["x", "y", "x", "y"],
    "value": [10, 20, 30, 40],
  }
)
df.sql("""
  SELECT category, sub, SUM(value) AS total
  FROM self
  GROUP BY ALL
  ORDER BY category, sub
""")
# shape: (4, 3)
# ┌──────────┬─────┬───────┐
# │ category ┆ sub ┆ total │
# │ ---      ┆ --- ┆ ---   │
# │ str      ┆ str ┆ i64   │
# ╞══════════╪═════╪═══════╡
# │ A        ┆ x   ┆ 10    │
# │ A        ┆ y   ┆ 20    │
# │ B        ┆ x   ┆ 30    │
# │ B        ┆ y   ┆ 40    │
# └──────────┴─────┴───────┘

HAVING#

Filter groups in a GROUP BY based on the given conditions.

df = pl.DataFrame(
      {
      "foo": ["a", "b", "b", "c"],
      "bar": [10, 20, 30, 40],
    }
  )
df.sql("""
  SELECT foo, SUM(bar) FROM self GROUP BY foo HAVING bar >= 40
""")
# shape: (2, 2)
# ┌─────┬─────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ c   ┆ 40  │
# │ b   ┆ 50  │
# └─────┴─────┘

WINDOW#

Define named window specifications that can be referenced by window functions.

Example:

One window, multiple expressions:

df = pl.DataFrame({
    "id": [1, 2, 3, 4, 5, 6, 7],
    "category": ["A", "A", "A", "B", "B", "B", "C"],
    "value": [20, 10, 30, 15, 50, 30, 35],
})
df.sql("""
  SELECT
    category,
    value,
    SUM(value) OVER w AS "w:sum",
    MIN(value) OVER w AS "w:min",
    AVG(value) OVER w AS "w:avg",
  FROM self
  WINDOW w AS (PARTITION BY category ORDER BY value)
  ORDER BY category, value
""")
# shape: (7, 5)
# ┌──────────┬───────┬───────┬───────┬───────────┐
# │ category ┆ value ┆ w:sum ┆ w:min ┆ w:avg     │
# │ ---      ┆ ---   ┆ ---   ┆ ---   ┆ ---       │
# │ str      ┆ i64   ┆ i64   ┆ i64   ┆ f64       │
# ╞══════════╪═══════╪═══════╪═══════╪═══════════╡
# │ A        ┆ 10    ┆ 10    ┆ 10    ┆ 20.0      │
# │ A        ┆ 20    ┆ 30    ┆ 10    ┆ 20.0      │
# │ A        ┆ 30    ┆ 60    ┆ 10    ┆ 20.0      │
# │ B        ┆ 15    ┆ 15    ┆ 15    ┆ 31.666667 │
# │ B        ┆ 30    ┆ 45    ┆ 15    ┆ 31.666667 │
# │ B        ┆ 50    ┆ 95    ┆ 15    ┆ 31.666667 │
# │ C        ┆ 35    ┆ 35    ┆ 35    ┆ 35.0      │
# └──────────┴───────┴───────┴───────┴───────────┘

Multiple windows, multiple expressions:

df.sql("""
  SELECT
    category,
    value,
    AVG(value) OVER w1 AS category_avg,
    SUM(value) OVER w2 AS running_value,
    COUNT(*) OVER w3 AS total_count
  FROM self
  WINDOW
    w1 AS (PARTITION BY category),
    w2 AS (ORDER BY value),
    w3 AS ()
  ORDER BY category, value
""")
# shape: (7, 5)
# ┌──────────┬───────┬──────────────┬───────────────┬─────────────┐
# │ category ┆ value ┆ category_avg ┆ running_value ┆ total_count │
# │ ---      ┆ ---   ┆ ---          ┆ ---           ┆ ---         │
# │ str      ┆ i64   ┆ f64          ┆ i64           ┆ u32         │
# ╞══════════╪═══════╪══════════════╪═══════════════╪═════════════╡
# │ A        ┆ 10    ┆ 20.0         ┆ 10            ┆ 7           │
# │ A        ┆ 20    ┆ 20.0         ┆ 45            ┆ 7           │
# │ A        ┆ 30    ┆ 20.0         ┆ 75            ┆ 7           │
# │ B        ┆ 15    ┆ 31.666667    ┆ 25            ┆ 7           │
# │ B        ┆ 30    ┆ 31.666667    ┆ 105           ┆ 7           │
# │ B        ┆ 50    ┆ 31.666667    ┆ 190           ┆ 7           │
# │ C        ┆ 35    ┆ 35.0         ┆ 140           ┆ 7           │
# └──────────┴───────┴──────────────┴───────────────┴─────────────┘

QUALIFY#

Filter rows in a query based on window function results. It runs after GROUP BY and HAVING, and can use columns that are not in the SELECT list.

Example:

Constrain the result to the top (largest) two values per category:

df = pl.DataFrame({
    "id": [100, 200, 300, 400, 500, 600, 700, 800],
    "category": ["A", "A", "A", "B", "B", "B", "B", "A"],
    "value": [20, 15, 30, 25, 15, 50, 35, 45],
})
df.sql("""
  SELECT
    id,
    category,
    value
  FROM self
  WINDOW w AS (PARTITION BY category ORDER BY value DESC)
  QUALIFY ROW_NUMBER() OVER w <= 2
  ORDER BY category, value DESC
""")
# shape: (4, 3)
# ┌─────┬──────────┬───────┐
# │ id  ┆ category ┆ value │
# │ --- ┆ ---      ┆ ---   │
# │ i64 ┆ str      ┆ i64   │
# ╞═════╪══════════╪═══════╡
# │ 800 ┆ A        ┆ 45    │
# │ 300 ┆ A        ┆ 30    │
# │ 600 ┆ B        ┆ 50    │
# │ 700 ┆ B        ┆ 35    │
# └─────┴──────────┴───────┘

ORDER BY#

Sort the query result based on one or more specified columns.

Example:

df = pl.DataFrame(
  {
    "foo": ["b", "a", "c", "b"],
    "bar": [20, 10, 40, 30],
  }
)
df.sql("""
  SELECT foo, bar FROM self ORDER BY bar DESC
""")
# shape: (4, 2)
# ┌─────┬─────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ c   ┆ 40  │
# │ b   ┆ 30  │
# │ b   ┆ 20  │
# │ a   ┆ 10  │
# └─────┴─────┘

ORDER BY ALL#

Sort the query result by all selected columns. This is a convenience shorthand that avoids repeating column names. The ASC/DESC and NULLS FIRST/NULLS LAST modifiers apply to every column.

Example:

df = pl.DataFrame(
  {
    "a": ["x", "y", "x", "y"],
    "b": [30, 10, 20, 40],
  }
)
df.sql("""
  SELECT a, b FROM self ORDER BY ALL
""")
# shape: (4, 2)
# ┌─────┬─────┐
# │ a   ┆ b   │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ x   ┆ 20  │
# │ x   ┆ 30  │
# │ y   ┆ 10  │
# │ y   ┆ 40  │
# └─────┴─────┘

df.sql("""
  SELECT a, b FROM self ORDER BY ALL DESC
""")
# shape: (4, 2)
# ┌─────┬─────┐
# │ a   ┆ b   │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ y   ┆ 40  │
# │ y   ┆ 10  │
# │ x   ┆ 30  │
# │ x   ┆ 20  │
# └─────┴─────┘

OFFSET#

Skip a number of rows before starting to return rows from the query.

Example:

df = pl.DataFrame(
  {
    "foo": ["b", "a", "c", "b"],
    "bar": [20, 10, 40, 30],
  }
)
df.sql("""
  SELECT foo, bar FROM self LIMIT 2 OFFSET 2
""")
# shape: (2, 2)
# ┌─────┬─────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ c   ┆ 40  │
# │ b   ┆ 30  │
# └─────┴─────┘

LIMIT#

Limit the number of rows returned by the query.

Example:

df = pl.DataFrame(
  {
    "foo": ["b", "a", "c", "b"],
    "bar": [20, 10, 40, 30],
  }
)
df.sql("""
  SELECT foo, bar FROM self LIMIT 2
""")
# shape: (2, 2)
# ┌─────┬─────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ b   ┆ 20  │
# │ a   ┆ 10  │
# └─────┴─────┘

FETCH#

Limit the number of rows returned by the query; this is the ANSI SQL standard alternative to the LIMIT clause, and can be combined with OFFSET. The WITH TIES and PERCENT modifiers are not currently supported.

Example:

df = pl.DataFrame(
  {
    "foo": ["b", "a", "c", "b"],
    "bar": [20, 10, 40, 30],
  }
)
df.sql("""
  SELECT foo, bar
  FROM self
  ORDER BY bar
  OFFSET 1 FETCH NEXT 2 ROWS ONLY
""")
# shape: (2, 2)
# ┌─────┬─────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞═════╪═════╡
# │ b   ┆ 20  │
# │ b   ┆ 30  │
# └─────┴─────┘