Union All Fanout Per Source Top K
Run one UNION ALL query where each source subquery keeps its own ORDER BY and LIMIT, so per-table top rows are computed before fanning out.
Code
CREATE TABLE news_posts (
title text,
score int,
created_at timestamptz
);
CREATE TABLE news_links (
title text,
score int,
created_at timestamptz
);
INSERT INTO news_posts VALUES
('schema diff guide', 95, now() - interval '2 hours'),
('old announcement', 40, now() - interval '10 days');
INSERT INTO news_links VALUES
('benchmark writeup', 88, now() - interval '1 hour'),
('old changelog', 12, now() - interval '20 days');
-- 每个源子查询各自带 ORDER BY + LIMIT:Top-K 先算好再做并集
SELECT * FROM (
SELECT title, score, 'posts' AS source
FROM news_posts
ORDER BY score DESC
LIMIT 1
) p
UNION ALL
SELECT * FROM (
SELECT title, score, 'links' AS source
FROM news_links
ORDER BY score DESC
LIMIT 1
) l
ORDER BY score DESC;
DROP TABLE news_posts, news_links;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with news_posts and news_links among the objects involved.
The pieces that do the work: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; a UNION combining result sets from separate queries.
Using it
Run the statement against the news_posts table; the LIMIT keeps the probe cheap while you tune the predicates.
Key statements
SELECT * FROM (
SELECT title, score, 'posts' AS source
FROM news_posts
ORDER BY score DESC
LIMIT 1
) p
UNION ALL
SELECT * FROM (
SELECT title, score, 'links' AS source
FROM news_links
ORDER BY score DESC
LIMIT 1
) l
ORDER BY score DESC;
INSERT INTO news_posts VALUES
('schema diff guide', 95, now() - interval '2 hours'),
('old announcement', 40, now() - interval '10 days');
INSERT INTO news_links VALUES
('benchmark writeup', 88, now() - interval '1 hour'),
('old changelog', 12, now() - interval '20 days');
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SPDX License LookupSearch common SPDX license identifiers and see permissions, conditions, limitations, copyleft strength, and OSI or FSF approval status.
FAQ
- Which objects does the SQL touch?
- `news_posts`, `news_links` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.