实现说明
这个文件依次执行 SELECT / INSERT / CREATE / ALTER / EXPLAIN 语句,涉及 incidents。
incidents 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。
用到的 SQL 构件:WHERE 把语句的作用范围收窄到满足条件的行;CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。
常见问题
这个脚本里出现了哪些表?
incidents。
核心语句
EXPLAIN (COSTS OFF)
SELECT id
FROM incidents
WHERE status = 'open'
AND created_at > now() - interval '1 day';
CREATE INDEX incidents_open_created_idx
ON incidents (created_at)
WHERE status = 'open';
CREATE TEMP TABLE incidents (
id bigint PRIMARY KEY,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
代码示例
-- partial index predicate must be IMMUTABLE: now() is STABLE
CREATE TEMP TABLE incidents (
id bigint PRIMARY KEY,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO incidents VALUES
(1, 'open', now() - interval '1 day'),
(2, 'closed', now() - interval '40 days');
-- 想给“最近 30 天”建 partial index:谓词里的 now() 随时间漂移,直接被拒
-- ERROR: functions in index predicate must be marked IMMUTABLE
-- CREATE INDEX incidents_recent_idx ON incidents (created_at)
-- WHERE created_at > now() - interval '30 days';
-- 现实解法:谓词用稳定字段(status),时间条件留在查询里
CREATE INDEX incidents_open_created_idx
ON incidents (created_at)
WHERE status = 'open';
EXPLAIN (COSTS OFF)
SELECT id
FROM incidents
WHERE status = 'open'
AND created_at > now() - interval '1 day';
-- 对照:CHECK 约束没有易变性限制,stable/volatile 函数可用,写入时逐行检查
ALTER TABLE incidents
ADD CONSTRAINT incidents_created_not_future
CHECK (created_at < now() + interval '1 hour');