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

Instruction

Let's get started. Take a look at the following example:

CREATE TABLE video_game (
  id 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 CHECK (hours > 0),
  price decimal(5, 2) CHECK (price > 0)
);

As you can see, we added the keyword CHECK to two columns, followed by a logical condition inside parentheses. For example, the price column value cannot be 0 or less because of the condition we set (price > 0). The database will ensure that this condition is always met.

Exercise

Run the template code to create the video_game table with the new constraint CHECK. The new columns which may require some explanation are:

  1. multiplayer – This column tells us whether a specific game has a multiplayer mode.
  2. hours – This column stores the estimated number of hours necessary to complete the game.