Module 1 › Writing Your First Queries — SELECT, DDL & DML

Writing Your First Queries: From SELECT to Building & Modifying Data

Module 1, Session 3. Master standalone SELECT, expressions, aliases, psql catalog navigation, the LIMIT safety net, DDL table architecture, and DML row modification.

Jo class mein bola, yahan nukte mein likha hai.
What I said in class, written here as key points.

← All NukteSELECT * FROM TheShiraverse

Writing Your First SQL Queries

From writing your first queries with SELECT, expressions, and psql exploration, to building durable relational structures with DDL and breathing life into tables with DML.

38
Interactive Scenes
3
Practice Arenas
12
Hands-on Drills
10
Interview Scenarios

Today's Agenda — SELECT, DDL & DML

Mastering standalone SELECT evaluation, psql database reconnaissance, DDL table architecture, and DML data manipulation.

Phase 01 ⚡ First Queries & psql
01 Library Catalog & Mental Model 📚 Story

Declarative queries vs manual ledger chaos at St. Xavier's.

02 SELECT Without FROM & Aliases 🧮 Runtime

Evaluating arithmetic, dates, system functions, and AS labels.

03 psql Recon & LIMIT Safety Net ⚔️ Arena 1

\dn, \dt, \d inspection and preventing terminal crashes with LIMIT.

Phase 02 🏛️ DDL: Building Structures
04 Architect, Builder & Resident 🏡 Story

The 3 languages of SQL and the intentional all-TEXT strategy.

05 CREATE DATABASE & SCHEMA 🏛️ Folders

Physical containers and logical department namespace partitions.

06 CREATE TABLE, ALTER & DROP ⚔️ Arena 2

Idempotent IF NOT EXISTS, schema mutations, and DROP vs TRUNCATE.

Phase 03 🚀 DML: Data Modification
07 The Empty College Story 🏫 Story

Why empty DDL structures need living rows of data.

08 INSERT, UPDATE & The WHERE Trap ⚠️ Safety

Multi-row inserts, RETURNING, and the danger of unconstrained updates.

09 DML Drills & Interview Studio 💼 Arena 3

Hands-on student enrollment drills + 10 master interview scenarios.

🎯
Primary Mission Master standalone queries, schema architecture, and safe data modifications from the ground up.
⚔️
3 Live Query Arenas Execute basic queries, build Prestige College tables, and run safe data modifications.
💼
10 Tech Interview Scenarios Master DDL vs DML, DROP vs TRUNCATE vs DELETE, and production psql reconnaissance.

Your SQL Journey So Far

A two-minute bridge from foundational theory to practical database manipulation.

SESSION 01
What is SQL & RDBMS
  • Relational Awakening: Why every app secretly runs on a database — every tap triggers SQL.
  • Data → Information: Raw facts become searchable, filterable, joinable records inside tables.
  • SQL vs NoSQL: The 80/20 rule — why relational wins most real-world analyst jobs.
  • Database vs DBMS: The warehouse (data) vs the manager (the engine that runs it).
SESSION 02
How SQL is Organised
  • Table Vocabulary: Rows, columns, keys, data types — the grammar every database speaks.
  • Database Hierarchy: Cluster → Database → Schema → Table → Column → Cell.
  • 5 SQL Command Types: DDL, DML, DQL, DCL, TCL — every command fits one of these.
  • Declarative Thinking: Tell the engine what you want, not how to get it.
THE MISSING LINK TODAY BRIDGES:
In Sessions 1 & 2, we understood what databases are and how they are organised. But you haven't written a single query, built a single table, or inserted a single row! Today, you become an active SQL practitioner.
📚
St. Xavier's Library • Catalog Crisis THE PHYSICAL LEDGER vs RELATIONAL QUERY ENGINE
ANALOGY • 12,000 BOOKS 🕘 FRIDAY 3:00 PM • PRINCIPAL'S QUERY
STEP 01 • THE INCIDENT
principal-office 3:00 PM • Today
“How many Physics books are currently checked out by Grade 12 students? Need this list for the science inspection in 15 minutes.”
Mrs. Sharma manages 12,000 books across 4 thick bound registers. Manual cross-referencing takes 3 full days of page flipping.
STEP 02 • THE BOTTLENECK
📖 Manual Ledgers
3 Days
Linear search across 4 physical registers. Human indexing errors, missing receipts, and zero cross-filtering.
PostgreSQL PostgreSQL Engine
0.004s
Single declarative query joins lending, books, and students. Filtered result in 4 milliseconds.
STEP 03 • THE QUERY ENGINE
⚡ 4ms
pgAdmin 4 • Query Tool
SELECT   b.title,
         s.student_name,
         l.due_date
FROM     library.lending l
JOIN     library.books b 
         ON l.book_id = b.book_id
JOIN     library.students s 
         ON l.student_id = s.student_id
WHERE    b.subject = 'Physics'
  AND    s.grade = 12;
⚡ 4ms • Rows: 3 ✅ 14 MINS EARLY
STEP 04 • CORE PRINCIPLE
The Moral: You do not instruct SQL how to search row-by-row; you declare WHAT data you need and the engine retrieves it instantly.

Translating the Library to PostgreSQL

The Physical to Relational Mapping
ROSETTA STONE • 6 CORE PRIMITIVES

Every physical object in Mrs. Sharma's library directly corresponds to an essential PostgreSQL relational primitive:

Physical Library Object SQL Relational Equivalent Production Database Example
🏛️ The Library Building Database retailmart
🗂️ Departmental Book Shelves Schema college, sales
📖 A Bound Register Book Table college.students
📝 One Handwritten Line Entry Row (Record / Tuple) Student '1', 'Aarav'
🏷️ Register Column Headers Column (Attribute) first_name, email
🔍 Asking Mrs. Sharma for a Book SQL Query (SELECT) SELECT * FROM college.students;
💡
The Crucial Insight: Databases didn't invent new business concepts — they formalized the physical filing systems humans have used for centuries, making them instantly searchable with mathematical precision.
🧮
The Calculator Test • Computational Runtime THE UNBOXING INTUITION • SELECT WITHOUT A TABLE
INTUITION BUILDER ⚡ UNBOXING MOMENT
STEP 01 • THE QUESTION
new-student-onboarding First Day Instinct
“Sir, doesn't every single SQL query require a FROM clause to pull rows from a table? How can we query before loading RetailMart?”
When you unbox a new calculator, you don't start with calculus. You punch 1 + 1 = 2 to verify the engine is alive.
STEP 02 • THE ENGINE REALITY
❌ Common Misconception
"Every SELECT statement must have a FROM clause and read physical blocks from a hard drive table."
PostgreSQL The PostgreSQL Reality
PostgreSQL is a full computational runtime. SELECT evaluates scalar math, string transforms, and system introspection instantly in memory.
STEP 03 • LIVE EXECUTION
⚡ 0.1ms
pgAdmin 4 • Query Tool
▶ Run Query
SELECT 42 AS answer;
SELECT 25 * 4 AS calculation;
SELECT version();
⚡ Standalone • No Disk I/O ✅ ENGINE VERIFIED
STEP 04 • CORE PRINCIPLE
The Moral: Master SELECT without a table first; it will become your primary testing and debugging superpower.

What is an SQL Query?

Declarative vs Imperative

An SQL query tells the database what you want — not how to get it. The engine figures out the execution plan.

🍽️ The Restaurant Analogy:

When you go to a restaurant, you order: "Butter Paneer with 2 Garlic Naans."
You do not tell the chef: "Walk 4 steps left, open the fridge, pick 200g cottage cheese, heat the pan to 180°C, stir clockwise for 3 minutes."

Python / Java (Imperative): You write every loop, step, and algorithm.
SQL (Declarative): You state the desired outcome — the engine compiles the optimal execution plan.
🎯 ANATOMY OF A QUERY
SELECT <what columns>
FROM   <which table>
WHERE  <condition> -- optional
LIMIT   10 -- optional
⚡ YOUR FIRST QUERY
▶
SELECT 'Hello, SQL!';

No table needed. No FROM clause. SQL can evaluate expressions standalone — this is the superpower you'll use in this session.

Basic SELECT Queries pgAdmin 4
LITERALSRaw Constants
-- Numeric constant
SELECT 42;

-- Text string literal
SELECT 'Hello, TheShiraverse!';
Single quotes 'text' for strings. Double quotes "col" for identifiers only.
ARITHMETICMath Operators
-- Multiplication, division, addition
SELECT 25 * 4;
SELECT 100 / 4;
SELECT 10 + 5 * 2; -- PEMDAS (20)
Standard mathematical operator precedence applies — PEMDAS order.
MULTI-EXPRMultiple Columns
-- Multiple expressions at once
SELECT
  100 AS base,
  100 * 0.18 AS gst,
  100 * 1.18 AS total;
Each comma-separated expression becomes a separate column in the output.
SYSTEMBuilt-in Functions
-- Engine diagnostics & timestamps
SELECT version();
SELECT current_database();
SELECT current_date, current_time;
Built-in functions inspect the running PostgreSQL server and active session.
65%
Practice Milestone 01

Query Mode: Unlocked — SELECT & Basic Queries

Time to get your hands dirty! Standalone arithmetic, string manipulation, system introspection, and safe table inspection across 4 challenge gates.

🧠Practice Time

Key Takeaways & The Semicolon Rule

💡 The Versatility of SELECT
▶

SELECT is the most versatile SQL command on Earth. It functions as a calculator, a clock, a system inspector, and a data retriever without needing a table.

SELECT 100 * 1.18 AS calculator;
SELECT current_timestamp AS clock;
SELECT version() AS system_inspector;
Core Realization: Never think of SQL as merely "looking up rows in Excel." It is a full relational execution engine capable of mathematical, boolean, and functional computations.
⚡ The Semicolon Rule (;)
▶

PostgreSQL waits patiently for the semicolon before executing. Forgetting it is the #1 beginner mistake — your query appears to hang, but it's just waiting for termination!

-- Correct termination:
SELECT 42;

-- What happens without semicolon in psql:
retailmart=# SELECT 42
retailmart-# ; -- The dash (# -> -#) indicates continuation line!
The psql Prompt Tell: retailmart=# means ready for a new statement. retailmart-# means PostgreSQL is still waiting for the statement to terminate with ;.
⚠️ COMMON MISTAKE Forgetting the Semicolon Terminator (;)
❌ THE MISTAKE
Pressing Enter Without Semicolon
retailmart=# SELECT 1 + 1
retailmart-# 
retailmart-# [Pressing Enter repeatedly]
retailmart-# Nothing happens! Cursor just moves down!
Typing SELECT 1 + 1 and pressing Enter. Nothing happens. The cursor just moves down. Beginners panic thinking PostgreSQL crashed or froze.
✅ THE FIX
Add the Semicolon Terminator (;)
▶
retailmart-# ;
 ?column? 
----------
        2
(1 row)

retailmart=# 
Every SQL statement MUST end with a semicolon: SELECT 1 + 1; — the semicolon tells PostgreSQL: "I'm done, compile and execute this now!"

Column Aliases & The Standalone SELECT Superpower ⚡

Two essential production habits: renaming output streams cleanly with AS and using PostgreSQL as a rapid testing scratchpad.

🏷️ The AS Keyword & Column Aliases
▶

Output Renaming vs Table Mutation: An alias renames the column header in your query output — it never alters or renames the underlying table data on disk.

-- Without alias: column header defaults to 'current_date'
SELECT current_date;

-- With alias: column header cleanly displays as 'today'
SELECT current_date AS today;

The AS keyword is technically optional (SELECT current_date today; works), but ALWAYS write AS explicitly in production code.

⚠️ The Missing Comma Trap: Omitting AS causes catastrophic bugs when a comma is deleted: SELECT first_name last_name FROM users; accidentally aliases first_name as last_name instead of fetching two columns!
🛠️ SELECT Without a Table (Superpower)
▶

Your Engineering Swiss Army Knife: Most tutorials claim every SELECT requires FROM. In PostgreSQL, you can evaluate standalone expressions without querying any table.

-- Fast math without opening Python or a calculator:
SELECT 100 * 1.18 AS price_with_tax;

-- Test string/date functions before touching production tables:
SELECT UPPER('theshiraverse') AS preview;

-- Generate instant mock sequences on the fly:
SELECT generate_series(1, 5) AS sample_seq;
🎯 The Senior Habit: Never test untrusted regex patterns, math formulas, or timestamp transformations directly against lakhs of production records. Always validate the calculation with standalone SELECT first!

psql Terminal Masterclass: Navigation & Reconnaissance 🧭

The essential command-line playbook for exploring databases, inspecting catalogs, and querying safely without a GUI.

STEP 1
Connection & Cluster

Confirm your environment, list cluster databases, and switch active connections instantly:

-- Check active DB, user, host & port:
retailmart=# \conninfo

-- List all databases on the cluster:
retailmart=# \l

-- Switch database connection:
retailmart=# \c retailmart
Slash vs Semicolon Rule: Backslash commands (\l, \c) are client meta-commands — never add a semicolon. SQL statements (SELECT) are sent to the engine and must end with ;.
STEP 2
Catalog Reconnaissance

Discover schemas, inspect relations, and avoid the empty public trap:

-- List all 16 schema namespaces:
retailmart=# \dn

-- Inspect tables in specific schema:
retailmart=# \dt sales.*

-- Dump all 55 tables across all schemas:
retailmart=# \dt *.*
The \dt Default Trap: By default, \dt only searches the public schema. In enterprise databases partitioned into domain schemas, \dt appears empty. Always run \dt *.*!
STEP 3
Inspection & LIMIT Safety
▶

Describe columns, types, and primary keys, then sample rows with qualified names:

-- Describe table columns & datatypes:
retailmart=# \d sales.orders

-- Extended details (indexes, storage):
retailmart=# \d+ sales.orders

-- ALWAYS qualify with schema + LIMIT:
SELECT * FROM sales.orders LIMIT 10;
⚠️ The No-LIMIT Crash: Running unbounded SELECT * FROM sales.orders; against massive enterprise tables dumps gigabytes of raw data, freezing your terminal. Always cap with LIMIT 10.
⚡ Pro Toolkit Everyday psql Shortcuts Seniors Rely On:
\q Exit terminal (or Ctrl+D)
\x auto Expanded view (flips wide tables into vertical records)
\timing Execution stopwatch (tracks ms per query)
\? / \h Built-in manuals (\? client / \h SQL)
🏢
The First Week at Any Data Job • RetailMart Recon THE LIVE PRODUCTION ONBOARDING • ZERO DOCUMENTATION
CASE STUDY • 24 LAKH ROWS 🕘 MONDAY 9:30 AM • LEAD'S SLACK MESSAGE
STEP 01 • THE INCIDENT
analytics-lead 9:30 AM • Monday Morning
“Welcome to RetailMart! Here is your connection string: postgresql://prod-db:5432/retailmart. Tell us what schemas we have and inspect the structure of sales.orders.”
There is no documentation. No PDF. No ER diagram. Just an unfamiliar production terminal and 24 lakh rows.
STEP 02 • THE SHOWDOWN
❌ The Rookie Guess
CRASH
Runs SELECT * FROM orders; (error: no schema), then SELECT * FROM sales.order_items; with no LIMIT: 3,75,202 rows flood the screen and the terminal crawls.
PostgreSQL The Professional
0.004s
Systematic reconnaissance: \dn → \dt sales.* → \d sales.orders → SELECT * FROM sales.orders LIMIT 5;.
STEP 03 • RECON PLAYBOOK
⚡ 4ms
Terminal • psql CLI
▶
-- 1. List schemas:
retailmart=# \dn

-- 2. Inspect tables in schema:
retailmart=# \dt sales.*

-- 3. Check columns & datatypes:
retailmart=# \d sales.orders

-- 4. Sample safely:
SELECT * FROM sales.orders LIMIT 5;
⚡ 4ms • Rows: 5 ✅ 0 CRASHES • 100% VISIBILITY
STEP 04 • CORE PLAYBOOK The 3-Pass Method to Master Terminal Reconnaissance
⚠️ SURVIVAL RULE: NEVER QUERY AN UNFAMILIAR TABLE WITHOUT LIMIT
PASS 1 — READ + CODE (45m)

Type every psql command manually in your terminal. Never copy-paste — tactile muscle memory is what saves you under pressure.

PASS 2 — RECALL FROM MEMORY (20m)

Close all notes. Write from memory: (a) list schemas (\dn), (b) list tables (\dt), (c) describe (\d), (d) LIMIT 5 query.

PASS 3 — TEACH IT (15m)

Explain to a peer: "Why does SELECT * FROM orders fail without sales.orders? Why does LIMIT save the server buffer?"

🏛️
The Architectural Paradigm • Three Roles of SQL THE ARCHITECT (DDL) • THE BUILDER (DML) • THE RESIDENT (DQL)
MENTAL MODEL • DATABASE ROLES 🔧 BLUEPRINTS → 🪑 FURNITURE → 👁 RESIDENCE
STEP 01 • THE 3 ROLES
building-metaphor Universal Concept
1. Architect (DDL): Blueprints and concrete walls — CREATE, ALTER, DROP. Never buys groceries.
2. Builder & Mover (DML): Brings in furniture — INSERT, UPDATE, DELETE. Cannot break walls.
3. Resident (DQL): Lives inside and looks around — SELECT. Changes nothing.
Every database operation belongs strictly to one of these three roles. Mixing them up causes architectural chaos.
STEP 02 • DIVISION OF POWER
🏗️ The Architect (DDL)
CONTAINER
Operates purely on schema objects, table definitions, column types, and constraints. Zero row-level awareness.
📦 The Builder (DML)
ROW-LEVEL
Operates on data stored inside the tables. Adds, modifies, or deletes rows. Cannot alter column structures.
STEP 03 • THE ENGINE WORKFLOW
⚡ Lifecycle
pgAdmin 4 • Query Tool
-- 1. ARCHITECT (DDL): Build empty room
CREATE TABLE home.living_room (
  sofa_id TEXT, 
  color   TEXT
);

-- 2. BUILDER (DML): Put furniture inside
INSERT INTO home.living_room 
VALUES ('1', 'Navy Blue');

-- 3. RESIDENT (DQL): Look around the room
SELECT * FROM home.living_room;
Structure → Rows → Query ✅ ROLES CLEAR
STEP 04 • THE MINDSET SHIFT
The Turning Point: Up to this moment, you have been a Resident querying data. From this scene forward, you become the Architect (DDL) and the Builder (DML) — building database structures from scratch.

DDL vs DML vs DQL: The 3 Languages of SQL ⚖️

Clear division of responsibilities: who queries the data, who builds the structure, and who modifies the records.

DQL
The Resident 👁️
▶
Data Query Language • Read-Only

Primary Verb: SELECT
What It Touches: Reads data rows into memory. Alters zero bits on disk storage.
Who Uses It: Analysts, Product Managers, BI Developers, Data Scientists.

-- Inspect customer directory:
SELECT customer_id, first_name, email 
FROM customers.customers 
LIMIT 10;
Safe Exploration: DQL never modifies schemas or records. You can never break production with SELECT.
DDL
The Architect 🏛️
Data Definition Language • Blueprints

Primary Verbs: CREATE, ALTER, DROP, TRUNCATE
What It Touches: Schema metadata, table definitions, columns, data types, and primary keys.
Who Uses It: Data Engineers, DBAs, System Architects.

-- Define table blueprint:
CREATE TABLE college.students (
  student_id TEXT,
  first_name TEXT,
  email      TEXT
);
Container Focus: DDL creates and destroys the container itself. It does not manipulate individual rows of data.
DML
The Builder 📦
Data Manipulation Language • Contents

Primary Verbs: INSERT, UPDATE, DELETE
What It Touches: Rows inside existing tables. Populates, modifies values, and purges rows.
Who Uses It: Backend Developers, Application APIs, ETL Pipelines.

-- Populate row inside table:
INSERT INTO college.students 
VALUES ('1', 'Aarav', 'aarav@edu');

-- Mutate row with condition:
UPDATE college.students 
SET email = 'aarav.s@edu' 
WHERE student_id = '1';
Row Modification: DML works purely with data values inside the walls established by the Architect.
⚠️
Interview Trap Why TRUNCATE is DDL, NOT DML:
Even though TRUNCATE deletes all data rows from a table, it is classified as DDL. DML (DELETE) scans rows one-by-one and fires triggers. TRUNCATE bypasses row scanning entirely — it drops the underlying disk storage segment and re-initializes an empty table structure in 1 millisecond at the engine metadata level.

Today's Big Strategy: Every Column Is TEXT 🧠

Why we intentionally typed every column as TEXT in today's session: structure before constraints.

PEDAGOGICAL PHILOSOPHY
Structure Before Constraints

In this session, every table we create will declare its columns as TEXT. Every ID ('1'), price ('999'), date ('2026-09-29'), and boolean ('true') is treated as a string literal.

CREATE TABLE college.students (
  student_id    TEXT,  -- Treated as '1', '2', etc.
  first_name    TEXT,
  email         TEXT,
  date_of_birth TEXT,  -- Stored as '2004-03-15'
  is_active     TEXT   -- Stored as 'true' / 'false'
);
The Golden Rule for Today: Put single quotes around every value you insert today: VALUES ('1', 'Aarav', 'true');
WHY IT IS DESIGNED THIS WAY
3 Strategic Learning Outcomes
1. Zero Type Friction

Getting halted by ERROR: invalid input syntax for integer: "abc" while learning basic table syntax completely kills momentum.

2. Pure Structural Mastery

Your entire brainpower stays focused on table naming, column order, schema qualification (college.students), and multi-row operations.

3. The Intentional Discomfort

You will soon feel the pain when sorting numbers stored as text ('10' comes before '2'!), creating the ultimate "aha!" moment for strict data types in the next session.

What Unlocks Next: Real production types (INT, NUMERIC, TIMESTAMPTZ) and constraints will introduce mathematical indexing and ironclad validation.

Creating Databases & Schemas: Land & Folders 🌐

The two top layers of the relational hierarchy: purchasing the plot of land, then building organized domain folders.

CONTAINER 01 • CLUSTER LEVEL
CREATE DATABASE (The Land 🏞️)

A database is the top-level container on the server cluster. Everything lives inside it: schemas, tables, views, and data. Before building rooms, you purchase the plot of land:

-- Create a brand new database plot:
CREATE DATABASE college_db;

-- Verify on cluster & connect:
retailmart=# \l
retailmart=# \c college_db
⚠️ Transaction Rule: CREATE DATABASE cannot run inside a transaction block (BEGIN ... COMMIT). It must execute as an autonomous standalone cluster command.
CONTAINER 02 • NAMESPACE LEVEL
CREATE SCHEMA (The Folders 📂)

A schema is a namespace — a logical directory grouping related tables. Without schemas, all 55 RetailMart tables would sit in one chaotic unindexed pile in public:

-- Create domain folder for academic data:
CREATE SCHEMA IF NOT EXISTS college;

-- Create domain folder for supply chain:
CREATE SCHEMA IF NOT EXISTS supply;

-- Verify schemas inside database:
college_db=# \dn
Why Schemas Matter: 1. Domain Boundaries (keep sales away from payroll) • 2. Role Security (grant permissions per schema) • 3. Multi-tenancy (isolate clients).
Hierarchy The Mental Model to Remember:
PostgreSQL Cluster → Database (college_db) → Schema (college) → Table (students) → Row Record

CREATE TABLE — The Main Event 🏗️

Defining durable structural schemas: columns, datatypes, and namespaces across domains.

pgAdmin 4 • Query Tool DDL TABLE DEFINITIONS
STUDENTSPrestige College
CREATE TABLE college.students (
  student_id    TEXT,
  first_name    TEXT,
  last_name     TEXT,
  email         TEXT,
  date_of_birth TEXT,
  is_active     TEXT
);
6 columns defining an academic student identity.
COURSESCurriculum
CREATE TABLE college.courses (
  course_id   TEXT,
  course_name TEXT,
  credits     TEXT,
  department  TEXT
);
Tracks course catalogue and academic department assignments.
PRODUCTSRetailMart
CREATE TABLE shop.products (
  product_id     TEXT,
  product_name   TEXT,
  category       TEXT,
  unit_price     TEXT,
  stock_quantity TEXT
);
E-commerce SKU inventory and catalog structure.
ORDERSCommerce Core
CREATE TABLE shop.orders (
  order_id     TEXT,
  customer_id  TEXT,
  order_date   TEXT,
  order_status TEXT,
  total_amount TEXT
);
Order transactions ledger with customer linking keys.
DDL Syntax Pattern CREATE TABLE schema.table (col_name DATA_TYPE, ...);
💡 Note: Playground supports in-memory DDL for practice, but resets on reload. For permanent disk storage, run DDL in pgAdmin 4 or psql.

Production Table Standards — Naming & Idempotence 🛡️

The unwritten engineering rules: collision-free naming conventions and automated migrations that never crash pipelines.

ENGINEERING STANDARDS • 5 RULES
Professional Naming Conventions 🏷️

In multi-table enterprise databases, consistency avoids ambiguity, syntax collisions, and painful quote-escaping:

Rule Standard (Do This) Anti-Pattern (Avoid) Why It Matters
Casing snake_case CamelCase, UPPER Postgres folds unquoted to lower
Table Names students, orders (Plural) student, order (Singular) Tables represent row collections
Column Names email, city (Singular) emails, cities (Plural) Each cell holds a single attribute
Primary Keys student_id, order_id id Unambiguous in complex multi-JOINs
Keywords order_date, booked_at order, date, user Reserved words cause parser syntax errors
Pro Rule: Never use spaces, hyphens, or uppercase letters in identifier names. If you create a table called "StudentRecords", you are condemned to type ugly double quotes in every query forever!
CI/CD • AUTOMATION STANDARD
The Idempotence Shield 🛡️

In production deployments, migration scripts run automatically. Re-running a setup script must never crash your pipeline:

-- ❌ Without Guard (Fragile Pipeline):
CREATE TABLE college.students ( student_id TEXT );
-- Run 1: SUCCESS
-- Run 2: ERROR: relation "college.students" already exists! (Pipeline Crashes)

-- ✅ With Guard (Production Idempotent Standard):
CREATE TABLE IF NOT EXISTS college.students (
  student_id TEXT, first_name TEXT
);
-- Run 1: SUCCESS
-- Run 2: NOTICE: relation "college.students" already exists, skipping.
The Idempotence Principle: An operation is idempotent if running it once produces the exact same state as running it 1,000 times. Always use IF NOT EXISTS in DDL scripts.
Production Checklist Defensive DDL Best Practices:
1. CREATE SCHEMA IF NOT EXISTS • 2. CREATE TABLE IF NOT EXISTS • 3. DROP TABLE IF EXISTS • 4. snake_case everywhere

ALTER TABLE — Modifying Structure 🔧

Modifying living table schemas: adding attributes, pruning obsolete columns, and refactoring names.

pgAdmin 4 • Query Tool DDL SCHEMA MUTATIONS
ADD COLUMNExpanding Table
ALTER TABLE college.students 
ADD COLUMN phone_number TEXT;
Appends a new column to the table. Existing rows automatically initialize with NULL.
DROP COLUMNRemoving Column
ALTER TABLE college.students 
DROP COLUMN IF EXISTS phone_number;
Permanently shreds the column and deletes stored data across all existing records.
RENAME COLRefactoring Attribute
ALTER TABLE college.students 
RENAME COLUMN date_of_birth TO dob;
Renames an existing column without re-writing table data or altering row contents.
RENAME TBLNamespace Migration
ALTER TABLE college.students 
RENAME TO college_students;
Renames the relation. All indexes, sequence ties, and constraints remain attached.
Production Safety ALTER TABLE Migration Best Practice:
Always use DROP COLUMN IF EXISTS in migration scripts to maintain idempotency.

DROP — The Demolition Crew 💥

The irreversible destroyer: understanding blast radii, the CASCADE nuclear option, and zero-recovery operations.

BLAST RADIUS How DROP Cascades Down:
1. DATABASE → wipes schemas → 2. SCHEMA CASCADE → wipes tables → 3. TABLE → wipes all rows!
TIER 1 • TABLE 🎯
DROP TABLE

Destroys 1 table relation. Other tables in the schema are completely unaffected.

-- Safe drop:
DROP TABLE IF EXISTS 
  shop.products;
Blast Radius: Table structure + all internal rows destroyed.
TIER 2 • DOMAIN ☣️
DROP SCHEMA CASCADE

The Nuclear Option. Wipes the folder AND all tables inside it simultaneously!

-- Safety lock blocks drop:
DROP SCHEMA shop; -- ❌ ERROR!

-- Nuclear bypass:
DROP SCHEMA IF EXISTS 
  shop CASCADE;
Blast Radius: Entire domain + every single table inside wiped!
TIER 3 • CLUSTER ☠️
DROP DATABASE

Purges the entire database container from server cluster disk. Gone forever.

-- Cannot drop connected db:
\c postgres
DROP DATABASE IF EXISTS 
  old_test_db;
Blast Radius: All schemas, all tables, entire database purged.
No Recycle Bin The Golden Rule of Destruction:
In SQL, there is no Undo, no Trash Can, and no Ctrl+Z. Always use IF EXISTS and verify your connection string before running DROP.

DDL vs DML — The Great Showdown ⚔️

The 3-way confusion that trips up database engineers and fails technical interviews: DROP vs TRUNCATE vs DELETE.

DDL • DEMOLITION 💥
DROP TABLE

Vaporizes the structure AND all data. Unlinks the table relation completely from the database catalog.

DROP TABLE shop.orders;
  • Structure: Destroyed completely
  • Data Rows: Destroyed
  • WHERE filter: ❌ Not allowed
  • Aftermath: relation does not exist
Whiteboard Analogy: Smashes the entire whiteboard into pieces and throws it in the trash.
DDL • STORAGE RESET 🧹
TRUNCATE TABLE

Wipes all rows simultaneously by deallocating storage extents on disk. The table structure remains pristine.

TRUNCATE shop.orders;
  • Structure: Preserved intact
  • Data Rows: All wiped (0 rows)
  • WHERE filter: ❌ Not allowed
  • Aftermath: Empty table ready for inserts
Whiteboard Analogy: Takes a spray bottle and duster to wipe the entire whiteboard completely clean.
DML • ROW MANIPULATION ✂️
DELETE FROM

Surgically removes specific rows evaluated by a condition. Generates transaction log records for each removed row.

DELETE FROM shop.orders WHERE order_status = 'Cancelled';
  • Structure: Preserved intact
  • Data Rows: Only matching rows deleted
  • WHERE filter: ✅ Mandatory in production!
  • Aftermath: Remaining rows untouched
Whiteboard Analogy: Uses a felt eraser tip to cleanly erase one specific sentence, leaving the rest.
Interview Truth Why is TRUNCATE classified as DDL instead of DML?
Because it does not inspect rows — it operates on the table storage structure itself by unlinking storage pages directly!
65%
Practice Milestone 02

Query Mode: Unlocked — DDL: Architecture & Schemas

Act as the Database Architect! Build the Prestige College database schema from scratch, design student tables, mutate columns with ALTER, and master DROP vs TRUNCATE.

🧠Practice Time
🏫
Prestige College • From Skeleton to Living System THE TRANSITION FROM ARCHITECTURE (DDL) TO DATA (DML)
DATA PARADIGM • BREATHING LIFE 🏫 4 TABLES READY → 🪑 0 STUDENTS → ⚡ DML ENROLLMENT
STEP 01 • THE GRAND ARCHITECTURE
dean-office Launch Day
Flawless DDL Executed: You defined college.students, college.courses, shop.products, and shop.orders.
The schemas are partitioned. Column definitions are crisp. The structural blueprints sit ready on disk.
Architectural Status: 4 tables created • 0 syntax errors • Disk allocated.
STEP 02 • THE HARSH REALITY
🏛️ DDL Alone
0 ROWS
Run SELECT count(*) → 0. Not a single human being is enrolled. No lectures scheduled. ₹0 tuition collected.
⚡ DML Awakening
LIVING SYSTEM
Every app signup, library book checkout, and fee payment is an INSERT breathing vitality into the schema.
STEP 03 • THE ENGINE WORKFLOW
⚡ Admissions Open
pgAdmin 4 • Query Tool
-- 1. DDL: Pristine empty classroom
SELECT count(*) FROM college.students;
-- Result: 0 (the table is empty)

-- 2. DML: Admissions open (Life enters)
INSERT INTO college.students
  (student_id, first_name, last_name, email, date_of_birth, is_active)
VALUES
  ('1', 'Aarav', 'Sharma', '[email protected]', '2004-03-15', 'true');
Output: INSERT 0 1 ✅ SYSTEM ALIVE
STEP 04 • THE GOLDEN PERSPECTIVE
The Core Reality: A database schema without data is like a grand hospital without doctors or patients. DDL gives you the durable structural container; DML is what breathes life, value, and transactions into software.

INSERT INTO — Adding Data 📥

The fundamental DML command: single rows, high-performance batching, and PostgreSQL's RETURNING superpower.

pgAdmin 4 • Query Tool DML INSERTION PATTERNS
SINGLE ROWExplicit Columns
INSERT INTO college.students 
  (student_id, first_name, last_name, 
   email, date_of_birth, is_active)
VALUES 
  ('1', 'Aarav', 'Sharma', 
   '[email protected]', '2004-03-15', 'true');
Always specify column names explicitly. Never rely on table column positions in production code.
MULTI-ROW BATCHHigh Performance
INSERT INTO college.students 
  (student_id, first_name, last_name, 
   email, date_of_birth, is_active)
VALUES
  ('2', 'Diya', 'Patel', 
   '[email protected]', '2003-11-02', 'true'),
  ('3', 'Kabir', 'Singh', 
   '[email protected]', '2004-07-20', 'true');
Separate value tuples with commas. Batch inserts are 10x-50x faster than individual single queries.
RETURNING *Secret Superpower
INSERT INTO college.students 
  (student_id, first_name, last_name, 
   email, date_of_birth, is_active)
VALUES 
  ('4', 'Neha', 'Verma', 
   '[email protected]', '2004-01-10', 'true')
RETURNING *;
PostgreSQL exclusive: Instantly returns newly generated rows without requiring a second roundtrip SELECT query.
SELECT VERIFYTable Inspection
SELECT student_id, first_name, email, is_active 
FROM college.students
LIMIT 10;
Verifies the committed disk records inside the physical table with a safety LIMIT.
Senior Pro Rule Always Declare Column Targets:
INSERT INTO table (col1, col2) VALUES (val1, val2); — Prevents silent column-shift bugs!

UPDATE — Modifying Data & The WHERE Safety Net 🔄

Modifying stored records, updating multiple attributes, and avoiding the catastrophic missing-WHERE disaster.

DML PATTERNS
Professional UPDATE Syntax ✏️

SET specifies new values; WHERE selects matching rows. Multiple columns update in a single transaction:

-- 1. Targeted single-column update:
UPDATE college.students
SET email = '[email protected]'
WHERE student_id = '1';

-- 2. Modify multiple columns simultaneously:
UPDATE college.students
SET is_active = 'false', 
    last_name = 'Sharma-Verma'
WHERE student_id = '3';

-- 3. RETURNING confirms change instantly:
UPDATE college.students
SET is_active = 'true'
WHERE student_id = '3'
RETURNING student_id, first_name, is_active;
Pro Rule: Always target unique primary keys (e.g. student_id = '1') to guarantee pinpoint row targeting.
DISASTER PREVENTION
The Missing WHERE Trap ⚠️

Without WHERE, PostgreSQL applies the new value to every single row in the table:

❌ DISASTER: Missing WHERE
UPDATE college.students
SET email = '[email protected]';
-- UPDATE 4 (every student now has Aarav's email!)
✅ PROTECTED: Specific Key + RETURNING
UPDATE college.students
SET email = '[email protected]'
WHERE student_id = '1'
RETURNING student_id, email;
-- UPDATE 1 (Only Aarav modified; confirmed instantly)
Impact: In production, an unconstrained UPDATE corrupts financial balances or customer emails across the entire company.
The 2-Step Golden Rule Always Preview Before You Update:
Run SELECT * FROM table WHERE cond; first → Then swap to UPDATE!

DELETE vs TRUNCATE — Surgical Pruning vs Bulk Reset ✂️⚡

Two distinct methods to remove rows: surgical row-by-row deletion with WHERE vs instant filesystem extent deallocation.

DML • SURGICAL PRUNING ✂️
DELETE FROM (Targeted Rows)

Removes individual rows evaluated by a WHERE condition. Always follow the mandatory 2-step protocol:

-- Step 1: Preview rows first with SELECT
SELECT student_id, first_name 
FROM college.students 
WHERE is_active = 'false';

-- Step 2: Swap to DELETE with RETURNING
DELETE FROM college.students 
WHERE is_active = 'false'
RETURNING student_id, first_name;
Senior Habit: Never type DELETE directly. Write SELECT, verify the row count, then swap keywords to execute.
DDL • BULK STORAGE RESET ⚡
TRUNCATE TABLE (Instant Empty)

Deallocates filesystem storage extents directly, almost instantly however many rows. Table structure stays 100% intact:

-- Fast bulk empty (0 rows in 5ms):
SELECT count(*) FROM college.students; -- 5,00,000
TRUNCATE TABLE college.students;
SELECT count(*) FROM college.students; -- 0
• DELETE FROM table; scans all 1 crore rows • takes minutes
• TRUNCATE TABLE; unlinks storage pages • 5 milliseconds
Syntax Rule: TRUNCATE does not allow a WHERE clause. It is always an all-or-nothing storage reset.
Interview Truth Can TRUNCATE be rolled back in PostgreSQL?
YES! In Postgres, TRUNCATE is transaction-safe inside BEGIN ... ROLLBACK;!

Feeling the Pain of All-TEXT 🧠

PAIN POINT 01 • ARITHMETIC 🧮
Clumsy Casting (No Direct Math)

In an all-TEXT table, you cannot do simple multiplication. SQL refuses to multiply a string:

-- ❌ FAILS with operator does not exist: text * numeric
UPDATE fees SET amount = amount * 1.1;

-- ⚠️ Clumsy double-cast workaround:
UPDATE fees 
SET amount = (amount::NUMERIC * 1.1)::TEXT;
Why it hurts: High compute overhead, ugly query syntax, and zero native math safety.
PAIN POINT 02 • COMPARISON ⚠️
Lexicographical Sort ('1000' < '900')

String comparison checks ASCII character codes left-to-right. '1' comes before '9':

-- 🚨 Silent bug: returns only '950', drops '1000'!
SELECT * FROM fees WHERE amount > '900';

-- In text comparison: '1000' < '900' evaluates TRUE!
-- Text sorts like a dictionary: "apple" < "banana"
Senior Trap: Silent logical bugs in reports where high-value customers get excluded!
The Clean Fix Session 4 Teaser: Strict Data Types
Next session we migrate: ALTER COLUMN amount TYPE NUMERIC; • Math & sorting instantly work!
65%
Practice Milestone 03

Query Mode: Unlocked — DML: Data Manipulation

Breathe life into empty schemas! Practice single & multi-row INSERTs, safe targeted UPDATEs, constrained DELETEs, and RETURNING outputs.

🧠Practice Time
TOP INTERVIEW QUESTIONS
TAXONOMY & ARCHITECTURE

Q1: What are the 5 categories of SQL commands? Give examples.

WHAT TO SAY (THE MODEL ANSWER):

"SQL commands fall into 5 distinct architectural categories: DDL (Data Definition Language) defines structure (CREATE, ALTER, DROP, TRUNCATE); DML (Data Manipulation Language) modifies row data (INSERT, UPDATE, DELETE); DQL (Data Query Language) reads data without altering anything (SELECT); DCL (Data Control Language) manages permissions and security (GRANT, REVOKE); and TCL (Transaction Control Language) manages atomic transactions (COMMIT, ROLLBACK)."

Why Interviewers Ask This

To check whether you view SQL as random scripts or understand database architecture and role separation.

Follow-up Trap

"Is TRUNCATE DDL or DML?" Remember: TRUNCATE is DDL because it acts on the relation structure, not row-by-row.

SQL Intro & DDL/DML Self-Check

Close your notes. Answer from memory. Click any card to reveal the verified answer.

1. Which psql command lists all schemas?
2. Write query returning first 5 rows of sales.orders
3. Why does SELECT * FROM orders; fail?
4. How to see columns & types of customers.customers?
5. Why is LIMIT important when exploring an unknown table?
6. What does DDL stand for? Give 3 examples.
7. Why use CREATE TABLE IF NOT EXISTS?
8. Difference between DROP TABLE and DELETE FROM?
9. What happens if UPDATE lacks a WHERE clause?
10. What does the RETURNING clause do?
11. Can TRUNCATE be rolled back in PostgreSQL?
12. Why does '1000' < '900' happen in TEXT columns?

The 6 Golden Rules Bento

The essential principles that govern query execution, structure creation, and data manipulation.

RULE 02 · DDL

The Safety Net: IF NOT EXISTS

Never write bare CREATE TABLE in migration scripts. Always add IF NOT EXISTS to ensure your operations are idempotent and CI/CD safe.

RULE 03 · CONVENTIONS

Professional Naming Standards

Always lowercase snake_case. Tables are plural (students), columns are singular (email), and ID keys follow table_id.

RULE 04 · DML CAUTION

The Mandatory WHERE Clause

UPDATE and DELETE without WHERE wipe the entire table. Always run SELECT first to preview the exact rows before executing mutations.

RULE 05 · THREE-WAY PARADIGM

DROP vs TRUNCATE vs DELETE

DROP: Demolish the room. TRUNCATE: Empty the room instantly (DDL). DELETE: Remove specific furniture (DML).

RULE 06 · MOTIVATION

Why All-TEXT Today?

We used TEXT to master structure without casting friction. Up next, we fix the '1000' < '900' trap by giving columns proper types and constraints!

Terminal Quick Reference Studio

Every core command ready to copy directly into your PostgreSQL shell.

SQL Quick Reference • Cheat Sheet
SESSION 03 • 4 TOOLKITS
PSQL META • RECON Terminal Shell
\l                 -- list databases
\c retailmart        -- connect to database
\dn                -- list all schemas
\dt sales.*        -- list tables in schema
\d  sales.orders   -- describe structure
Client meta-commands. No semicolon required.
DQL • EVALUATION ENGINE Expressions & Tables
SELECT 42;
SELECT 25 * 4 AS total;
SELECT current_timestamp, version();
SELECT * FROM sales.orders LIMIT 10;
Non-locking reads with safe LIMIT sampling.
DDL • ARCHITECTURE Structures
CREATE SCHEMA IF NOT EXISTS college;
CREATE TABLE IF NOT EXISTS college.students (
  student_id TEXT, first_name TEXT
);
ALTER TABLE college.students ADD COLUMN email TEXT;
TRUNCATE TABLE college.students;
DDL defines relations, shapes, and storage.
DML • DATA MUTATION Row Records
INSERT INTO college.students (student_id, first_name)
VALUES ('1', 'Arjun') RETURNING *;

UPDATE college.students 
SET email = '[email protected]' WHERE student_id = '1';

DELETE FROM college.students WHERE student_id = '1';
Always write WHERE or preview with SELECT first.

Take-Home Challenge: Database Builder Sprint

Complete these 6 hands-on exercises in your local database before moving forward to Data Types.

🎯 THE 6-STEP BUILDER MISSION:
Step 1 — Create Schema

Create a schema named gym with IF NOT EXISTS.

Step 2 — Create Members Table

Create gym.members with member_id, full_name, plan_type, join_date, is_active (all TEXT).

Step 3 — Batch Insert

Insert 3 members in a single multi-row statement using RETURNING *.

Step 4 — Update Plan

Upgrade member '1' to 'Annual Premium' using UPDATE ... WHERE.

Step 5 — Safe Delete

Run SELECT first, then DELETE member '3' who cancelled.

Step 6 — Catalog Verification

Run \dt gym.* and query the final member roster with SELECT * FROM gym.members;.

Master Curriculum Journey Roadmap

TheShiraverse Curriculum Flow
🟢 ACTIVE WAYPOINT: MODULE 1 • TOPIC 03 (Writing Your First Queries)
Track: 60 Topics • 6 Modules • Free & Live
01
TOPIC 01 Session 1 • Done
What is SQL & DBs?
Relational Model Port 5432 & Server 5 SQL Sublanguages Declarative Syntax
✓ COMPLETED VERIFIED
02
TOPIC 02 Session 2 • Done
How SQL is Organised
Database Hierarchy Schemas as Folders Tables as Files Catalog Introspection
✓ COMPLETED VERIFIED
03
TOPIC 03 Today • Live
Writing First Queries
SELECT Evaluation CREATE • ALTER • DROP INSERT • UPDATE • DELETE The Safe WHERE Rule
📍 YOU ARE HERE ACTIVE
04
TOPIC 04 Up Next
Data Types & Migrations
Ending All-TEXT NUMERIC vs FLOAT TIMESTAMPTZ & Dates ALTER TABLE ... USING
⚡ UP NEXT Data Types
05
TOPIC 05 Session 5
Constraints & Keys
NOT NULL • DEFAULT CHECK • UNIQUE PRIMARY KEY FOREIGN KEY
🔒 NOT STARTED Later
✦ THE FOCUSED ASCENT: ZERO CONCEPTS ➔ SCHEMAS & ARCHITECTURE ➔ FIRST QUERIES & MUTATIONS ➔ STRICT DATA TYPES ➔ CONSTRAINTS & KEYS ✦

Next Session: From Naked Tables to DATA TYPES & CASTING

NEXT MISSION • DATA TYPES & PERFORMANCE
Data Types: Beyond Plain Text
Taking off the training wheels — Ending the all-TEXT era, mastering numeric precision, date-time timezones, and seamless column migrations with USING.
• NEXT SESSION • THE SHIRAVERSE
🛡️
1. Ending All-TEXT
Replacing naive text columns with true storage types: NUMERIC(12,2), TIMESTAMPTZ, INTEGER, and BOOLEAN. Real math without awkward casting, and proper numerical sorting!
NUMERIC • INT • DATE • BOOL
⚖️
2. Precision & Float Traps
Why FLOAT and REAL introduce catastrophic binary rounding errors in currency, and why financial ledgers demand exact NUMERIC arithmetic.
NUMERIC(p,s) vs FLOAT • ROUNDING
⚙️
3. The USING Migration
Live schema alteration: transform existing production data safely across types using explicit conversion pipelines:
ALTER TABLE gym.members ALTER COLUMN join_date TYPE DATE USING join_date::DATE;
⚠️ TAKE-HOME PREREQUISITE: Complete today's 6-step Gym Database sprint locally. Next up: we migrate those very tables from all-TEXT to strict storage types!
← How SQL is Organised Next: Data Types →
→ next   ← back   F fullscreen   H hide bars   N notes
1 / 38