FOREIGN KEY
- SQL course
- Beginner
- Lesson 97/115
- 4 min
Relate two tables with FOREIGN KEY.
CHECK
With CHECK you apply a condition to a column. Values failing the condition cannot be inserted.
CREATE TABLE products (
id INT PRIMARY KEY,
price DECIMAL(10,2) CHECK (price > 0)
);Price must be positive; negative prices are blocked.
The table products is created.
CHECK — details
The CHECK condition is verified on every INSERT and UPDATE. Complex conditions work too: CHECK (price > 0 AND stock >= 0).
Practice CHECK
Create products with id INT PRIMARY KEY and price DECIMAL(10,2) CHECK (price > 0).
Starter code
-- constrained table
CREATE TABLE productsSample solution
CREATE TABLE products (
id INT PRIMARY KEY,
price DECIMAL(10,2) CHECK (price > 0)
)Expected output
Tablo oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 FOREIGN KEY: match the terms
| Term | Meaning |
|---|---|
CHECK |
check |
UNIQUE |
unique |
PRIMARY KEY |
primary |
NOT NULL |
not null |
2 Apply check
CREATE TABLE products (
price DECIMAL(10,2) ____ (price > 0)
);
CREATE TABLE products (
price DECIMAL(10,2) CHECK (price > 0)
);
Explanation: CHECK (price > 0) checks the condition on every insert and update; 0 or less is rejected.
3 When is CHECK verified?
- Never
- Only when querying
- Only when deleting
- On every insert and update Correct answer
Explanation: CHECK is verified on every INSERT and UPDATE.