How to See the SQL Behind an Ibis Spatial Query

On this page

Problem statement

An Ibis expression is a description of a query, and when the answer is wrong or slow you need to see the query it became. Two Ibis spatial joins that look equivalent can compile to SQL that DuckDB plans in completely different ways: one with its R-tree spatial join, one comparing every pair of rows. This page compiles Ibis expressions on Overture Maps places in Auckland to SQL with ibis.to_sql, reads DuckDB's plan for each with EXPLAIN, and times them, so you can tell from the SQL which of two spellings of the same question will be fast.

Quick answer

ibis.to_sql(expr) returns the SQL as a string, formatted for the backend the expression is bound to:

per_suburb = (places.join(suburbs, places.geometry.within(suburbs.geometry))
              .group_by(suburb=_.name_right).aggregate(n=_.count()))
sql = ibis.to_sql(per_suburb)
print(f"{len(sql.splitlines())} lines of SQL; the join condition: "
      f"{next(l.strip() for l in sql.splitlines() if 'ST_WITHIN' in l)}")
37 lines of SQL; the join condition: ON ST_WITHIN("t2"."geometry", "t3"."geometry")
How DuckDB decides whether a spatial join can use its R-tree. Is the join condition an ST_ predicatebetween two columns?yes: ST_Within, ST_DWithin…SPATIAL_JOINR-tree, fastno: ST_Distance(a, b) < rnested-loop joinevery pairThe optimiser does not rewrite one into the other spatialworkflow.io
The shape of the join condition decides the operator.

From expression to plan

1. The whole query

small = places.filter(_.basic_category == "library").select("name", geometry=_.geometry.buffer(0.001))
print(ibis.to_sql(small))
SELECT
  *
  REPLACE (ST_ASWKB("geometry") AS "geometry")
FROM (
  SELECT
    "t0"."name",
    ST_BUFFER("t0"."geometry", 0.001) AS "geometry"
  FROM (
    SELECT
      *
      REPLACE (CAST(geometry AS GEOMETRY) AS geometry)
    FROM READ_PARQUET('data/overture-auckland-places-2026-11-18.0.parquet')
  ) AS "t0"
  WHERE
    "t0"."basic_category" = 'library'
)

2. Ask DuckDB how it will run it

def join_operators(expr):
    """The join operators in DuckDB's plan for an Ibis expression."""
    plan = con.raw_sql("EXPLAIN " + ibis.to_sql(expr)).fetchall()[0][1]
    return sorted(set(re.findall(r"\b[A-Z_]*(?:JOIN|CROSS_PRODUCT)\b", plan)))


print("within:", join_operators(places.join(suburbs, places.geometry.within(suburbs.geometry))))
within: ['SPATIAL_JOIN']
The DuckDB join operator each Ibis spatial predicate compiles to. predicate → plan → timecompiles toDuckDB operatortime, 126,673 pairswithinST_WITHIN✓SPATIAL_JOIN—d_within(…, 200)ST_DWITHIN✓SPATIAL_JOIN✓0.06 sdistance(…) < 200ST_DISTANCE < 200✕nested loop✕0.67 sThe nested loop is DuckDB’s BLOCKWISE_NL_JOIN: same answer, ten times the time spatialworkflow.io
The same 126,673 pairs, found about ten times faster with d_within.

3. Two spellings of "within 200 m"

pm = places.select("id", g=_.geometry.convert("EPSG:4326", "EPSG:2193"))
cm = places.filter(_.basic_category == "cafe").select(cid=_.id, cg=_.geometry.convert("EPSG:4326", "EPSG:2193"))
for label, pred in [("d_within(cg, distance=200)", pm.g.d_within(cm.cg, distance=200)),
                    ("distance(cg) < 200", pm.g.distance(cm.cg) < 200)]:
    joined = pm.join(cm, pred)
    t0 = time.perf_counter()
    n = joined.count().execute()
    print(f"{label:27} {n:,} pairs  {join_operators(joined)}  {time.perf_counter() - t0:.2f} s")
d_within(cg, distance=200)  126,673 pairs  ['SPATIAL_JOIN']  0.06 s
distance(cg) < 200          126,673 pairs  ['BLOCKWISE_NL_JOIN']  0.67 s

Both expressions ask for every place within 200 m of a café, and both return 126,673 pairs. d_within compiles to ST_DWITHIN, which DuckDB plans as a SPATIAL_JOIN, and it takes 0.06 s. distance(...) < 200 compiles to a comparison on ST_DISTANCE, which no index can serve. DuckDB plans it as a BLOCKWISE_NL_JOIN that computes the distance for all 56,465 × 980 pairs, about 55 million, and it takes 0.67 s, about ten times longer. The gap grows with the product of the table sizes, so on larger tables it is the difference between seconds and hours.

4. The same expression in another dialect

line = lambda sql, key: next(l.strip() for l in sql.splitlines() if key in l)
for dialect in ["duckdb", "postgres"]:
    sql = ibis.to_sql(per_suburb, dialect=dialect)
    print(f"{dialect:9} {line(sql, 'ST_WITHIN')}   reads with: {line(sql, 'READ_PARQUET')[:22]}…")
duckdb    ON ST_WITHIN("t2"."geometry", "t3"."geometry")   reads with: FROM READ_PARQUET('dat…
postgres  ON ST_WITHIN("t2"."geometry", "t3"."geometry")   reads with: FROM READ_PARQUET('dat…

dialect= compiles the same expression for another backend. The join condition is identical in DuckDB's and PostgreSQL's SQL, but the PostgreSQL version still reads with READ_PARQUET: the con.sql text the tables were built from is passed through as written. Only the parts made with Ibis methods are portable.

What the compiled SQL adds

The data used on this page

Places and suburbs from Overture Maps 2026-11-18.0 for Auckland, read from a saved copy: enough rows (56,465 places, 980 of them cafés) for the slow plan to show. Places CDLA Permissive 2.0, suburbs ODbL 1.0.

import re
import time
from pathlib import Path

import ibis
import requests
from ibis import _

Path("data").mkdir(exist_ok=True)
# saved from s3://overturemaps-us-west-2/release/2026-11-18.0/ (theme=places, theme=divisions)
for layer in ["places", "suburbs"]:
    name = f"overture-auckland-{layer}-2026-11-18.0.parquet"
    if not Path(f"data/{name}").exists():
        Path(f"data/{name}").write_bytes(requests.get(f"https://data.spatialworkflow.io/{name}", timeout=300).content)

con = ibis.duckdb.connect()
con.load_extension("spatial")        # EXPLAIN runs before any Ibis geometry method would load it
# the cast is for Ibis 12, which cannot read DuckDB's GEOMETRY('OGC:CRS84') type (see /ibis-keyerror-ogc-crs84/)
read = lambda layer: con.sql("select * replace (geometry::GEOMETRY as geometry) "
                             f"from read_parquet('data/overture-auckland-{layer}-2026-11-18.0.parquet')")
places, suburbs = read("places"), read("suburbs")
print(f"{places.count().execute():,} places, {suburbs.count().execute()} suburbs")
56,465 places, 167 suburbs

Example 1: the wrapper on every geometry output

for label, expr in [("geometry out", places.select("id", "geometry").limit(1)),
                    ("number out", places.select("id", x=_.geometry.x()).limit(1))]:
    sql = ibis.to_sql(expr)
    print(f"{label:13} ST_ASWKB in SQL: {'ST_ASWKB' in sql};  {con.raw_sql(sql).description[1][1]}")
geometry out  ST_ASWKB in SQL: True;  BLOB
number out    ST_ASWKB in SQL: False;  DOUBLE

When the result has a geometry column, the compiled SQL ends in ST_ASWKB and DuckDB returns a BLOB, which Ibis turns into shapely geometries. When it returns only numbers, there is no wrapper and DuckDB returns a DOUBLE. That wrapper is why a COPY of compiled SQL writes plain bytes (the CRS on the way out), and why SQL passed to Table.sql sees WKB.

The layers of SQL Ibis compiles for a filtered, buffered table read from GeoParquet. compiled SQL, outside inREPLACE (ST_ASWKB(geometry))every geometry outST_BUFFER(…, 0.001), WHERE …your methodsCAST(geometry AS GEOMETRY)your con.sql textREAD_PARQUET('…')passed through as writtenDuckDB’s optimiser flattens the nesting spatialworkflow.io
Each method adds a nested select; the con.sql text sits at the bottom unchanged.

Example 2: time the plans, not the expressions

t0 = time.perf_counter()
lazy = pm.join(cm, pm.g.distance(cm.cg) < 200).count()
built = time.perf_counter() - t0
t0 = time.perf_counter()
lazy.execute()
ran = time.perf_counter() - t0
print(f"building the expression: {built * 1000:.1f} ms; running it: {ran:.2f} s")
building the expression: 0.6 ms; running it: 0.65 s

Building the slow join took under a millisecond and running it about two thirds of a second. In Ibis the time is spent in execute, count().execute() or to_pandas, never on the lines that build the expression. A profiler pointed at the building code finds nothing; time the call that runs the query, and read its plan.

Why the spelling changes the plan

DuckDB chooses a join operator from the shape of the join condition, not from what it means. A condition that is a call to ST_Intersects, ST_Within, ST_Contains or ST_DWithin between a column of each table can be served by an R-tree, so DuckDB builds one. A comparison of a computed value against a constant, ST_Distance(a, b) < 200, means the same thing, but the optimiser does not rewrite it into ST_DWithin. It falls back to a nested-loop join. Ibis passes each method through to one SQL function and does not rewrite either, so the choice of method is the choice of operator. Reading the plan once for each new kind of join is the quickest way to see which you have.

Reading compiled SQL

What to look for when reading SQL compiled by Ibis. reading compiled SQLsearch for function namest2, t3 aliases changeEXPLAIN for the join operatorSPATIAL_JOIN or a looptime execute(), not the build0.6 ms against 0.65 scon.sql text is not portableREAD_PARQUET in postgres SQLEXPLAIN ANALYZE adds rows and time per operator spatialworkflow.io
What to look at first in 37 lines of generated SQL.
  • EXPLAIN before any geometry method. On a fresh connection, EXPLAIN of compiled spatial SQL fails with "not in the catalog" until the spatial extension is loaded; this page's setup loads it.
  • EXPLAIN ANALYZE. It runs the query and adds row counts and times per operator. It is the tool for a join that is slow even with a SPATIAL_JOIN.
  • Names like t2 and t3. They are Ibis's aliases for its nested selects and change as the expression changes. Search the SQL for function names, not aliases.

FAQ

Does to_sql run the query?

No. It compiles the expression and returns a string. Nothing is read from the files, which is why it can compile for a backend you are not connected to.

Can I run the compiled SQL myself?

Yes, with con.raw_sql(sql) on the same connection, as this page does with EXPLAIN in front. On another connection the tables the SQL reads from must exist there too.