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
| Resource | Link |
|---|---|
| Previous | Intro to DBMS |
| Next | Aggregate functions |
| Lab tables | customers, 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.

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:
SELECT column1, column2→ which columns to show in the resultFROM table_name→ which table to read fromWHERE condition→ keep only rows that pass your filterORDER BY column1 DESC, column2 ASC→ sort: first column high→low, then second low→highLIMIT 100→ stop after 100 rows
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 habit | SQL translation | What you name before you write SQL |
|---|---|---|
| Input | Source | Which table(s) and columns do you have? |
| Logic | Pattern | Which clause pattern applies — WHERE / JOIN / GROUP BY / subquery / window? |
| Output | Result | What 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 learnings_lab→ switch to the lab databaseSELECT customer_id, segment, total_revenue→ three columns in the outputFROM customers→ source tableWHERE churned = 0 AND total_revenue > 1000→ active customers only, revenue above 1000ORDER BY total_revenue DESC→ richest firstLIMIT 10→ top ten only
Use this when: You need a ranked shortlist for outreach, not a full table dump.
Comparison operators
| Operator | Meaning |
|---|---|
= | 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:
SELECT *→ all columns (fine for exploration; list columns explicitly in production)FROM customers→ read from the customers tableWHERE total_revenue >= 500 AND total_revenue < 2000→ inclusive lower bound, exclusive upper — the $500–$1999.99 band
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:
- First query:
(segment = 'Gold' OR segment = 'Platinum')→ either premium tier AND churned = 0→ still active — both conditions must be true- Second query:
NOT churned = 1→ same as "not churned" — flip a true/false flag
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:
segment IN ('Gold', 'Silver')→ segment equals any value in the listchannel NOT IN ('mobile', 'email')→ exclude those channels — keep web, store, etc.
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:
SELECT customer_id, total_revenue→ id plus the number you're filtering onBETWEEN 500 AND 1500→ both endpoints included — same as>= 500 AND <= 1500
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 characterBreaking it down:
LIKE 'C00%'→%= any characters after — IDs starting with C00LIKE '%old'→ anything ending in "old" (catches Gold)LIKE '_old'→_= exactly one character before "old"
Use this when: You have partial text clues, not a full exact value.
| Pattern | Meaning |
|---|---|
% | 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:
segment IS NULL→ rows where segment was never filled intotal_revenue IS NOT NULL→ rows where revenue exists (even if it's 0)
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:
COALESCE(segment, 'Unknown')→ use segment if present, otherwise show 'Unknown'AS segment_clean→ friendlier column name in the result
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:
DISTINCT segment→ one row per unique segment valueAS seg/AS rev→ shorter aliases in the result setWHERE total_revenue > 1000→ filter on the real column. MySQL does not allow therevalias inWHERE(that clause is evaluated beforeSELECT)
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:
total_revenue * 1.1→ multiply each row's revenue by 1.1 for a 10% upliftmonthly_spend * 12→ turn monthly into yearly on the flyAS revenue_with_tax/AS annualized_spend→ name the new columns
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:
ORDER BY segment ASC→ alphabetical segment ordertotal_revenue DESC→ within the same segment, highest revenue on top
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:
LIMIT 10→ return at most 10 rowsOFFSET 20→ skip the first 20 rows, then take the next 10 — classic pagination
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:
customers AS c→cis a nickname for the tablec.customer_id,c.segment→ columns qualified with the alias
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:
-- single-line comment→ everything after--on that line is ignored/ ... /→ block comment spanning multiple lines
Use this when: You hand off .sql files and want the next person to trust your intent.
Safe habits
| Do | Why |
|---|---|
| List columns explicitly | Avoid surprises when table changes |
Always WHERE on UPDATE/DELETE | Prevent wiping whole table |
LIMIT when exploring | Protect Workbench from huge result sets |
| Test SELECT before UPDATE | Copy 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:
INSERT INTO ... VALUES→ add one new row with listed columnsUPDATE ... SET ... WHERE→ change columns only for rows matching the filterDELETE FROM ... WHERE→ remove rows matching the filter — never omit WHERE in real life
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 keepBreaking it down:
START TRANSACTION→ begin a batch you can undoROLLBACK→ throw away all changes since STARTCOMMIT→ make changes permanent — comment it until you're sure
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.
| Category | Command / clause | Use |
|---|---|---|
| Session | USE db; | Pick database |
| Explore | SHOW TABLES;, DESCRIBE t; | Structure |
| Read | SELECT cols FROM t | Pull data |
| Filter | WHERE | Row filter |
| Logic | AND, OR, NOT, () | Combine conditions |
| Compare | =, <>, <, >, BETWEEN | Values |
| Lists | IN, NOT IN | Many values |
| Text | LIKE, NOT LIKE | Pattern match |
| NULL | IS NULL, IS NOT NULL | Missing data |
| Display | COALESCE, IFNULL | Default for NULL |
| Unique | DISTINCT | Dedupe rows |
| Rename | AS alias | Readable output |
| Sort | ORDER BY, DESC | Rank rows |
| Page | LIMIT, OFFSET | Top-N / pages |
| Write | INSERT, UPDATE, DELETE | Change data (careful) |
| Next | GROUP BY, JOIN | sql3, sql4 |
Essential commands
| Command / action | What it does |
|---|---|
SELECT col1, col2 FROM t | Choose columns to return. |
WHERE + AND / OR / NOT | Filter rows. |
IN (...), BETWEEN a AND b | List and range filters. |
LIKE 'pattern' | Text pattern (%, _). |
IS NULL / IS NOT NULL | Filter missing values. |
COALESCE(col, default) | Replace NULL in results. |
ORDER BY col DESC | Sort results. |
LIMIT n / OFFSET n | Cap rows / pagination. |
DISTINCT, AS alias | Unique values and column names. |
INSERT / UPDATE / DELETE | Modify 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:
SELECTwithWHERE,ORDER BY,LIMIT- One query using
INorBETWEEN - One query using
LIKE - One query using
IS NULLorCOALESCE - One
DISTINCTand one columnASalias
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):
- Source: ___
Pattern: ___
Result: ___
- Source: ___
Pattern: ___
Result: ___
- Source: ___
Pattern: ___
Result: ___
- 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
INorBETWEEN - [ ] I used
LIKEwith% - [ ] Saved
.sqlfile with comments