Skip to content

Commit 6b70115

Browse files
committed
constraints in sql
1 parent 74f2982 commit 6b70115

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
-- Create a contacts table with unique phone numbers
2+
CREATE TABLE contacts (
3+
name VARCHAR(100) NOT NULL,
4+
phone VARCHAR(15) NOT NULL UNIQUE
5+
);
6+
7+
-- Insert a valid contact
8+
INSERT INTO contacts (name, phone)
9+
VALUES ('billybob', '8781213455');
10+
11+
-- This will cause an error due to UNIQUE constraint violation on phone
12+
-- INSERT INTO contacts (name, phone)
13+
-- VALUES ('billybob', '8781213455');
14+
15+
-- Create a users table with a CHECK constraint on age
16+
CREATE TABLE users (
17+
username VARCHAR(20) NOT NULL,
18+
age INT CHECK (age > 0)
19+
);
20+
21+
-- Attempt to create a palindromes table with a CHECK using REVERSE (this will likely fail in many RDBMS as REVERSE is not allowed in CHECK)
22+
CREATE TABLE palindromes (
23+
word VARCHAR(100) CHECK (REVERSE(word) = word)
24+
);
25+
26+
-- Safer version with named CHECK constraint on users2 table
27+
CREATE TABLE users2 (
28+
username VARCHAR(20) NOT NULL,
29+
age INT,
30+
CONSTRAINT age_not_negative CHECK (age >= 0)
31+
);
32+
33+
-- Another attempt at a palindrome table using a named CHECK constraint
34+
CREATE TABLE palindromes2 (
35+
word VARCHAR(100),
36+
CONSTRAINT word_is_palindrome CHECK (REVERSE(word) = word)
37+
);
38+
39+
-- Create a companies table with a composite UNIQUE constraint on name and address
40+
CREATE TABLE companies (
41+
name VARCHAR(255) NOT NULL,
42+
address VARCHAR(255) NOT NULL,
43+
CONSTRAINT name_address UNIQUE (name, address)
44+
);
45+
46+
-- Create a houses table with a CHECK constraint to ensure sale price ≥ purchase price
47+
CREATE TABLE houses (
48+
purchase_price INT NOT NULL,
49+
sale_price INT NOT NULL,
50+
CONSTRAINT sprice_gt_pprice CHECK (sale_price >= purchase_price)
51+
);

0 commit comments

Comments
 (0)