Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
CHECK constraints with a simple condition
CHECK constraints with complex conditions
7. Complex conditions with multiple columns
Adding CHECK constraints to existing tables
Summary

Instruction

Nice! You should also know that we can use other columns in the CHECK constraint as well. Take a look at the example below:

CREATE TABLE video_game (
  id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  name varchar(32) UNIQUE NOT NULL,
  genre varchar(32) NOT NULL,
  studio varchar(32),
  multiplayer boolean,
  hours integer,
  price decimal(5, 2),
  CHECK (price/hours < 1.00)
);

In the example above, the database will only allow you to enter relatively cheap video games, where the result of the game's cost divided by the hours of playing is low.

Exercise

We put the constraint from our example into the database. Let's try to insert a new game that meets the criteria. Insert a game called 'Disciples II' into the video_game table:

  1. genre is 'Strategy'.
  2. studio is 'Dat'.
  3. multiplayer is TRUE.
  4. hours are 150.
  5. price is 29.99.