Rana Maninder Singh
Lesson 2 of 11SQL & DBMS (MySQL)

SQL Commands & Basics

Lesson opener

In one line: Read data with SELECT, filter with WHERE, sort, limit results, handle NULLs, and write safe DML on a practice database - the vocabulary every analyst uses before aggregates and joins.

Why it matters: Without a fixed clause order, you mix up filtering and sorting - and wonder why your query errors or returns the wrong rows.

Before this lesson: Intro to DBMS

Before you start

ResourceLink
PreviousIntro to DBMS
NextAggregate functions
Lab tablescustomers, sales in learnings_lab


What you will learn

Read data with SELECT, filter with WHERE, sort, limit results, handle NULLs, and write safe DML on a practice database — the vocabulary every analyst uses before aggregates and joins.

Excel vs Python vs SQL — same task, three tools
Excel vs Python vs SQL — same task, three tools

SELECT template (read query)

[SELECT read-query skeleton]

WHY: Without a fixed clause order, you mix up filtering and sorting — and wonder why your query errors or returns the wrong rows.

WHEN: You're starting any new pull from a table and want a checklist before you add business logic.

SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1 DESC, column2 ASC
LIMIT 100;

Breaking it down:

Use this when: You're drafting a customer export and need columns, filters, sort, and a safety cap in one shot.

Order of execution (logical): FROM → WHERE → SELECT → ORDER BY → LIMIT.


How every SQL problem works — Source → Pattern → Result

Python scripts walk Input → Logic → Output (py1). SQL is shaped differently: you are not writing a top-to-bottom recipe so much as describing a result set. So we translate the same habit into SQL-native wording — same thinking, different labels:

Python habitSQL translationWhat you name before you write SQL
InputSourceWhich table(s) and columns do you have?
LogicPatternWhich clause pattern applies — WHERE / JOIN / GROUP BY / subquery / window?
OutputResultWhat shape should the answer take — one row per X, aggregated, ranked, flagged?

Plain English: Before you type SELECT, say the three beats out loud. "I have customers. I need a WHERE + ORDER BY + LIMIT pattern. I want ten ranked rows for outreach." If you cannot name the Result shape, you do not yet know what the query is for.

In practice files, leave the three beats as SQL comments above each query:

-- Source: customers (customer_id, segment, total_revenue, churned)
-- Pattern: WHERE + ORDER BY + LIMIT
-- Result: top 10 active high-revenue rows (one row per customer)

This is a translation, not a copy-paste of Python's labels. Keep using Source / Pattern / Result in SQL lessons so the habit fits how queries actually work.


Examples on customers

[Top active high-revenue customers]

WHY: Pulling the whole customers table buries the few rows your manager actually asked for — Gold segments with real spend.

WHEN: Marketing wants the top 10 non-churned customers by revenue for a retention campaign.

USE learnings_lab;

SELECT customer_id, segment, total_revenue
FROM customers
WHERE churned = 0
  AND total_revenue > 1000
ORDER BY total_revenue DESC
LIMIT 10;

Breaking it down:

Use this when: You need a ranked shortlist for outreach, not a full table dump.


Comparison operators

OperatorMeaning
=Equal
<> or !=Not equal
<, >, <=, >=Range comparisons

[Revenue band filter]

WHY: Eyeballing thousands of rows to find mid-tier spenders doesn't scale — you need the database to do the comparison.

WHEN: Finance asks for customers with revenue between $500 and $2,000 for a mid-market pilot.

SELECT * FROM customers
WHERE total_revenue >= 500 AND total_revenue < 2000;

Breaking it down:

Use this when: You're slicing a numeric column into a range without exporting to Excel first.


AND, OR, NOT, parentheses

[Combine filters with logic]

WHY: A flat list of conditions without AND/OR/NOT gives you everyone or no one — not the segment mix you intended.

WHEN: You want active Gold or Platinum customers, or everyone who isn't flagged as churned.

SELECT customer_id, segment
FROM customers
WHERE (segment = 'Gold' OR segment = 'Platinum')
  AND churned = 0;

SELECT customer_id
FROM customers
WHERE NOT churned = 1;

Breaking it down:

Use this when: Your filter mixes "any of these segments" with "must also be active."

Use parentheses when mixing AND/OR so intent is obvious.


IN and NOT IN (list of values)

[Match a short list of values]

WHY: Writing segment = 'Gold' OR segment = 'Silver' OR ... gets ugly fast and easy to typo.

WHEN: Ops wants every customer in Gold or Silver, or every sale that didn't come through mobile or email.

SELECT customer_id, segment
FROM customers
WHERE segment IN ('Gold', 'Silver');

SELECT customer_id
FROM sales
WHERE channel NOT IN ('mobile', 'email');

Breaking it down:

Use this when: You're filtering on a handful of known categories from a dropdown or stakeholder list.

Cleaner than long OR chains.


BETWEEN (inclusive range)

[Inclusive numeric range]

WHY: Two separate >= and <= conditions work, but BETWEEN reads like how people actually say "between 500 and 1500."

WHEN: You're pulling customers in a revenue window for a pricing experiment.

SELECT customer_id, total_revenue
FROM customers
WHERE total_revenue BETWEEN 500 AND 1500;

Breaking it down:

Use this when: Someone gives you a min–max range on a single numeric column.

Same as >= 500 AND <= 1500.


LIKE and NOT LIKE (text patterns)

[Text pattern matching]

WHY: Exact = match fails when you only know part of a string — like "starts with C00" or "ends with old."

WHEN: You're hunting customer IDs with a known prefix, or segment names that share a suffix.

SELECT customer_id FROM customers
WHERE customer_id LIKE 'C00%';      -- starts with C00

SELECT customer_id FROM customers
WHERE segment LIKE '%old';          -- ends with old (Gold)

SELECT customer_id FROM customers
WHERE segment LIKE '_old';          -- _ = one character

Breaking it down:

Use this when: You have partial text clues, not a full exact value.

PatternMeaning
%Any length (including zero)
_Exactly one character

NULL — IS NULL / IS NOT NULL

[Find missing values]

WHY: = NULL never matches anything — NULL means "unknown," not zero or blank string, so you need special operators.

WHEN: Data quality check: which customers have no segment assigned, or who definitely has revenue on file.

SELECT customer_id, segment
FROM customers
WHERE segment IS NULL;

SELECT customer_id
FROM customers
WHERE total_revenue IS NOT NULL;

Breaking it down:

Use this when: You're cleaning master data or excluding incomplete records from a report.

Never use = NULL — it does not work.


COALESCE / IFNULL (replace NULL for display)

[Default for missing segment]

WHY: NULLs in a report look broken to stakeholders — "Unknown" reads better than a blank cell.

WHEN: You're building a segment breakdown and don't want NULL rows to disappear from charts.

SELECT customer_id,
       COALESCE(segment, 'Unknown') AS segment_clean
FROM customers;

Breaking it down:

Use this when: You're feeding a dashboard or CSV where every row needs a label in the segment column.

MySQL: IFNULL(segment, 'Unknown') does the same for two arguments.


DISTINCT and column aliases

[Unique values and readable names]

WHY: Raw column names and duplicate segment rows clutter output when you just want "what segments exist?" or cleaner headers.

WHEN: You're listing distinct segments for a filter dropdown, or renaming columns for a slide deck.

SELECT DISTINCT segment FROM customers;

SELECT segment AS seg,
       total_revenue AS rev
FROM customers
WHERE total_revenue > 1000;

Breaking it down:

Use this when: You need a unique picklist or shorter column headers for export.

Alias names can be used in ORDER BY in MySQL; not in WHERE (use real column name there).


Expressions in SELECT

[Calculated columns in the result]

WHY: The table stores base numbers — tax-adjusted revenue or annualized spend often lives only in your head until you compute it.

WHEN: You need to show estimated tax-inclusive revenue or annualized monthly spend alongside raw columns.

SELECT customer_id,
       total_revenue,
       total_revenue * 1.1 AS revenue_with_tax,
       monthly_spend * 12 AS annualized_spend
FROM customers;

Breaking it down:

Use this when: Stakeholders ask for derived metrics without changing the underlying table.


ORDER BY multiple columns

[Sort by segment, then revenue]

WHY: Sorting on one column alone mixes segments together — you lose the "best in each group" view.

WHEN: You want customers grouped by segment A→Z, with highest revenue first inside each segment.

SELECT customer_id, segment, total_revenue
FROM customers
ORDER BY segment ASC, total_revenue DESC;

Breaking it down:

Use this when: You're printing a per-segment leaderboard in one query.

Sort by segment A→Z, then highest revenue first within each segment.


LIMIT and OFFSET (pagination)

[Top-N and paged results]

WHY: Returning millions of rows crashes tools and hides the page you actually need.

WHEN: You're building "page 3 of 10" for a customer list, or just want the first 10 rows sorted by id.

SELECT * FROM customers
ORDER BY customer_id
LIMIT 10;              -- first 10 rows

SELECT * FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 20;    -- skip 20, take 10 (page 3 if page size 10)

Breaking it down:

Use this when: Your app or report shows customers in pages instead of one giant scroll.


Table alias (short name)

[Shorthand table name]

WHY: Repeating customers.customer_id everywhere is noisy — aliases shorten queries before you add a second table.

WHEN: You're filtering active customers and plan to join sales next lesson with c and s.

SELECT c.customer_id, c.segment
FROM customers AS c
WHERE c.churned = 0;

Breaking it down:

Use this when: Any query that will grow into a join — start the alias habit early.

Useful before joins: customers c, sales s.


Comments

[Document your SQL inline]

WHY: Six-month-old queries with no notes leave you guessing what a weird filter was for.

WHEN: You're saving a script the team will rerun — note why a filter exists.

-- single-line comment
SELECT customer_id FROM customers; /* block
comment */

Breaking it down:

Use this when: You hand off .sql files and want the next person to trust your intent.


Safe habits

DoWhy
List columns explicitlyAvoid surprises when table changes
Always WHERE on UPDATE/DELETEPrevent wiping whole table
LIMIT when exploringProtect Workbench from huge result sets
Test SELECT before UPDATECopy WHERE clause to verify rows

INSERT / UPDATE / DELETE (practice DB only)

[Practice write operations]

WHY: You need to test how data changes work — but one wrong DELETE without WHERE wipes the table.

WHEN: You're practicing add/update/remove on lab data with a throwaway customer id like C9999.

-- INSERT
INSERT INTO customers (customer_id, segment, churned, total_revenue)
VALUES ('C9999', 'Bronze', 0, 100.00);

-- UPDATE
UPDATE customers
SET segment = 'Silver'
WHERE customer_id = 'C9999';

-- DELETE
DELETE FROM customers
WHERE customer_id = 'C9999';

Breaking it down:

Use this when: You're learning DML [data change commands] on a sandbox database, not production.

Use transactions when experimenting (constraints module):

[Safe practice with rollback]

WHY: A bad UPDATE in the middle of experimenting can stick around — transactions let you try and undo.

WHEN: You're testing INSERT/UPDATE/DELETE and want a safety net before COMMIT.

START TRANSACTION;
-- your DML here
ROLLBACK;   -- undo practice changes
-- COMMIT;  -- only when you mean to keep

Breaking it down:

Use this when: You're running risky practice writes and need a one-click undo.


SQL basics command reference

Tick commands you have run on lab data.

CategoryCommand / clauseUse
SessionUSE db;Pick database
ExploreSHOW TABLES;, DESCRIBE t;Structure
ReadSELECT cols FROM tPull data
FilterWHERERow filter
LogicAND, OR, NOT, ()Combine conditions
Compare=, <>, <, >, BETWEENValues
ListsIN, NOT INMany values
TextLIKE, NOT LIKEPattern match
NULLIS NULL, IS NOT NULLMissing data
DisplayCOALESCE, IFNULLDefault for NULL
UniqueDISTINCTDedupe rows
RenameAS aliasReadable output
SortORDER BY, DESCRank rows
PageLIMIT, OFFSETTop-N / pages
WriteINSERT, UPDATE, DELETEChange data (careful)
NextGROUP BY, JOINsql3, sql4

Essential commands

Command / actionWhat it does
SELECT col1, col2 FROM tChoose columns to return.
WHERE + AND / OR / NOTFilter rows.
IN (...), BETWEEN a AND bList and range filters.
LIKE 'pattern'Text pattern (%, _).
IS NULL / IS NOT NULLFilter missing values.
COALESCE(col, default)Replace NULL in results.
ORDER BY col DESCSort results.
LIMIT n / OFFSET nCap rows / pagination.
DISTINCT, AS aliasUnique values and column names.
INSERT / UPDATE / DELETEModify data — lab only, use transactions.

Practice

Before each query, fill the three SQL blanks — Source → Pattern → Result (worked model for task 1 below; blanks for the rest). Save exercises/answers/sql/02_basics.sql with at least:

  1. SELECT with WHERE, ORDER BY, LIMIT
  2. One query using IN or BETWEEN
  3. One query using LIKE
  4. One query using IS NULL or COALESCE
  5. One DISTINCT and one column AS alias

Example framing for task 1 (copy the comment habit onto every query in your file):

-- Source: customers (customer_id, segment, total_revenue, churned)
-- Pattern: WHERE + ORDER BY + LIMIT
-- Result: top 10 active customers by revenue (one row per customer)

SELECT customer_id, segment, total_revenue
FROM customers
WHERE churned = 0
  AND total_revenue > 1000
ORDER BY total_revenue DESC
LIMIT 10;

Framing prompts for the rest (fill these blanks in your .sql comments before writing each query):

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

Where This Connects

Scale-up: Once one OLTP database isn't enough for analytics at volume, teams land data in a cloud warehouse (e.g. BigQuery, Snowflake, Redshift) and often model transforms with dbt. Awareness only; not taught on this site.

Cross-ecosystem: Same filter / sort / select job on this site (trio diagram at the top): Spreadsheets intro and Pandas basics. Next SQL skills on this track: aggregates → joins; dialect deepening later in PostgreSQL.

Checklist

  • [ ] I know logical order: FROM → WHERE → SELECT → ORDER BY → LIMIT
  • [ ] I used IS NULL (not = NULL)
  • [ ] I used IN or BETWEEN
  • [ ] I used LIKE with %
  • [ ] Saved .sql file with comments