This error occurs because PostgreSQL is inferring the data type of the combination column differently between the non-recursive term (the first SELECT in the UNION ALL) and the recursive term (the second SELECT in the UNION ALL).
Here's what's happening:
-
In the non-recursive term (base case), you're casting product_id to VARCHAR(1000):
CAST(product_id AS VARCHAR(1000)) AS combination
PostgreSQL sees this and assumes combination should be VARCHAR(1000).
-
In the recursive term, CONCAT returns a generic VARCHAR (not VARCHAR(1000) explicitly). PostgreSQL infers this as just VARCHAR (without a length limit), which conflicts with the VARCHAR(1000) from the base case.
To fix this, explicitly cast the result of CONCAT to VARCHAR(1000) in the recursive term:
WITH RECURSIVE ordered AS (
SELECT
transaction_id,
product_id,
ROW_NUMBER() OVER (PARTITION BY transaction_id ORDER BY product_id) AS rn,
COUNT(*) OVER (PARTITION BY transaction_id) AS cnt
FROM transactions
WHERE product_id IS NOT NULL
),
recursive_combinations AS (
-- Base case: Start with the first product in each multi-product transaction
SELECT
transaction_id,
CAST(product_id AS VARCHAR(1000)) AS combination, -- VARCHAR(1000) here
rn
FROM ordered
WHERE rn = 1 AND cnt > 1
UNION ALL
-- Recursive step: Append the next product
SELECT
o.transaction_id,
CAST(CONCAT(rc.combination, ', ', o.product_id) AS VARCHAR(1000)) AS combination, -- CAST CONCAT result to VARCHAR(1000)
o.rn
FROM recursive_combinations rc
JOIN ordered o ON rc.transaction_id = o.transaction_id AND o.rn = rc.rn + 1
)
SELECT DISTINCT combination
FROM recursive_combinations
ORDER BY combination;
What changed?
- Added
CAST(... AS VARCHAR(1000)) around the CONCAT in the recursive term.
- Now both parts of the
UNION ALL agree on the exact type: VARCHAR(1000).
This should resolve the type mismatch error and let your query run smoothly in PostgreSQL.
Alternative Fix (if you prefer TEXT over VARCHAR(1000)):
If you don't care about the exact length limit, you can simplify the casts to TEXT:
CAST(product_id AS TEXT) AS combination
...
CAST(CONCAT(rc.combination, ', ', o.product_id) AS TEXT) AS combination
TEXT is PostgreSQL's flexible string type (equivalent to VARCHAR without a length limit). This avoids the length mismatch issue altogether.
Try it, and you should get the output like:
111, 222, 444