VALUES CTE Inline Lookup Join
Turn a small hand-written tuple list into an inline WITH ... AS (VALUES ...) CTE and LEFT JOIN against it, so unmatched parameters return zero rows.
Code
-- VALUES list as inline CTE: a hand-written lookup joined like a table
-- 小批量参数(人工圈定的组合清单)走 JOIN 而不是 IN,没命中的组合也保留
CREATE TEMP TABLE subscriptions (
id int PRIMARY KEY,
tenant text NOT NULL,
status text NOT NULL
);
INSERT INTO subscriptions VALUES
(1, 'acme', 'active'),
(2, 'acme', 'active'),
(3, 'acme', 'expired'),
(4, 'globex', 'trial');
WITH wanted (tenant, status) AS (
VALUES
('acme', 'active'),
('acme', 'trial'),
('globex', 'active')
)
SELECT
wanted.tenant,
wanted.status,
count(s.id) AS matches
FROM wanted
LEFT JOIN subscriptions s
ON s.tenant = wanted.tenant
AND s.status = wanted.status
GROUP BY wanted.tenant, wanted.status
ORDER BY wanted.tenant, wanted.status;A hand-written table for one query
WITH wanted (tenant, status) AS (VALUES ('acme','active'), ('acme','trial'), ('globex','active')) turns three literal tuples into an inline relation with named columns — no CREATE, no persistence, joinable like any table. The outer query LEFT JOINs it against subscriptions on both columns and counts matches per wanted pair with count(s.id), so every requested combination appears exactly once whether or not data exists for it.
The counts, unmatched pairs included
tenant | status | matches
--------+--------+---------
acme | active | 2
acme | trial | 0
globex | active | 0
acme/active matches subscriptions 1 and 2, so count(s.id) is 2. The other two wanted pairs have no rows on the right side — the LEFT JOIN keeps them and the count is 0, which is the point the file’s comment makes about keeping unmatched parameter combinations instead of letting an IN filter or an inner join silently drop them.
The line that keeps zero-match pairs
LEFT JOIN subscriptions s
ON s.tenant = wanted.tenant
AND s.status = wanted.status
Swapping to an inner join would remove the two zero rows and the report would lie by omission — count(s.id) counts non-null ids only, so unmatched pairs still count as 0 rather than 1.
Interactive Tools for This Topic
FAQ
- What relations does the SQL touch?
- The references are `subscriptions`, `wanted`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.