SQL · Module 01: SQL Foundations & Table DesignTutorial 2 of 24

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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.

INT / BIGINT42, 10000004 / 8 bytesIDs, counts, agesDECIMAL(10,2)199.99Exact mathMoney & prices (NEVER FLOAT!)VARCHAR(n)'BigOSlate'Variable bytesNames, emails, URLsTIMESTAMP2026-11-23 14:308 bytescreated_at, orders
Always use DECIMAL(p, s) for money — FLOAT uses IEEE-754 binary approximations where 0.1 + 0.2 != 0.3!

Key Data Type Differences (Frequently Asked in Interviews!)

A. CHAR(n) vs VARCHAR(n) vs TEXT

TypeStorage BehaviorExample Use CaseWatch-Out
CHAR(n)Fixed length — right-pads shorter strings with spaces to n charsFixed-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
TEXTVariable length with no practical limit (up to 1 GB in Postgres)Blog posts, product descriptions, commentsCannot be used directly as a full-length index key in MySQL without prefix length

B. INT vs BIGINT & FLOAT vs DECIMAL(p, s)

TypePrecision / RangeUse ForAvoid For
INT (4 bytes)-2.1B to +2.1BAges, ratings, quantitiesHigh-growth user/order IDs (Twitter/Instagram overflowed 32-bit INT!)
BIGINT (8 bytes)Up to 9.2 quintillionPrimary keys (user_id, order_id)Tiny enum flags (SMALLINT saves space)
FLOAT / DOUBLEApproximate binary floating-pointGPS coordinates, ML scores, sensor readingsNEVER use for money, tax, or balances!
DECIMAL(10, 2)Exact base-10 math (10 total digits, 2 after decimal)Prices (99999999.99), salaries, ledger entriesScientific 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:

ConstraintWhat It EnforcesExample
PRIMARY KEYUNIQUE + NOT NULL (one per table)user_id BIGINT PRIMARY KEY
NOT NULLRejects missing/NULL valuesemail VARCHAR(255) NOT NULL
UNIQUENo two rows may share the same value (allows NULLs)email VARCHAR(255) UNIQUE
CHECK (...)Custom boolean rule validated on every writeCHECK (price >= 0 AND discount <= price)
DEFAULTFallback value when column is omitted in INSERTstatus VARCHAR(20) DEFAULT 'pending'

Auto-Incrementing IDs (PostgreSQL vs MySQL)

SQL
-- 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
);
SQL
-- 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):

users (Parent Table)user_id (PK)name1Aarav2Meeraorders (Child Table)order_iduser_id (FK)total5011₹9995021₹4501 : Many
Foreign Keys guarantee referential integrity: the database physically blocks inserting an order for a non-existent user_id!
SQL
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?

OptionBehavior When Parent Row Is DeletedWhen to Use
ON DELETE RESTRICT (Default)Blocks the delete with an errorFinancial records, orders, invoices (never orphan accounting data!)
ON DELETE CASCADEAutomatically deletes all child rows tooSession tokens, post likes, cart items belonging strictly to that parent
ON DELETE SET NULLKeeps child rows and sets their FK column to NULLKeeping 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):

SQL
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!)

FeatureDELETE FROM t WHERE ...TRUNCATE TABLE tDROP TABLE t
SQL FamilyDMLDDLDDL
What Gets RemovedSelected rows (or all if no WHERE)ALL rows (table structure stays)ALL rows + the table itself
Supports WHERE?✅ Yes❌ No❌ No
Speed on 10M rowsSlow (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)
SQL
-- 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

Q1.Why should you use DECIMAL(10, 2) instead of FLOAT for storing prices or bank balances?
Q2.What is the key difference between TRUNCATE TABLE logs; and DROP TABLE logs;?
Q3.Which ON DELETE rule automatically deletes all a user's active login sessions when that user account is deleted?

Keep Exploring: Related Lessons & Tools

All Courses →