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.

SqlData Fetching

Code

snippet
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

FAQ

Which objects does the SQL touch?
`news_posts`, `news_links` — referenced directly, no join needed.