SELECT INTO STRICT Enforces Row Counts
PL/pgSQL SELECT INTO STRICT raises no_data_found or too_many_rows on bad row counts, while the loose form silently takes the first row.
Code
CREATE TEMP TABLE account_status (
account text PRIMARY KEY,
status text NOT NULL
);
INSERT INTO account_status VALUES
('ada', 'active'),
('bob', 'locked');
-- 不带 STRICT:多行静默取第一行,零行则变量被赋 NULL——两类隐患都不报错
DO $$
DECLARE
picked text;
BEGIN
SELECT status INTO picked FROM account_status ORDER BY account;
RAISE NOTICE 'loose pick: %', picked;
END $$;
-- NOTICE: loose pick: active
-- STRICT:行数不对立刻抛错,条件名是 no_data_found 与 too_many_rows
DO $$
DECLARE
picked text;
BEGIN
BEGIN
SELECT status INTO STRICT picked FROM account_status;
EXCEPTION WHEN too_many_rows THEN
RAISE NOTICE 'strict refused multi-row result';
END;
BEGIN
SELECT status INTO STRICT picked FROM account_status WHERE account = 'missing';
EXCEPTION WHEN no_data_found THEN
RAISE NOTICE 'strict refused empty result';
END;
END $$;
-- NOTICE: strict refused multi-row result
-- NOTICE: strict refused empty resultThe structural read
SELECT / INSERT / CREATE statements share the script, touching account_status, picked and strict.
account_status is set up right here as a session-local temp table — there is no prior setup to arrange for, and ending the session drops it again.
In terms of clauses, the statements use: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The file sets up its own scratch surface: it builds the session-local tables it works with (account_status), so one full run against a throwaway database is enough.
Statements that matter
DO $$
DECLARE
picked text;
BEGIN
SELECT status INTO picked FROM account_status ORDER BY account;
RAISE NOTICE 'loose pick: %', picked;
END $$;
CREATE TEMP TABLE account_status (
account text PRIMARY KEY,
status text NOT NULL
);
INSERT INTO account_status VALUES
('ada', 'active'),
('bob', 'locked');
Interactive Tools for This Topic
FAQ
- What relations does the SQL touch?
- `account_status`, `picked`, `strict`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.