bhylu.com

Advertisements

SQL Check

CHECK enforces a condition on the values being stored. Use it for rules such as positive quantities or an end date that must not precede a start date. It complements the type declaration rather than replacing it.

Understand the idea

A room reservation needs an end date after its start date. This small example stores ISO date strings consistently, so their lexical ordering matches chronological order for plain dates. Required columns use NOT NULL as well as CHECK. More complex rules spanning many rows may need a different design or controlled transaction logic.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

CREATE TABLE reservations (
  reservation_id INTEGER PRIMARY KEY,
  starts_on TEXT NOT NULL,
  ends_on TEXT NOT NULL,
  CHECK (ends_on > starts_on)
);
INSERT INTO reservations VALUES (1, '2026-03-01', '2026-03-03');
SELECT * FROM reservations;

Read the result

The two-day date interval is accepted. Reversing the dates would violate the check. The example does not detect overlapping reservations, which is a separate problem.

Try one change

Try an end date equal to the start date. Decide whether your booking rules require a positive duration or allow a same-day interval.