← 中文资源

简体中文版本

tableoid 指向行所在的分区

tableoid 是每行自带的系统列,::regclass 一转就能看到行落在哪个分区;再按它分组即可统计每个物理分区的行数。events 按 created_at 做 RANGE 分区,两条查询分别列出每行 stored_in 与按 tableoid 分组的行数,全程不需要手写分区名。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 events。 从子句角度看,用到了:用 COUNT 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

这个文件引用了哪些表?

events。

核心语句

SELECT tableoid::regclass AS partition, count(*)
FROM events
GROUP BY tableoid
ORDER BY partition;
CREATE TABLE events (
    id         bigint GENERATED ALWAYS AS IDENTITY,
    kind       text NOT NULL,
    created_at timestamptz NOT NULL
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_05 PARTITION OF events
    FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');

代码示例

CREATE TABLE events (
    id         bigint GENERATED ALWAYS AS IDENTITY,
    kind       text NOT NULL,
    created_at timestamptz NOT NULL
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2026_05 PARTITION OF events
    FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
CREATE TABLE events_2026_06 PARTITION OF events
    FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');

INSERT INTO events (kind, created_at) VALUES
    ('signup', '2026-05-14 09:00+00'),
    ('signup', '2026-06-02 11:30+00');

-- tableoid carries the oid of the physical table the row lives in
SELECT kind, created_at, tableoid::regclass AS stored_in
FROM events
ORDER BY created_at;

-- count rows per physical partition without listing partition names
SELECT tableoid::regclass AS partition, count(*)
FROM events
GROUP BY tableoid
ORDER BY partition;