Who Bought in Both Quarters? One SQL Statement on Elasticsearch

SoftClient4ES 0.24.0 adds CTEs and the UNION, INTERSECT and EXCEPT set operators: compare lists, merge sources and write reports in readable steps, on live Elasticsearch data.

  • Elasticsearch
  • SQL
  • CTEs
  • Set Operators

This is the second post on SoftClient4ES 0.24.0. The first covered subqueries and derived tables. This one covers common table expressions (WITH) and the set operators UNION, INTERSECT and EXCEPT. Together, they turn the questions you answer in a spreadsheet today into one SQL statement.

The spreadsheet step nobody draws on the architecture diagram

Some of the most common business questions compare one list with another:

  • Which customers ordered in both quarters? That is retention.
  • Which customers ordered last quarter but not this one? That is churn.
  • Across two sources, what is the single, de-duplicated list of customers? That is reach.

On Elasticsearch, questions like these usually end in two exports and a spreadsheet, or in a script that someone has to maintain. Elasticsearch runs each search on its own, and it has no operation that intersects two result sets or removes the duplicates between them.

The second pain is readability. A report with three steps turns into three levels of nested parentheses. It may well be correct, but nobody wants to review it, and nobody wants to change it.

Compare lists in one statement

Take orders_q1 and orders_q2, one index per quarter, a common Elasticsearch layout.

Retention: who ordered in both quarters?

SELECT customer_id FROM orders_q1
INTERSECT
SELECT customer_id FROM orders_q2;

Churn: who ordered in Q1 but not in Q2?

SELECT customer_id FROM orders_q1
EXCEPT
SELECT customer_id FROM orders_q2;

Reach: every customer who ordered in either quarter, listed once.

SELECT customer_id FROM orders_q1
UNION
SELECT customer_id FROM orders_q2;

The semantics are standard SQL, with no local dialect. UNION, INTERSECT and EXCEPT remove duplicates, and their ALL forms keep them. Like any other SELECT, each branch can carry a GROUP BY, a JOIN or a derived table.

Write the report in steps

A common table expression (CTE) gives a name to one step of a query, so the next step can build on it. Here is one: who are our biggest customers, and what tier are they on?

WITH revenue_by_customer AS (
SELECT customer_id, SUM(amount) AS revenue
FROM orders
GROUP BY customer_id
),
big_spenders AS (
SELECT customer_id, revenue
FROM revenue_by_customer
WHERE revenue > 10000
)
SELECT c.name, c.tier, b.revenue
FROM customers c
JOIN big_spenders b ON c.id = b.customer_id
ORDER BY b.revenue DESC;

Each step reads like a sentence and can be checked on its own, and a reviewer can follow the logic from top to bottom. A CTE can use any CTE declared before it.

Keep one thing in mind: a CTE is a name, not a cache. If a statement reads the same CTE twice, that CTE runs twice. When a dashboard reads the same result all day, store it instead: a materialized view can keep a cross-index JOIN as an ordinary Elasticsearch index, ready to query.

What runs where

  • UNION ALL runs on Elasticsearch, everywhere. It keeps every row of every branch, so there is nothing to de-duplicate: each branch is its own search, and the results come back in branch order. It works in the REPL, the JDBC driver, ADBC and Arrow Flight SQL, as part of the Apache-2.0 core, with nothing to install.
  • CTEs, UNION, INTERSECT and EXCEPT run on the relational engine. That engine is softclient4es-arrow-extensions 0.3.4, the one behind cross-index JOINs and derived tables. The JDBC driver, the ADBC driver and the Arrow Flight SQL server bundle it, and the REPL installer adds it by default. A REPL installed with --no-extensions refuses these statements with an error naming the construct and the missing jar. It never answers from a single branch.
  • What it costs. A set operation or a CTE costs nothing against your plan’s JOIN allowance. JOINs and correlated subqueries inside the branches count as usual; the free Community plan allows up to two per query, so the example above, with its one JOIN, fits. The relational engine is under the Elastic License 2.0: free to use, not open source.

Already using UNION ALL? Four changes to check

UNION ALL worked before this release. 0.24.0 corrects how it behaves, and some existing results can change:

  1. Columns match by position. Branches are matched column by column, from left to right, and the result takes the first branch’s column names. That is the SQL standard’s rule and what other SQL databases do. Before 0.24.0, branches were matched by name, so a column that two branches named differently came back NULL. Check that your branches list their columns in the same order, and list them explicitly rather than with SELECT *.
  2. No more partial branches. A branch without a LIMIT now returns all of its rows. Before, it could return only some of them.
  3. Mismatched branches are refused. Branches that list different numbers of columns, or types that cannot be combined, are rejected before any request is sent. Before, they ran and returned ragged or coerced rows.
  4. intersect is now a reserved word. Quote any column or alias with that name.

Good to know

  • WITH RECURSIVE is refused. Flatten hierarchies at index time, for example by storing a path or a level on each document.
  • WITH is accepted at the top of a SELECT. It is not accepted inside a subquery, a CREATE TABLE … AS SELECT, an INSERT … SELECT or a materialized view.
  • A CTE that has the same name as the index it reads is refused, with a suggestion to rename it. PostgreSQL accepts that pattern. We would rather not guess which of the two names you meant.
  • To sort or limit the combined result of UNION, INTERSECT or EXCEPT, wrap the operation in a derived table. A trailing ORDER BY or LIMIT after the last branch is refused, because it would apply to that branch alone.

The full rules, including precedence and column types, are in the set operators and CTE reference.

Try it

Terminal window
curl -fsSL https://raw.githubusercontent.com/SOFTNETWORK-APP/SoftClient4ES/main/install.sh | bash
softclient4es --host localhost --port 9200

The installer includes the relational engine, so everything above runs out of the box. Point the retention query at two of your own indices and check the answer against your spreadsheet. With --no-extensions you get the pure Apache-2.0 core, where UNION ALL still runs and every other form tells you exactly what is missing.

These features ship in core 0.24.0, with the relational engine at 0.3.4; the JDBC driver 0.3.4 bundles it.

Where to Go Next

Resources

Which list is your team still comparing in a spreadsheet? Write it as one statement, and tell us in GitHub Discussions if anything gets in the way.

P.S. Before you upgrade, look at one UNION ALL in your own code. If its branches list their columns in different orders, 0.24.0 will pair them by position, as standard SQL does, so put them in the same order first.