实现说明
这个文件依次执行 SELECT / INSERT / CREATE / EXPLAIN 语句,涉及 audit_events、generate_series。
从子句角度看,用到了:WHERE 决定这条语句会作用到哪些行;用 COUNT 做聚合;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。
常见问题
这个脚本里出现了哪些表?
audit_events、generate_series。
核心语句
INSERT INTO audit_events (kind, detail)
SELECT
CASE WHEN g % 1000 = 0 THEN 'security_alert' ELSE 'heartbeat' END,
'event ' || g
FROM generate_series(1, 50000) AS g;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM audit_events WHERE detail = 'event 777';
CREATE TABLE audit_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
kind text NOT NULL,
detail text NOT NULL,
occurred_at timestamptz NOT NULL DEFAULT now()
);
代码示例
CREATE TABLE audit_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
kind text NOT NULL,
detail text NOT NULL,
occurred_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO audit_events (kind, detail)
SELECT
CASE WHEN g % 1000 = 0 THEN 'security_alert' ELSE 'heartbeat' END,
'event ' || g
FROM generate_series(1, 50000) AS g;
ANALYZE audit_events;
-- detail has no index, so the only plan is a seq scan; EXPLAIN ANALYZE then
-- reports how many rows the filter threw away after reading them all
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM audit_events WHERE detail = 'event 777';
CREATE INDEX audit_events_detail_idx ON audit_events (detail);
ANALYZE audit_events;
-- same query, one matching row: the plan switches to the index and the
-- filter waste disappears
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM audit_events WHERE detail = 'event 777';