Skip to content

Tutorial: graph questions over your PostgreSQL schema

In ten minutes you will describe a shop database as nodes and edges, ask it Cypher questions, and get back one plain SQL query selecting primary keys. Install with pip install cypher2sql (or uv add cypher2sql), and pip install psycopg only to execute the SQL.

You need Python ≥ 3.12, PostgreSQL ≥ 15 and a scratch database (createdb shop_tutorial); the library has no runtime dependencies. Section 3 shows your first query and its one-row answer.

Status: 0.1.0 (pre-1.0) — the API may still change; every example below runs in the test suite, except the four t-string blocks across these docs, which run in CI on Python 3.14 (on 3.13 they are skipped with a visible count, never silently).

1. The database you already have

Customers, orders, products (via a join table) and reviews; load it with psql -d shop_tutorial:

CREATE TABLE customer (id int PRIMARY KEY, name text NOT NULL, country text);
CREATE TABLE product (sku text PRIMARY KEY, price_cents int NOT NULL);
CREATE TABLE "order" (id int PRIMARY KEY, customer_id int NOT NULL REFERENCES customer);
CREATE TABLE order_line (order_id int REFERENCES "order", product_sku text REFERENCES product, quantity int NOT NULL, PRIMARY KEY (order_id, product_sku));
CREATE TABLE review (customer_id int REFERENCES customer, product_sku text REFERENCES product, stars int NOT NULL, PRIMARY KEY (customer_id, product_sku));
INSERT INTO customer VALUES (1, 'Ada', 'FR'), (2, 'Grace', 'US'), (3, 'Alan', NULL);
INSERT INTO product VALUES ('MUG', 900), ('LAMP', 4500), ('BOOK', 1500);
INSERT INTO "order" VALUES (10, 1), (11, 2), (12, 3);
INSERT INTO order_line VALUES (10, 'MUG', 2), (10, 'LAMP', 1), (11, 'MUG', 1), (12, 'BOOK', 3);
INSERT INTO review VALUES (1, 'LAMP', 5), (2, 'MUG', 2), (3, 'BOOK', 4);
export PGDATABASE=shop_tutorial (plus PGHOST/PGUSER if needed), and a helper that runs a compiled query:
import psycopg
conn = psycopg.connect(autocommit=True)
def keys(q): return sorted(conn.execute(q.sql, q.params).fetchall())

2. Describe your schema once

A Node maps a table to a label and names its primary key (a tuple when composite); properties maps property names to column types (Column renames). A key column is a property only if listed: a key you leave out — Customer.id and both Review keys below — still identifies the node, still joins its foreign keys and still comes back from RETURN, but it is not queryable as a property, and an untyped walk compares its rendered text instead of casting it back to its type. Declare a key you filter on, or one whose walk hop should look the edge column up by its own key: that cast needs the key and the edge's foreign-key column to carry the same exact type, and it works for an int, bool, uuid.UUID, date or datetime key, never for a str, Decimal or float one. An Edge names the columns pointing at each end's key: a foreign key names one side (source_columns="customer_id" lives in the target's table, whose own side is its key); a join table names both sides and its table.

from cypher2sql import Column, Edge, Limits, Node, Schema
customer = Node("Customer", table="customer", key="id", properties={"name": str, "country": str})
product = Node("Product", table="product", key="sku",
               properties={"sku": str, "price": Column("price_cents", int)})
order = Node("Order", table="order", key="id", properties={"id": int})
review = Node("Review", table="review", key=("customer_id", "product_sku"), properties={"stars": int})
shop = Schema(nodes=[customer, product, order, review], edges=[
    Edge("PLACED", customer, order, source_columns="customer_id"),
    Edge("CONTAINS", order, product, source_columns="order_id", target_columns="product_sku",
         table="order_line", properties={"quantity": int}),
    Edge("WROTE", customer, review, source_columns="customer_id"),
])

3. First query

The variable in RETURN picks the table whose keys you get back; 'FR' travels as a bound parameter, never SQL text.

q = shop.to_sql("MATCH (c:Customer {country: 'FR'}) RETURN c")
print(q.sql)
print(q.params, keys(q))
output
SELECT n1."id"
FROM "customer" AS n1
WHERE n1."country" COLLATE "C" = %s::text
('FR',) [(1,)]

Composite keys

A review is identified by two columns, so its keys come back as pairs, in key order:

top = shop.to_sql("MATCH (r:Review {stars: 5}) RETURN r")
print(top.sql)
print(top.columns, keys(top))
output
SELECT n1."customer_id", n1."product_sku"
FROM "review" AS n1
WHERE n1."stars" = %s::bigint
('customer_id', 'product_sku') [(1, 'LAMP')]

4. Let the schema find the path

The schema has no Customer–Product edge, so the compiler searched the declared edges and found the shortest path through Order. An untyped, undirected -- first tries any declared edge joining the two (either direction) — a deliberate extension of Cypher's single-relationship --; only when none joins them does it infer the shortest declared path up to max_path_length. No relationship at all gives a CypherSemanticError naming the foreign keys that would relate them; a shortest path beyond the limit, or more than max_inferred_paths equally short paths, gives a LimitExceededError naming the limit — declare an Edge or raise it. Only the keys of p come back.

via = shop.to_sql("MATCH (c:Customer {country: 'FR'})--(p:Product {sku: 'MUG'}) RETURN p")
print(via.sql)
print(via.params, keys(via))
output
SELECT n3."sku"
FROM "product" AS n3
WHERE n3."sku" COLLATE "C" = %s::text
  AND EXISTS (
    SELECT 1
    FROM "customer" AS n1
    JOIN "order" AS n2 ON n2."customer_id" = n1."id"
    JOIN "order_line" AS r1 ON r1."order_id" = n2."id"
    WHERE r1."product_sku" COLLATE "C" = n3."sku" COLLATE "C"
      AND n1."country" COLLATE "C" = %s::text
  )
('MUG', 'FR') [('MUG',)]

5. Follow foreign keys

Who bought a mug? $sku comes from the dict you pass, and unnamed nodes like (:Order) are fine; the rest of the pattern sits in one EXISTS, so each customer appears at most once.

buyers = shop.to_sql("MATCH (c:Customer)-[:PLACED]->(:Order)-[:CONTAINS]->(:Product {sku: $sku}) "
                     "RETURN c", {"sku": "MUG"})
print(buyers.sql)
print(keys(buyers))
output
SELECT n1."id"
FROM "customer" AS n1
WHERE EXISTS (
  SELECT 1
  FROM "order" AS n2
  JOIN "order_line" AS r1 ON r1."order_id" = n2."id"
  JOIN "product" AS n3 ON n3."sku" COLLATE "C" = r1."product_sku" COLLATE "C"
  WHERE n2."customer_id" = n1."id"
    AND n3."sku" COLLATE "C" = %s::text
)
[(1,), (2,)]

6. Filter with WHERE

Any node can be the answer. Here: products French customers bought at least two of. The relationship variable line exposes the join table's quantity.

bulk = shop.to_sql("MATCH (c:Customer)-[:PLACED]->(:Order)-[line:CONTAINS]->(p:Product) "
                   "WHERE c.country = $country AND line.quantity >= 2 RETURN p", {"country": "FR"})
print(bulk.sql)
print(bulk.params, keys(bulk))
output
SELECT n3."sku"
FROM "product" AS n3
WHERE EXISTS (
  SELECT 1
  FROM "customer" AS n1
  JOIN "order" AS n2 ON n2."customer_id" = n1."id"
  JOIN "order_line" AS r1 ON r1."order_id" = n2."id"
  WHERE r1."product_sku" COLLATE "C" = n3."sku" COLLATE "C"
    AND n1."country" COLLATE "C" = %s::text
    AND r1."quantity" >= %s::bigint
)
('FR', 2) [('MUG',)]

Missing values

Missing values behave as in Cypher: Alan has no country, and comparing with a missing value is neither true nor false, so he is not "outside France" unless you ask with IS NULL.

print(keys(shop.to_sql("MATCH (c:Customer) WHERE c.country <> 'FR' RETURN c")))
print(keys(shop.to_sql("MATCH (c:Customer) WHERE c.country <> 'FR' OR c.country IS NULL RETURN c")))
output
[(2,)]
[(2,), (3,)]
On Python ≥ 3.14, {country} binds the value with no params dict; on < 3.14 use str + $params.
country = "FR"
fr = shop.to_sql(t"MATCH (c:Customer) WHERE c.country = {country} RETURN c")
print(fr.params, keys(fr))
output
('FR',) [(1,)]

7. Use the keys in a bigger query

Three ways; only q.sql/to_template() is ever spliced, never a value. 1. t-string (Python ≥ 3.14, psycopg ≥ 3.3 to execute it): a nested Template is the only value-carrying channel, and a %s string can never enter a t-string. 2. psycopg.sql composition: splices q.sql unchanged, but the final statement still doubles your own literal % as %%; params in textual order. 3. f-string splice (portable, available now): params in textual order, your own % as %%, best as a parenthesised CTE.

name = "Grace"
rows = conn.execute(t"WITH b AS ({buyers.to_template():q}) SELECT name FROM customer JOIN b USING (id) WHERE name <> {name}").fetchall()
print(rows)
That prints [('Ada',)]. The portable form works on every version: splice buyers.sql whole as one CTE, then pass buyers.params in place.
sql = f"WITH b AS ({buyers.sql}) SELECT name FROM customer JOIN b USING (id) WHERE name <> %s"
print(conn.execute(sql, (*buyers.params, "Grace")).fetchall())
output
[('Ada',)]
Django, single-column key: filter(pk__in=RawSQL(q.sql, q.params)); composite keys: join a CTE.

8. One template, several node types

A label or a relationship type can be a parameter, so one template compiles for different declared shapes. Here the same template asks for Ada's orders, then her reviews.

template = "MATCH (c:Customer {name: $name})-[:$rel]->(x:$kind) RETURN x"
orders = shop.to_sql(template, {"name": "Ada", "rel": "PLACED", "kind": "Order"})
print(orders.sql)
print(keys(orders))
output
SELECT n2."id"
FROM "order" AS n2
WHERE EXISTS (
  SELECT 1
  FROM "customer" AS n1
  WHERE n2."customer_id" = n1."id"
    AND n1."name" COLLATE "C" = %s::text
)
[(10,)]
The second call changes only rel and kind; the SQL is the one for :Review, including its composite key.
reviews = shop.to_sql(template, {"name": "Ada", "rel": "WROTE", "kind": "Review"})
print(reviews.sql)
print(keys(reviews))
output
SELECT n2."customer_id", n2."product_sku"
FROM "review" AS n2
WHERE EXISTS (
  SELECT 1
  FROM "customer" AS n1
  WHERE n2."customer_id" = n1."id"
    AND n1."name" COLLATE "C" = %s::text
)
[(1, 'LAMP')]
Only declared names are accepted: an unknown one raises ParameterError, and a list of labels is rejected too — one label per element. The value only selects among the identifiers you declared, so it never becomes SQL text; prepare one statement per label and type. Limits, inference and ambiguity errors are unchanged.

9. When a query is wrong

Errors point at the problem and suggest a fix; they never repeat property values (a label/type selector is the exception: naming what was rejected is how the message points at a declaration).

from cypher2sql import QueryError
try:
    shop.to_sql("MATCH (c:Custmer) RETURN c")
except QueryError as e:
    print(e)
output
unknown label :Custmer (line 1, column 10)
  MATCH (c:Custmer) RETURN c
           ^^^^^^^
hint: did you mean :Customer?
Untrusted queries are fine: values are always bound; a value PostgreSQL cannot represent (a $param value such as a huge int, or a NUL in a string) is rejected at compile time with a ParameterError naming the declared type, never the value.
from cypher2sql import ParameterError

try:
    shop.to_sql("MATCH (p:Product) WHERE p.price = $price RETURN p", {"price": 2**63})
except ParameterError as e:
    print(e)
output
parameter $price is not a valid int (line 1, column 35)
  MATCH (p:Product) WHERE p.price = $price RETURN p
                                    ^^^^^^
hint: pass an int in int64 range or a float
A float property never compares with an int or Decimal one — see Mixing property types. Identifiers come only from your Schema; Limits bound compilation. Errors name what your Schema declares, so give each audience its own Schema. Limits do not bound execution: set statement_timeout (and a row cap) where untrusted queries run.

10. Any number of hops

A product can be substituted by another, and that one by a third. "Which products can I serve if MUG is gone, allowing up to two substitutions?" is a variable-length pattern, [:SUBSTITUTE*1..2]. Add the table and declare just the node and edge this question needs — product is the node you already described:

CREATE TABLE substitute (
    product_sku text REFERENCES product,
    alternative_sku text REFERENCES product,
    PRIMARY KEY (product_sku, alternative_sku)
);
INSERT INTO substitute VALUES ('MUG', 'LAMP'), ('LAMP', 'BOOK');
substitute = Edge("SUBSTITUTE", product, product, source_columns="product_sku",
                  target_columns="alternative_sku", table="substitute")
shelf = Schema(nodes=[product], edges=[substitute], limits=Limits(open_path_length=8))
subs = shelf.to_sql("MATCH (p:Product {sku: 'MUG'})-[:SUBSTITUTE*1..2]->(alt:Product) RETURN alt")
print(subs.sql)
print(keys(subs))
output
SELECT n2."sku"
FROM "product" AS n2
WHERE EXISTS (
  SELECT 1
  FROM "product" AS n1
  WHERE n1."sku" COLLATE "C" = %s::text
    AND (
      EXISTS (
        SELECT 1
        FROM "substitute" AS r1
        WHERE r1."product_sku" COLLATE "C" = n1."sku" COLLATE "C"
          AND r1."alternative_sku" COLLATE "C" = n2."sku" COLLATE "C"
      )
      OR EXISTS (
        SELECT 1
        FROM "product" AS n3
        JOIN "substitute" AS r2 ON r2."alternative_sku" COLLATE "C" = n3."sku" COLLATE "C"
        JOIN "substitute" AS r3 ON r3."product_sku" COLLATE "C" = n3."sku" COLLATE "C"
        WHERE r2."product_sku" COLLATE "C" = n1."sku" COLLATE "C"
          AND r3."alternative_sku" COLLATE "C" = n2."sku" COLLATE "C"
          AND (r2."product_sku", r2."alternative_sku") <> (r3."product_sku", r3."alternative_sku")
      )
    )
)
[('BOOK',), ('LAMP',)]
Each length in the bound is one alternative — one hop through the substitute rows, or two through an intermediate product — and only the keys of alt come back, once each. The <> line is row uniqueness: one path may not walk the same substitute row twice, so the two hops must read different rows. The lower end may be omitted (*..2 is *1..2), *2 is *2..2, and *0..0 is the identity: zero hops means both sides are the same node, so no edge row is read. A bound may name its relationship type, as here; leave the type out to walk every declared edge (step 11). A typed bound's hops are joins while they fit, so every length it allows counts against max_pattern_size (each hop of the one-hop and of the two-hop alternative); a bound past max_path_length, or a running join total past max_pattern_size, raises LimitExceededError, never partial SQL. An untyped bound is one walk instead: its branches count against max_edge_branches, never max_pattern_size. An open-ended * (or *1..) has no fixed number of joins, and a bound whose hops exceed the join budget cannot be a fixed number of joins either; both compile with WITH RECURSIVE instead — a walk bounded by open_path_length (* resolved first) or by the bound. open_path_length has no default: the keyword on Limits above sets it, and leaving it unset raises LimitExceededError. It is at most max_path_length. The walk carries the rows it has read and stops at its depth even on a cycle, so it never reads a row twice; a chain longer than N is cut there silently — no error — and keys beyond N hops are not returned. Two expansions of the same relationship type in one path would need one walk over the whole path, which is not built, so they are refused rather than risking a repeated row. This block reaches both products without naming a hop count, and prints the walk it compiles; anchor1 holds the start product's key as k1, and reach1 is the set of products reachable from it:
reaches = shelf.to_sql("MATCH (p:Product {sku: 'MUG'})-[:SUBSTITUTE*]->(alt:Product) RETURN alt")
print(reaches.sql)
print(keys(reaches))
output
WITH RECURSIVE
anchor1 AS NOT MATERIALIZED (
  SELECT n1."sku" AS "k1"
  FROM "product" AS n1
  WHERE n1."sku" COLLATE "C" = %s::text
),
reach1 (depth, src1, dst1, trail) AS MATERIALIZED (
  SELECT 1, (e1."product_sku" COLLATE "C"), (e1."alternative_sku" COLLATE "C"), ARRAY[ROW((e1."product_sku" COLLATE "C"), (e1."alternative_sku" COLLATE "C"))]
  FROM "substitute" AS e1
  CROSS JOIN anchor1 AS a1
  WHERE (e1."product_sku" COLLATE "C") = a1."k1" COLLATE "C"
  UNION ALL
  SELECT reach1.depth + 1, (e1."product_sku" COLLATE "C"), (e1."alternative_sku" COLLATE "C"), reach1.trail || ROW((e1."product_sku" COLLATE "C"), (e1."alternative_sku" COLLATE "C"))
  FROM reach1
  JOIN "substitute" AS e1 ON (e1."product_sku" COLLATE "C") = (reach1.dst1 COLLATE "C")
  WHERE reach1.depth < 8
    AND NOT (ROW((e1."product_sku" COLLATE "C"), (e1."alternative_sku" COLLATE "C")) = ANY (reach1.trail))
)
SELECT n2."sku"
FROM "product" AS n2
WHERE EXISTS (
  SELECT 1
  FROM reach1
  WHERE reach1.depth BETWEEN 1 AND 8
    AND (reach1.dst1 COLLATE "C") = n2."sku" COLLATE "C"
)
[('BOOK',), ('LAMP',)]
src1 and dst1 are the edge row's two ends: the product the walk left and the product it arrived at. depth is how many substitute rows the walk has read and trail is those rows, so the NOT (... = ANY (trail)) line is the same one-path-never-reuses-a-row rule as the <> above. Because the start comes from the same matched row, the statement reads anchor1 once, then computes every reachable product in reach1 once; the outer query asks which candidate products that set holds, so the walk's cost depends on how much is reachable, not on how many products you might return.

11. Walk any declared edge

A variable-length pattern with no type walks every declared edge the arrow allows. Here it finds the products a French customer can reach within two declared edges, without naming PLACED or CONTAINS:

any_path = shop.to_sql("MATCH (c:Customer {country: 'FR'})-[*1..2]-(p:Product) RETURN p")
print(any_path.sql)
print(any_path.params, keys(any_path))
output
WITH RECURSIVE
anchor1 AS NOT MATERIALIZED (
  SELECT n1."id" AS "k1"
  FROM "customer" AS n1
  WHERE n1."country" COLLATE "C" = %s::text
),
reach1 (current, depth, trail) AS MATERIALIZED (
  SELECT ARRAY['Order', e11."id"::text]::text COLLATE "C", 1, ARRAY['0:' || ARRAY[e11."customer_id"::text, e11."id"::text]::text COLLATE "C"]
  FROM "order" AS e11
  CROSS JOIN anchor1 AS a1
  WHERE e11."customer_id" = a1."k1"
  UNION ALL
  SELECT step1.next_key, reach1.depth + 1, reach1.trail || step1.identity
  FROM reach1
  CROSS JOIN LATERAL (
    SELECT ARRAY['Product', e12."product_sku"::text]::text COLLATE "C" AS next_key, '1:' || ARRAY[e12."order_id"::text, e12."product_sku"::text]::text COLLATE "C" AS identity
    FROM "order_line" AS e12
    WHERE ((reach1.current::text[])[1] COLLATE "C") = 'Order'
      AND e12."order_id" = (reach1.current::text[])[2]::bigint
      AND e12."product_sku" IS NOT NULL
  ) AS step1
  WHERE reach1.depth < 2
    AND NOT (step1.identity = ANY (reach1.trail))
)
SELECT n2."sku"
FROM "product" AS n2
WHERE EXISTS (
  SELECT 1
  FROM reach1
  WHERE reach1.depth BETWEEN 1 AND 2
    AND reach1.current = ARRAY['Product', (n2."sku" COLLATE "C")::text]::text COLLATE "C"
)
('FR',) [('LAMP',), ('MUG',)]
current is one node's identity as text: its label followed by its key columns, so a Customer key can never match an Order key with the same value. Each hop branch reads only the one current row: the label test ((reach1.current::text[])[1] COLLATE "C") = 'Order' skips branches that cannot leave that node type, and the key test e12."order_id" = (reach1.current::text[])[2]::bigint compares the frontier key with the edge table's own key column, so the edge table's index serves the lookup. Each branch leaves the current node, and trail collects the tag:key identity of every edge row walked; NOT (step1.identity = ANY (reach1.trail)) is the same one-path-never-reuses-a-row rule as step 10. -> follows every declared edge forward, <- every declared edge backward, and - both ways. The walk counts hops and stops at the last hop that can land on p, never past the bound, so a cycle terminates and a chain longer than the bound is cut silently; *0..0 is the identity, both sides the same node with no edge read. An omitted upper end (*1..) uses open_path_length, an upper end past max_path_length raises, and each declared-edge branch the walk unions counts against max_edge_branches (two here: PLACED forward from Customer, CONTAINS forward from Order). Every returned key appears once.

12. Find the customers who did not place order 12

A required pattern drops a row when it finds nothing; OPTIONAL MATCH keeps it and leaves the variables it introduced missing. Order 12 is Alan's order, and every customer who did not place it comes back:

not_twelve = shop.to_sql(
    "MATCH (c:Customer) OPTIONAL MATCH (c)-[:PLACED]->(o:Order) WHERE o.id = 12 "
    "MATCH (c) WHERE o IS NULL RETURN c"
)
print(not_twelve.sql)
print(not_twelve.params, keys(not_twelve))
output
SELECT n1."id"
FROM "customer" AS n1
LEFT JOIN LATERAL (
  SELECT TRUE AS "found"
  FROM "order" AS n2
  WHERE n2."customer_id" = n1."id"
    AND n2."id" = %s::bigint
) AS o1 ON TRUE
WHERE o1."found" IS NULL
(12,) [(1,), (2,)]
No row disappeared for a customer without order 12: the optional side contributes nothing, and the LEFT JOIN LATERAL still yields that customer's row. The group projects one found column, which is NULL exactly when it matched nothing — not the node's own columns — so o IS NULL reads o1."found" IS NULL. The WHERE written inside OPTIONAL MATCH filters that optional expansion only (o.id = 12), never the required rows; the later MATCH (c) gives the outer WHERE a clause to attach to, and that outer WHERE is what keeps only the customers the optional side missed. There is no DISTINCT here because o IS NULL pins the only optional group to its null row; a group left able to multiply rows adds it.

13. Filter, then keep going

WITH does what that dummy MATCH (c) did, in one clause: it starts a new variable scope, and a WHERE written after it filters the rows produced so far — including rows an OPTIONAL MATCH left missing. Edsger has never ordered anything, so o IS NULL keeps exactly him:

INSERT INTO customer VALUES (4, 'Edsger', 'NL');
never = shop.to_sql(
    "MATCH (c:Customer) OPTIONAL MATCH (c)-[:PLACED]->(o:Order) "
    "WITH c, o WHERE o IS NULL RETURN c"
)
print(never.sql)
print(never.params, keys(never))
output
SELECT n1."id"
FROM "customer" AS n1
LEFT JOIN LATERAL (
  SELECT TRUE AS "found"
  FROM "order" AS n2
  WHERE n2."customer_id" = n1."id"
) AS o1 ON TRUE
WHERE o1."found" IS NULL
() [(4,)]
The WHERE is a boundary, not a predicate pushed into the optional body: written inside the OPTIONAL MATCH, o IS NULL would filter the orders it found, match nothing for every customer and bring all four back. Outside, the optional side's found column decides, and since o IS NULL pins that group to its one null row no DISTINCT is needed.

WITH c, o keeps exactly those variables; anything bound earlier is gone afterwards, and a later reference to it is a CypherSemanticError naming it. Rename with WITH c AS customer — the keys do not change — and chain clauses with another WITH to rebind again. WITH DISTINCT is accepted and does nothing: the result is a key set already.

Only whole variables are supported for 0.1.0: aggregation, a function call, a property projection, WITH *, ORDER BY, SKIP and LIMIT inside WITH raise UnsupportedCypherError with a hint. The WHERE after the WITH may also name variables bound before it — WITH c WHERE o IS NULL compiles and keeps the customers without orders.

14. Ask whether something exists, do not fetch it

A permission question is not a fetch. "Has this customer ordered the lamp?" needs a yes or no per customer, not the order rows, and a pattern written in WHERE is exactly that question. Wrap the pattern in EXISTS { ... } when it needs a WHERE or names of its own:

lamp = shop.to_sql(
    "MATCH (c:Customer) WHERE EXISTS { MATCH (c)-[:PLACED]->(o:Order)-[:CONTAINS]->(p:Product) "
    "WHERE p.sku = 'LAMP' } RETURN c"
)
print(lamp.sql)
print(lamp.params, keys(lamp))
output
SELECT n1."id"
FROM "customer" AS n1
WHERE EXISTS (
  SELECT 1
  FROM "order" AS n2
  JOIN "order_line" AS r1 ON r1."order_id" = n2."id"
  JOIN "product" AS n3 ON n3."sku" COLLATE "C" = r1."product_sku" COLLATE "C"
  WHERE n2."customer_id" = n1."id"
    AND n3."sku" COLLATE "C" = %s::text
)
('LAMP',) [(1,)]
Nothing about the order or the product reaches the result: each customer is kept or dropped by one correlated EXISTS, and the target's table is still the only one in the outer FROM. Only Ada ordered the LAMP; Grace's order has the MUG and Alan's the BOOK.

The relation alone needs no EXISTS { }: WHERE (c)-[:PLACED]->() is the same question about the pattern's existence, and NOT asks the opposite. Edsger, who has never ordered anything, is the one a NOT keeps — NOT EXISTS is true when there is nothing to match, so a missing row is not a third answer:

placed = shop.to_sql("MATCH (c:Customer) WHERE (c)-[:PLACED]->() RETURN c")
never = shop.to_sql("MATCH (c:Customer) WHERE NOT (c)-[:PLACED]->() RETURN c")
not_book = shop.to_sql(
    "MATCH (c:Customer) WHERE (c)-[:PLACED]->(:Order)-[:CONTAINS]->(:Product) "
    "AND NOT (c)-[:PLACED]->(:Order)-[:CONTAINS]->(:Product {sku: 'BOOK'}) RETURN c"
)
print(placed.sql)
print(keys(placed), keys(never), keys(not_book))
output
SELECT n1."id"
FROM "customer" AS n1
WHERE EXISTS (
  SELECT 1
  FROM "order" AS n2
  WHERE n2."customer_id" = n1."id"
)
[(1,), (2,), (3,)] [(4,)] [(1,), (2,)]
Two predicates in one WHERE must both hold, direction and type are part of the question, and a variable-length bound works the same way. A pattern predicate names only variables already bound; a name it does not know is a CypherSemanticError with a hint to use EXISTS { MATCH ... } instead. The bound is part of the question too: shelf from step 10 asks which products can be substituted by the BOOK within two hops, without fetching the alternatives:
reachable = shelf.to_sql(
    "MATCH (p:Product) WHERE (p)-[:SUBSTITUTE*1..2]->(:Product {sku: 'BOOK'}) RETURN p"
)
print(reachable.sql)
print(reachable.params, keys(reachable))
output
SELECT n1."sku"
FROM "product" AS n1
WHERE EXISTS (
  SELECT 1
  FROM "product" AS n2
  WHERE n2."sku" COLLATE "C" = %s::text
    AND (
      EXISTS (
        SELECT 1
        FROM "substitute" AS r1
        WHERE r1."product_sku" COLLATE "C" = n1."sku" COLLATE "C"
          AND r1."alternative_sku" COLLATE "C" = n2."sku" COLLATE "C"
      )
      OR EXISTS (
        SELECT 1
        FROM "product" AS n3
        JOIN "substitute" AS r2 ON r2."alternative_sku" COLLATE "C" = n3."sku" COLLATE "C"
        JOIN "substitute" AS r3 ON r3."product_sku" COLLATE "C" = n3."sku" COLLATE "C"
        WHERE r2."product_sku" COLLATE "C" = n1."sku" COLLATE "C"
          AND r3."alternative_sku" COLLATE "C" = n2."sku" COLLATE "C"
          AND (r2."product_sku", r2."alternative_sku") <> (r3."product_sku", r3."alternative_sku")
      )
    )
)
('BOOK',) [('LAMP',), ('MUG',)]
Each length in the bound is one alternative inside the same EXISTS, and p is still the only table in the outer FROM; the targets are pinned to the BOOK, so MUG survives only through LAMP.

Over a variable an OPTIONAL MATCH may have left missing, a pattern predicate is NULL, not false — and NOT keeps it NULL. Back in the shape of §13, only Alan's BOOK matches; Edsger has no order, so the predicate is NULL for him and he is dropped unless the query asks for the missing row as well:

book = shop.to_sql(
    "MATCH (c:Customer) OPTIONAL MATCH (c)-[:PLACED]->(o:Order) "
    "WITH c, o WHERE (o)-[:CONTAINS]->(:Product {sku: 'BOOK'}) RETURN c"
)
book_or_missing = shop.to_sql(
    "MATCH (c:Customer) OPTIONAL MATCH (c)-[:PLACED]->(o:Order) "
    "WITH c, o WHERE (o)-[:CONTAINS]->(:Product {sku: 'BOOK'}) OR o IS NULL RETURN c"
)
print(keys(book), keys(book_or_missing))
output
[(3,)] [(3,), (4,)]
EXISTS is two-valued instead: it is false, never NULL, when the optional side matched nothing, so it drops the row without the CASE guard the pattern predicate needs. An unlabeled () is legal only where exactly one declared node type fits. A typed relationship narrows both of the ends it touches, so (c)-[:PLACED]->() is always an Order and that end needs no label. An untyped (c)-[]->() narrows nothing: from :Customer a :PLACED row reaches an :Order and a :WROTE row reaches a :Review, so the schema cannot choose, and the error names the types it could not choose between: CypherSemanticError: cannot tell which node type the pattern is: :Order or :Review. Name the label on the ambiguous end, or name the relationship type.

15. Filter by a list and by text

A set of accepted values is one IN, and the list travels as one array parameter — never as SQL text. Ask for two products by sku:

skus = ["MUG", "BOOK"]
by_sku = shop.to_sql("MATCH (p:Product) WHERE p.sku IN $skus RETURN p", {"skus": skus})
print(by_sku.sql)
print(by_sku.params, keys(by_sku))
output
SELECT n1."sku"
FROM "product" AS n1
WHERE n1."sku" COLLATE "C" = ANY(%s::text[])
(['MUG', 'BOOK'],) [('BOOK',), ('MUG',)]
= ANY(%s::text[]) is the whole membership test: one placeholder, cast to the property's type array. An empty list matches nothing — never every row. A NULL element never matches on its own: ['MUG', NULL] still matches MUG, and when no element matches it makes the answer NULL, so no row. A wrong-type $param list — or a scalar where a list is expected — raises ParameterError naming the parameter and the declared type, never a value; a literal element of another type simply never equals anything. A list written in the query, p.sku IN ['MUG', 'BOOK'], compiles to the same SQL with the same array parameter.

A search box binds what the user typed and compares with string functions, so %, _ and a backslash are characters, not wildcards, and case matters. Two customers' names start with A, and both also contain a lowercase a:

prefix = shop.to_sql("MATCH (c:Customer) WHERE c.name STARTS WITH $q RETURN c", {"q": "A"})
search = shop.to_sql(
    "MATCH (c:Customer) WHERE c.name STARTS WITH $first AND c.name CONTAINS $part RETURN c",
    {"first": "A", "part": "a"},
)
print(prefix.sql)
print(prefix.params, keys(prefix))
print(search.sql)
print(search.params, keys(search))
output
SELECT n1."id"
FROM "customer" AS n1
WHERE starts_with((n1."name" COLLATE "C"), %s::text)
('A',) [(1,), (3,)]
SELECT n1."id"
FROM "customer" AS n1
WHERE starts_with((n1."name" COLLATE "C"), %s::text)
  AND position(%s::text in (n1."name" COLLATE "C")) > 0
('A', 'a') [(1,), (3,)]
STARTS WITH is PostgreSQL's starts_with (which needs PostgreSQL ≥ 15), CONTAINS is position(needle in (value COLLATE "C")) > 0, and ENDS WITH — which PostgreSQL has no function for — is right((value COLLATE "C"), length(needle)) = needle, the one that binds its needle twice. None is LIKE, and each pins the column with COLLATE "C" so a case-insensitive or nondeterministic collation cannot make it match more than the characters say. An empty needle matches every non-NULL string, and NULL on either side makes the answer NULL, which NOT keeps NULL, so a customer with no name is never in the result.

=~ matches a regular expression against the whole string: the pattern is a bound parameter wrapped in ^(?: … )$, so 'ab' matches ab but not the ab inside abc, and NOT emits PostgreSQL's !~. Anchoring is Cypher's own whole-string match; a ^ or $ in the pattern is redundant but harmless. The column carries the same COLLATE "C" pin, so the match is by code point whatever the column's collation, nondeterministic or not.

The engine is PostgreSQL's POSIX regular expressions, not Java's, so \d and character classes work while Java-only constructs do not — \Q…\E is not supported, so escape metacharacters with a backslash. A pattern whose parentheses are unbalanced, or that starts with a (?flags) group, is refused at compile time; any other pattern PostgreSQL cannot parse raises psycopg.errors.InvalidRegularExpression when you run the SQL, and the pattern value never appears in the SQL.

16. Order and page the keys

A key set has no order until you ask for one. ORDER BY o sorts by o's key columns in key order, and SKIP/LIMIT page the result after that sort; every value is bound, so a page never becomes SQL text:

page = shop.to_sql(
    "MATCH (c:Customer)-[:PLACED]->(o:Order) RETURN o ORDER BY o SKIP $skip LIMIT $limit",
    {"skip": 1, "limit": 1},
)
print(page.sql)
print(page.params, conn.execute(page.sql, page.params).fetchall())
output
SELECT n2."id"
FROM "order" AS n2
WHERE EXISTS (
  SELECT 1
  FROM "customer" AS n1
  WHERE n2."customer_id" = n1."id"
)
ORDER BY n2."id"
OFFSET %s::bigint
FETCH FIRST (%s::bigint) ROWS ONLY
(1, 1) [(11,)]
OFFSET and FETCH FIRST take $skip and $limit as %s::bigint parameters, in the query's own SKIP then LIMIT order (FETCH FIRST accepts only a parenthesised cast, hence the brackets).

LIMIT 0 returns no row, SKIP past the end returns nothing, and a negative literal is a compile error while a negative, oversized or non-int parameter is a ParameterError naming the parameter and never its value. A query without ORDER BY still compiles; the rows PostgreSQL picks for a page are then not deterministic.

DESC reverses every key column, which matters for a composite key. A review is identified by (customer_id, product_sku), so both columns flip:

reviews = shop.to_sql("MATCH (r:Review) RETURN r ORDER BY r DESC")
print(reviews.sql)
print(conn.execute(reviews.sql, reviews.params).fetchall())
output
SELECT n1."customer_id", n1."product_sku"
FROM "review" AS n1
ORDER BY n1."customer_id" DESC, n1."product_sku" DESC
[(3, 'BOOK'), (2, 'MUG'), (1, 'LAMP')]
A key column declared as a str property orders by code point under COLLATE "C", so BOOK comes before LAMP before MUG whatever the database's default collation:
products = shop.to_sql("MATCH (p:Product) RETURN p ORDER BY p")
print(products.sql)
print(conn.execute(products.sql, products.params).fetchall())
output
SELECT n1."sku"
FROM "product" AS n1
ORDER BY n1."sku" COLLATE "C"
[('BOOK',), ('LAMP',), ('MUG',)]
A key column you did not declare as a property — Review.product_sku above — keeps its own column collation. DISTINCT dedupes the keys first, then the order and the page apply to that list; a collated text key is projected as the same expression it is ordered by, so PostgreSQL accepts SELECT DISTINCT with ORDER BY and LIMIT.

Ordering is by the returned variable alone: a property (ORDER BY p.sku), another variable or an expression raises UnsupportedCypherError with a hint, because the result is a key set, not a projection.

For compile, planning and execution numbers on a 10,000-customer shop, the plans they produce, and the index a non-C collation needs, see Performance.