sqlcmd.net validated sql reference
intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Validate Column Values With CHECK

Use a `CHECK` constraint to reject rows whose values fall outside an allowed rule.

Docker-validated Not currently validation-green

Allow only non-negative inventory quantities

Both inserted rows satisfy quantity >= 0, so they are stored. A later insert such as quantity = -1 would violate the CHECK constraint and be rejected before bad data entered the table.

Shared across supported engines.
SQL
CREATE TABLE inventory (
  id INT,
  item VARCHAR(50),
  quantity INT,
  CONSTRAINT chk_inventory_quantity CHECK (quantity >= 0)
);

INSERT INTO
  inventory (id, item, quantity)
VALUES
  (1, 'Widget', 12),
  (2, 'Gadget', 0);

SELECT
  id,
  item,
  quantity
FROM
  inventory
ORDER BY
  id;
Returned rows for the shared example.
iditemquantity
1Widget12
2Gadget0

The accepted rows and returned result are identical across supported engines.

Where this command helps.

  • preventing negative quantities or prices from entering a table
  • keeping simple validation rules close to the data instead of only in application code

What the command is doing.

A CHECK constraint stores a data-quality rule in the table definition. The database evaluates the rule whenever rows are inserted or updated, and rejects rows that do not satisfy it. Use CHECK for simple row-level rules such as non-negative quantities, allowed ranges, or relationships between columns in the same row.