CHECK Violation Rejects Whole Insert
One out-of-range row fails the entire INSERT statement: CHECK constraints evaluate every row and the whole batch rolls back, so pre-validate imports.
Code
CREATE TABLE seats (
seat_id int PRIMARY KEY,
zone text NOT NULL,
price_cents int NOT NULL CHECK (price_cents BETWEEN 0 AND 50000)
);
INSERT INTO seats VALUES
(1, 'floor', 30000),
(2, 'balcony', 12000);
-- 同一条 INSERT 里第二行越界:CHECK violation 使整条语句原子回滚,
-- 第一行合法也不会落库(whole batch rejected)
INSERT INTO seats VALUES
(3, 'floor', 28000),
(4, 'mezzanine', 60000);
-- ERROR: new row for relation "seats" violates check constraint "seats_price_cents_check"
SELECT seat_id FROM seats ORDER BY seat_id;
-- 只有 1、2:一行脏数据会否掉整批,导入前先校验或分批兜底
DROP TABLE seats;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with seats among the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the seats table.
Statements that matter
CREATE TABLE seats (
seat_id int PRIMARY KEY,
zone text NOT NULL,
price_cents int NOT NULL CHECK (price_cents BETWEEN 0 AND 50000)
);
INSERT INTO seats VALUES
(3, 'floor', 28000),
(4, 'mezzanine', 60000);
INSERT INTO seats VALUES
(1, 'floor', 30000),
(2, 'balcony', 12000);
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `seats` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.