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.
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_q1INTERSECTSELECT customer_id FROM orders_q2;Churn: who ordered in Q1 but not in Q2?
SELECT customer_id FROM orders_q1EXCEPTSELECT customer_id FROM orders_q2;Reach: every customer who ordered in either quarter, listed once.
SELECT customer_id FROM orders_q1UNIONSELECT 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.revenueFROM customers cJOIN big_spenders b ON c.id = b.customer_idORDER 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 ALLruns 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,INTERSECTandEXCEPTrun on the relational engine. That engine issoftclient4es-arrow-extensions0.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-extensionsrefuses 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:
- 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 *. - No more partial branches. A branch without a
LIMITnow returns all of its rows. Before, it could return only some of them. - 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.
intersectis now a reserved word. Quote any column or alias with that name.
Good to know
WITH RECURSIVEis refused. Flatten hierarchies at index time, for example by storing a path or a level on each document.WITHis accepted at the top of aSELECT. It is not accepted inside a subquery, aCREATE TABLE … AS SELECT, anINSERT … SELECTor 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,INTERSECTorEXCEPT, wrap the operation in a derived table. A trailingORDER BYorLIMITafter 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
curl -fsSL https://raw.githubusercontent.com/SOFTNETWORK-APP/SoftClient4ES/main/install.sh | bashsoftclient4es --host localhost --port 9200The 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
- Subqueries on Elasticsearch: no rewrite, no warehouse copy: the companion post on subqueries and derived tables.
- Which forms need the relational engine: the per-venue rules in one table.
- JOINs in Elasticsearch? One SQL statement: materialized views, for the results you read all day.
Resources
- GitHub: SoftClient4ES Repository
- SQL Reference: Full SQL Documentation
- Discussions: Ask Questions
- LinkedIn: SoftNetwork
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.