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

1.1 What Is SQL, Tables & How Databases Think

Start from absolute zero: understand how relational databases store data on disk, SQL vs NoSQL differences, PostgreSQL vs MySQL vs SQLite, and the #1 secret of SQL query execution order.

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

1. Why Do Databases Exist? (Real-World Intuition)

Imagine you are building an e-commerce app like Flipkart or Amazon. At first, you might think: "Why not just save all users and orders in a CSV or Excel file?"

Here is what breaks the moment you get real traffic:

  1. Concurrency crashes: If 5,000 customers buy the last iPhone at the exact same millisecond, a plain file gets overwritten and corrupted.
  2. Speed collapses: Searching for one order inside a 50-million-row CSV requires reading the entire file from top to bottom (taking minutes!).
  3. Crash safety: If the server loses power mid-write, a plain file is left half-written.

A Relational Database Management System (RDBMS) solves all three:

  • Stores billions of rows durably on disk with crash-recovery logs (WAL).
  • Handles thousands of concurrent reads & writes safely using transactions.
  • Finds 1 exact row out of 100 million in ~2 milliseconds using B+ Tree Indexes.

SQL (Structured Query Language) is the universal, declarative language you use to talk to any RDBMS. "Declarative" means you tell the database WHAT result you want — not how to loop through rows in memory. The database's Query Optimizer figures out the fastest execution plan automatically!


2. Visual Anatomy of a Database Table

Every relational database organizes information into Tables (also called relations):

TABLE: studentsColumns (Attributes / Schema) ↓id (PK)namecoursescore101AaravPython92102MeeraSQL96103KabirDSA881 Row (Tuple)= 1 Complete RecordPrimary Key (PK): Unique & Never NULL
A table enforces a fixed Schema (Columns + Data Types), stores individual Records as Rows, and identifies every row uniquely via a Primary Key.
Database TermFormal Relational TermEveryday EquivalentStrict Rule
DatabaseSchema / CatalogAn entire Excel workbookContains multiple related tables (users, orders, payments)
TableRelationOne worksheet tab (students)Stores one specific kind of entity
ColumnAttribute / FieldA column header (score)Every value in that column must match its Data Type
RowTuple / RecordOne horizontal entryRepresents one concrete item (e.g., student Meera)
Primary Key (PK)Unique IdentifierPassport / Roll NumberStrictly UNIQUE and NOT NULL — never changes

3. Key Differences Every Beginner & Interviewee Must Know

A. SQL (Relational) vs NoSQL (Document / Key-Value)

DimensionSQL (PostgreSQL, MySQL, Oracle)NoSQL (MongoDB, Redis, DynamoDB)
Data ModelStructured tables with rows & columnsFlexible JSON documents, key-value pairs, or graphs
SchemaStrict schema enforced before writingSchema-less / dynamic per document
Relationships (JOINs)First-class, fast, normalized via Foreign KeysDenormalized (data often duplicated inside documents)
Transactions (ACID)Rock-solid multi-table ACID guaranteesTraditionally eventual consistency (limited multi-doc ACID)
Best Used ForBanking, e-commerce orders, SaaS, analyticsCaching (Redis), chat logs, CMS catalogs, IoT telemetry

B. PostgreSQL vs MySQL vs SQLite (Which One Should You Learn?)

The great news: 90% of SQL syntax is identical across all of them! Here are the practical differences:

DatabaseBest Known ForKey Technical Difference
PostgreSQLModern startups, fintech, analytics, AI (pgvector)Strictest SQL standards compliance, rich types (JSONB, arrays), ILIKE, FULL OUTER JOIN
MySQLWeb apps, WordPress, legacy & high-read backendsVery fast simple reads, uses AUTO_INCREMENT and backticks `col`, no native FULL OUTER JOIN
SQLiteMobile apps (iOS/Android), local dev, embeddedSingle .db file on disk — zero server setup required!

4. The #1 Secret of SQL: Written Order vs Execution Order

Beginners often get confused by SQL error messages like "column bonus_score does not exist in WHERE".
The reason is simple: the order you WRITE a SQL query is NOT the order the database EXECUTES it!

The #1 Secret of SQL: You WRITE SELECT first, but the Engine RUNS FROM first!1FROM / JOINLoad tables→2WHEREFilter rows→3GROUP BYMake buckets→4HAVINGFilter groups→5SELECTPick columns→6ORDER BYSort result→7LIMITTake top NWhy this matters: You CANNOT use a SELECT column alias inside WHERE!Because Step 2 (WHERE) executes BEFORE Step 5 (SELECT) even creates the alias — but ORDER BY (Step 6) CAN use it!
Notice that FROM (Step 1) and WHERE (Step 2) execute BEFORE SELECT (Step 5) — while ORDER BY (Step 6) executes AFTER SELECT!
Written Order (How You Type It)Logical Execution Order (How DB Runs It)What Happens at That Step
1. SELECT5thPicks/computes columns & creates AS aliases
2. FROM / JOIN1stLoads base table(s) and combines joined tables
3. WHERE2ndFilters individual rows (cannot see SELECT aliases!)
4. GROUP BY3rdGroups surviving rows into buckets
5. HAVING4thFilters entire groups (e.g., HAVING COUNT(*) > 5)
6. ORDER BY6thSorts final rows (CAN use SELECT aliases!)
7. LIMIT / OFFSET7thSlices the top N rows for pagination

Watch the Database Engine Execute a Query Step-by-Step

Click Next below to see the exact intermediate table inside the database engine at every step:

Tracing Your First SELECT Query
Interactive SQL Execution Tracer · Step 1 of 4 (1. FROM students)
1SELECT name, score, score + 5 AS final_score
2→FROM students
3WHERE score >= 90
4ORDER BY final_score DESC;
Live Table State · 1. FROM students4 rows
idnamecoursescore
101AaravPython92
102MeeraSQL96
103KabirDSA88
104RiyaSQL91
What the DB engine just did: Step 1: The database loads all 4 rows from the students table.

5. The 5 Families of SQL Commands (Interview Reference)

FamilyFull NameCore CommandsReal-World Purpose
DQLData Query LanguageSELECTReading, filtering, joining, and analyzing data
DDLData Definition LanguageCREATE, ALTER, DROP, TRUNCATEDefining or changing table structure (auto-commits in MySQL!)
DMLData Manipulation LanguageINSERT, UPDATE, DELETEAdding, modifying, or removing rows
TCLTransaction Control LanguageBEGIN, COMMIT, ROLLBACK, SAVEPOINTMaking multi-step writes atomic (all-or-nothing)
DCLData Control LanguageGRANT, REVOKEControlling user permissions (read-only analyst vs admin)
SQL
-- Clean, industry-standard SQL formatting:
-- 1. UPPERCASE keywords (SELECT, FROM, WHERE)
-- 2. snake_case table & column names (order_items, created_at)
-- 3. Always end statements with a semicolon (;)
SELECT
    name,
    course,
    score
FROM students
WHERE score >= 90
ORDER BY score DESC;

Beginner Watch-Out: String literals in standard SQL MUST use single quotes ('SQL'), never double quotes ("SQL"). In PostgreSQL and standard SQL, double quotes refer to column/table identifiers, not text values!


6. Mini Practice Challenge

Try solving this before peeking at the answer:
Why does the query below fail with an error, and how do you fix it?

SQL
SELECT name, salary * 12 AS annual_pay
FROM employees
WHERE annual_pay > 1200000;

7. Quick Check Your Understanding

Module 1.1 Quick Quiz

Q1.In SELECT name, score * 2 AS doubled FROM students WHERE score > 80 ORDER BY doubled DESC;, which clause runs FIRST?
Q2.Why can you use a SELECT column alias inside ORDER BY, but NOT inside WHERE?
Q3.Which quote style should you ALWAYS use for text strings in standard SQL (like 'Bengaluru')?

Keep Exploring: Related Lessons & Tools

All Courses →