SQL Modelling Flashcards

(11 cards)

1
Q

Surrogate Key

A

A surrogate key is a type of primary key.A synthetic, meaningless identifier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Natural Key or Business Key

A

A key that has real-world meaning email ,phone number ,country_code, ISO currency code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Default Rule (Production Systems)

A

Use a surrogate key as the primary key by default.
Why surrogate keys win (in practice)
Stability -
Business values change.
Primary keys should not.
Ex - email changes → FK cascade nightmare
Smaller indexes = faster joins
ORM-friendly - Works best with surrogate IDs
Safer cascades
Changing a natural PK forces:
FK updates
Locks
Long transactions
Surrogate keys never change.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Correct modelling pattern (recommended)

A

Use both:
Surrogate key → Primary Key
Natural key → Unique constraint

CREATE TABLE users (
id BIGINT PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

One-line rule you can remember

A

Primary keys are for databases, not for humans.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

UUID vs BIGINT surrogate keys

A

BIGINT

✔️ Small
✔️ Fast
✔️ Sequential
❌ Not globally unique

UUID

✔️ Globally unique
✔️ Safe for distributed systems
❌ Large index
❌ Random write amplification

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Foreign Key

A

Every value in the child column must reference an existing row in the parent table (or be NULL).
orders(id PRIMARY KEY)

order_items(
id PRIMARY KEY,
order_id BIGINT,
FOREIGN KEY (order_id) REFERENCES orders(id)
)
Meaning:

You cannot insert an order_item with order_id = 123
unless orders(id = 123) already exists

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Every FK column must have an index <Tatooable></Tatooable>

A

Foreign keys do NOT automatically create indexes on the child table
If order_items(order_id) is not indexed:
DELETE on orders
Causes full scan of order_items
Takes row locks
Spikes CPU
Blocks concurrent writes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Cascades

A

FOREIGN KEY (order_id)
REFERENCES orders(id)
ON DELETE CASCADE
DELETE order →
DB automatically deletes all order_items

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Index Working

A

Most common is B Tree. Works for =, <>,BETWEEN, ORDER BY, prefix LIKE ‘abc%’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Index - Faster reads, slower writes

A

On INSERT:
Write table row
Write to each index

On UPDATE:
Possibly update index entries

On DELETE:
Remove index entries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly