1.2 Data Types, CREATE TABLE, Primary Keys & Foreign Keys
Learn how to design rock-solid tables: CHAR vs VARCHAR vs TEXT, DECIMAL vs FLOAT, auto-increment IDs, Primary/Composite/Foreign Keys, ON DELETE behaviors, and DELETE vs TRUNCATE vs DROP.
1. Choosing the Right SQL Data Types (And Why It Matters)
Every column in SQL has a strict Data Type. Picking the right one prevents silent bugs (like losing ₹0.01 on every payment!), saves gigabytes of RAM/disk, and makes indexes significantly faster.
Key Data Type Differences (Frequently Asked in Interviews!)
A. CHAR(n) vs VARCHAR(n) vs TEXT
| Type | Storage Behavior | Example Use Case | Watch-Out |
|---|---|---|---|
CHAR(n) | Fixed length — right-pads shorter strings with spaces to n chars | Fixed-length codes: country_code CHAR(2) ('IN', 'US'), currency CHAR(3) ('INR') | Wastes space for variable-length names! |
VARCHAR(n) | Variable length up to max n chars (stores only actual length + 1–2 bytes) | name VARCHAR(100), email VARCHAR(255) | Enforces a clean upper length guardrail |
TEXT | Variable length with no practical limit (up to 1 GB in Postgres) | Blog posts, product descriptions, comments | Cannot be used directly as a full-length index key in MySQL without prefix length |
B. INT vs BIGINT & FLOAT vs DECIMAL(p, s)
| Type | Precision / Range | Use For | Avoid For |
|---|---|---|---|
INT (4 bytes) | -2.1B to +2.1B | Ages, ratings, quantities | High-growth user/order IDs (Twitter/Instagram overflowed 32-bit INT!) |
BIGINT (8 bytes) | Up to 9.2 quintillion | Primary keys (user_id, order_id) | Tiny enum flags (SMALLINT saves space) |
FLOAT / DOUBLE | Approximate binary floating-point | GPS coordinates, ML scores, sensor readings | NEVER use for money, tax, or balances! |
DECIMAL(10, 2) | Exact base-10 math (10 total digits, 2 after decimal) | Prices (99999999.99), salaries, ledger entries | Scientific physics simulations |
2. Building Tables with Guardrails (CREATE TABLE + Constraints)
Application code changes every week, and bugs slip through. Database Constraints act as an unbreakable safety net directly inside the database engine:
| Constraint | What It Enforces | Example |
|---|---|---|
PRIMARY KEY | UNIQUE + NOT NULL (one per table) | user_id BIGINT PRIMARY KEY |
NOT NULL | Rejects missing/NULL values | email VARCHAR(255) NOT NULL |
UNIQUE | No two rows may share the same value (allows NULLs) | email VARCHAR(255) UNIQUE |
CHECK (...) | Custom boolean rule validated on every write | CHECK (price >= 0 AND discount <= price) |
DEFAULT | Fallback value when column is omitted in INSERT | status VARCHAR(20) DEFAULT 'pending' |
Auto-Incrementing IDs (PostgreSQL vs MySQL)
-- PostgreSQL (Modern SQL Standard)
CREATE TABLE users (
user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
age INT CHECK (age >= 13),
role VARCHAR(20) NOT NULL DEFAULT 'learner',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- MySQL equivalent (uses AUTO_INCREMENT)
CREATE TABLE users (
user_id BIGINT AUTO_INCREMENT PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
age INT CHECK (age >= 13),
role VARCHAR(20) NOT NULL DEFAULT 'learner',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
3. Foreign Keys & Referential Integrity (1-to-Many)
Instead of duplicating a user's full_name and email inside every single order row, orders stores only a Foreign Key (user_id) referencing users(user_id):
CREATE TABLE orders (
order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL,
total_amt DECIMAL(10, 2) NOT NULL CHECK (total_amt > 0),
status VARCHAR(20) NOT NULL DEFAULT 'pending',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_user
FOREIGN KEY (user_id)
REFERENCES users(user_id)
ON DELETE RESTRICT
);
Understanding ON DELETE Actions (Huge Interview Favorite!)
What happens if someone runs DELETE FROM users WHERE user_id = 1; while user 1 still has 5 orders?
| Option | Behavior When Parent Row Is Deleted | When to Use |
|---|---|---|
ON DELETE RESTRICT (Default) | Blocks the delete with an error | Financial records, orders, invoices (never orphan accounting data!) |
ON DELETE CASCADE | Automatically deletes all child rows too | Session tokens, post likes, cart items belonging strictly to that parent |
ON DELETE SET NULL | Keeps child rows and sets their FK column to NULL | Keeping historical audit logs after an employee leaves |
Bonus: Composite Primary Keys (Many-to-Many Join Tables)
What if a student can enroll in many courses, and a course has many students? You prevent duplicate enrollments using a Composite Primary Key across (student_id, course_id):
CREATE TABLE enrollments (
student_id BIGINT NOT NULL REFERENCES users(user_id),
course_id BIGINT NOT NULL,
enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (student_id, course_id)
);
4. DELETE vs TRUNCATE vs DROP (Top 3 Interview Comparison!)
| Feature | DELETE FROM t WHERE ... | TRUNCATE TABLE t | DROP TABLE t |
|---|---|---|---|
| SQL Family | DML | DDL | DDL |
| What Gets Removed | Selected rows (or all if no WHERE) | ALL rows (table structure stays) | ALL rows + the table itself |
Supports WHERE? | ✅ Yes | ❌ No | ❌ No |
| Speed on 10M rows | Slow (logs every single row deletion) | Instant (deallocates data pages) | Instant |
Can ROLLBACK? | ✅ Yes (inside a transaction) | PostgreSQL: Yes · MySQL: No! | PostgreSQL: Yes · MySQL: No! |
| Resets Auto-Increment? | ❌ No | ✅ Yes (in MySQL; RESTART IDENTITY in Postgres) | N/A (table is gone) |
-- Safe schema evolution with ALTER TABLE
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
ALTER TABLE users RENAME COLUMN full_name TO name;
ALTER TABLE users DROP COLUMN IF EXISTS legacy_tag;
5. Quick Check Your Understanding
Module 1.2 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.