SQL Mastery Notes: From Zero to Analyst-Level
SQL Mastery Notes: From Zero to AnalystLevel
Written the way a senior analyst would teach it: mental models first, syntax second,
practice always.
0. How to Use These Notes
Learn in layers. Sections 1 to 6 get you productive. Sections 7 to 11 make you strong.
Sections 12 to 15 make you senior.
Type every example. Reading SQL is not learning SQL. Run each query and change one
thing to see what breaks.
Practice setup (free): install SQLite or PostgreSQL, or use an online playground. Load a
sample dataset (e.g. Chinook, Northwind, or any CSV you like).
Rule of thumb: 20% reading, 80% writing queries.
Suggested pace: 6 to 8 weeks at 45 to 60 minutes a day.
Week
Focus
Sections
1
Basics: SELECT, WHERE, ORDER BY
1 to 3
2
Aggregation and GROUP BY
4
3
JOINs
5
4
Subqueries, CTEs, CASE
6 to 7
5
Window functions
8
6
Dates, strings, NULLs, set operations
9 to 10
7
Design, indexes, performance
11 to 13
8
Analyst patterns and projects
14 to 15
Page 1 of 19
SQL Mastery Notes: From Zero to Analyst-Level
1. The Big Picture
SQL (Structured Query Language) is how you talk to relational databases. A database is a
collection of tables. A table has columns (fields) and rows (records).
customers
+----+---------+-----------+------------+
| id | name
| country
| signup_date|
+----+---------+-----------+------------+
| 1 | Amina
| BD
| 2024-01-15 |
| 2 | Lucas
| BR
| 2024-02-03 |
+----+---------+-----------+------------+
Four families of SQL commands:
Family
Purpose
Examples
DQL (Query)
Read data
SELECT
DML (Manipulation)
Change data
INSERT , UPDATE , DELETE
DDL (Definition)
Change structure
CREATE , ALTER , DROP
DCL/TCL (Control)
Permissions, transactions
GRANT , COMMIT , ROLLBACK
As an analyst, you will spend about 90% of your time in SELECT .
Key vocabulary
Primary key (PK): column(s) that uniquely identify a row.
Foreign key (FK): a column that points to another table's primary key. This is how
tables relate.
Schema: the blueprint of tables, columns, and types.
Dialect: flavors of SQL (PostgreSQL, MySQL, SQL Server, SQLite, BigQuery,
Snowflake). 90% is identical; the differences are mostly dates, strings, and a few
functions.
2. The Single Most Important Mental Model
You write SQL in one order but the database executes it in another.
Written order:
Page 2 of 19
SQL Mastery Notes: From Zero to Analyst-Level
SELECT
columns
FROM
table
JOIN
other_table ON ...
WHERE
row_filter
GROUP BY columns
HAVING
group_filter
ORDER BY columns
LIMIT
n;
Logical execution order:
1. FROM and JOIN (build the working table)
2. WHERE (filter rows)
3. GROUP BY (form groups)
4. HAVING (filter groups)
5. SELECT (compute columns and aliases)
6. DISTINCT
7. ORDER BY
8. LIMIT
Why this matters (it explains many beginner errors):
You cannot use a SELECT alias in WHERE , because WHERE runs before SELECT .
You cannot use aggregates ( SUM , COUNT ) in WHERE ; use HAVING .
ORDER BY can use aliases because it runs after SELECT .
If you only memorize one thing from these notes, memorize this order.
3. Core Querying (Week 1)
3.1 SELECT and FROM
SELECT name, country FROM customers;
-- chosen columns
SELECT * FROM customers;
-- all columns (OK for exploring,
avoid in production)
SELECT DISTINCT country FROM customers;
-- unique values
SELECT name AS customer_name FROM customers; -- alias
Page 3 of 19
SQL Mastery Notes: From Zero to Analyst-Level
3.2 WHERE: filtering rows
SELECT * FROM orders
WHERE amount > 100
AND status = 'paid'
AND country IN ('BD', 'IN', 'PK')
AND created_at BETWEEN '2026-01-01' AND '2026-03-31'
AND customer_name LIKE 'A%';
-- starts with A
Operator
Meaning
= , <> (or != ), < , > , <= , >=
Comparison
AND , OR , NOT
Logic (use parentheses when mixing AND/OR)
IN (...)
Matches any in a list
BETWEEN a AND b
Inclusive range
LIKE
Pattern: % any characters, _ exactly one
IS NULL , IS NOT NULL
Test for missing values
Trap: WHERE a = 1 OR b = 2 AND c = 3 is read as a=1 OR (b=2 AND c=3) . Always use
parentheses.
3.3 ORDER BY and LIMIT
SELECT name, amount
FROM orders
ORDER BY amount DESC, name ASC
LIMIT 10;
-- SQL Server uses TOP 10; Oracle uses FETCH FIRST
3.4 Calculated columns
SELECT price * quantity AS revenue,
ROUND(price * 0.15, 2) AS tax
FROM order_items;
Page 4 of 19
SQL Mastery Notes: From Zero to Analyst-Level
4. Aggregation and GROUP BY (Week 2)
Aggregate functions collapse many rows into one value.
Function
Does
COUNT(*)
Counts rows
COUNT(col)
Counts non-NULL values
COUNT(DISTINCT col)
Counts unique non-NULL values
SUM , AVG , MIN , MAX
What they say (ignore NULLs)
SELECT country,
COUNT(*)
AS orders,
SUM(amount)
AS revenue,
AVG(amount)
AS avg_order
FROM orders
WHERE status = 'paid'
-- filter rows BEFORE grouping
GROUP BY country
HAVING SUM(amount) > 10000
-- filter groups AFTER grouping
ORDER BY revenue DESC;
The golden rule: every column in SELECT must either be inside an aggregate function or
appear in GROUP BY .
WHERE vs HAVING
WHERE filters rows before grouping.
HAVING filters groups after aggregation.
Conditional aggregation (a key analyst skill):
SELECT
COUNT(*) AS total_orders,
SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunds,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue
FROM orders;
This pattern builds pivot-style tables and KPIs in a single pass.
Page 5 of 19
SQL Mastery Notes: From Zero to Analyst-Level
5. JOINs (Week 3)
Joins combine tables on a related column. Think of two overlapping circles.
Join
Returns
INNER JOIN
Only rows that match in both tables
LEFT JOIN
All rows from the left table, plus matches from the
right (NULL if none)
RIGHT JOIN
Mirror of LEFT (rarely used; just flip the tables)
FULL OUTER JOIN
All rows from both, matched where possible
CROSS JOIN
Every combination (Cartesian product)
SELF JOIN
A table joined to itself (e.g., employee and
manager)
SELECT c.name, o.id AS order_id, o.amount
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;
Find rows with no match (anti-join):
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
-- customers who never ordered
Self join example:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
Join pitfalls that cause wrong numbers:
1. Row explosion: joining on a non-unique key multiplies rows. A customer with 5 orders
joined to 3 addresses gives 15 rows. Always know the grain (what one row represents)
of each table.
Page 6 of 19
SQL Mastery Notes: From Zero to Analyst-Level
2. LEFT JOIN turned into INNER JOIN: putting a right-table filter in WHERE removes the
NULL rows. Put it in the ON clause instead:
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
3. Wrong key: always check you join on the intended columns, and use table aliases to
avoid ambiguity.
Sanity check habit: after every join, compare COUNT(*) before and after. If it changed
unexpectedly, find out why.
6. Subqueries, CTEs, and CASE (Week 4)
6.1 Subqueries
-- In WHERE
SELECT * FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);
-- With IN
SELECT * FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE amount > 500);
-- In FROM (derived table)
SELECT country, AVG(total)
FROM (SELECT customer_id, country, SUM(amount) AS total
FROM orders GROUP BY customer_id, country) t
GROUP BY country;
-- EXISTS (fast existence check)
SELECT c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
6.2 CTEs (Common Table Expressions): your best friend
A CTE is a named temporary result. It makes complex queries readable, which matters
more than cleverness.
Page 7 of 19
SQL Mastery Notes: From Zero to Analyst-Level
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
),
top_customers AS (
SELECT * FROM customer_totals WHERE total_spent > 1000
)
SELECT c.name, t.total_spent
FROM top_customers t
JOIN customers c ON c.id = t.customer_id
ORDER BY t.total_spent DESC;
Professional habit: write queries as a chain of small CTEs, each doing one thing, instead of
one giant nested query.
Recursive CTE (hierarchies like org charts or category trees):
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS level
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.level + 1
FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org;
6.3 CASE: if/else logic
SELECT name, amount,
CASE
WHEN amount >= 1000 THEN 'High'
WHEN amount >= 100
ELSE 'Low'
THEN 'Medium'
END AS tier
FROM orders;
CASE works in SELECT , WHERE , ORDER BY , and inside aggregates.
Page 8 of 19
SQL Mastery Notes: From Zero to Analyst-Level
7. Modifying Data and Structure
-- Create
CREATE TABLE products (
id
INTEGER PRIMARY KEY,
name
price
VARCHAR(100) NOT NULL,
DECIMAL(10,2) CHECK (price >= 0),
category_id INTEGER REFERENCES categories(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert
INSERT INTO products (id, name, price) VALUES (1, 'Pen', 1.50);
-- Update (ALWAYS include WHERE)
UPDATE products SET price = 2.00 WHERE id = 1;
-- Delete (ALWAYS include WHERE)
DELETE FROM products WHERE id = 1;
-- Alter
ALTER TABLE products ADD COLUMN stock INTEGER DEFAULT 0;
-- Drop
DROP TABLE products;
Safety habit: before any UPDATE or DELETE , run the same condition as a SELECT first and
check the row count. Use transactions (section 12) for risky changes.
Constraints protect data quality: PRIMARY KEY , FOREIGN KEY , NOT NULL , UNIQUE ,
CHECK , DEFAULT .
8. Window Functions (Week 5): the analyst's superpower
A window function calculates across a set of related rows without collapsing them
(unlike GROUP BY ).
Syntax:
Page 9 of 19
SQL Mastery Notes: From Zero to Analyst-Level
function() OVER (
PARTITION BY col
ORDER BY col
-- restart calculation per group (optional)
-- ordering inside the group
ROWS BETWEEN ...
-- frame (optional)
)
8.1 Ranking
Function
Behavior on ties
ROW_NUMBER()
1,2,3,4 (always unique)
RANK()
1,2,2,4 (gaps)
DENSE_RANK()
1,2,2,3 (no gaps)
NTILE(n)
Splits into n buckets
-- Top 3 products per category
WITH ranked AS (
SELECT category, product, revenue,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS
rn
FROM product_sales
)
SELECT * FROM ranked WHERE rn <= 3;
(You need the CTE because window functions cannot be used directly in WHERE .)
8.2 Looking at other rows
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
LEAD(revenue) OVER (ORDER BY month) AS next_month,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_revenue;
Page 10 of 19
SQL Mastery Notes: From Zero to Analyst-Level
8.3 Running totals and moving averages
SELECT date, sales,
SUM(sales) OVER (ORDER BY date) AS running_total,
AVG(sales) OVER (ORDER BY date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS
moving_avg_7d
FROM daily_sales;
8.4 Share of total
SELECT category, revenue,
revenue * 100.0 / SUM(revenue) OVER () AS pct_of_total
FROM category_revenue;
Other useful ones: FIRST_VALUE , LAST_VALUE , PERCENT_RANK , CUME_DIST .
9. Working With NULLs, Dates, and Strings
9.1 NULL: the "unknown" value
NULL is not zero or empty. It means unknown.
NULL = NULL is not true. Use IS NULL .
Any arithmetic with NULL gives NULL: 5 + NULL is NULL .
Aggregates (except COUNT(*) ) ignore NULLs.
NOT IN (subquery) returns nothing if the subquery contains a NULL. Prefer NOT
EXISTS .
COALESCE(discount, 0)
NULLIF(x, 0)
-- first non-NULL value
-- returns NULL if x = 0 (avoids divide-by-zero)
Page 11 of 19
SQL Mastery Notes: From Zero to Analyst-Level
9.2 Dates (syntax varies by dialect; the ideas do not)
-- PostgreSQL examples
CURRENT_DATE
DATE_TRUNC('month', order_date)
EXTRACT(YEAR FROM order_date)
-- first day of the month
order_date + INTERVAL '7 days'
AGE(date1, date2)
-- MySQL: DATE_FORMAT, DATEDIFF, DATE_ADD
-- SQL Server: DATEPART, DATEDIFF, DATEADD
-- BigQuery: DATE_TRUNC, DATE_DIFF, FORMAT_DATE
Typical analyst task, monthly trend:
SELECT DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY 1
ORDER BY 1;
9.3 Strings
UPPER(s), LOWER(s), TRIM(s), LENGTH(s)
SUBSTRING(s, start, len)
REPLACE(s, 'old', 'new')
CONCAT(a, ' ', b)
SPLIT_PART(s, ',', 1)
-- or a || ' ' || b
-- PostgreSQL
9.4 Type casting
CAST(price AS INTEGER)
price::INTEGER
-- PostgreSQL shorthand
10. Set Operations
Stack results of two queries that have the same number of columns and compatible
types.
Page 12 of 19
SQL Mastery Notes: From Zero to Analyst-Level
Operator
Result
UNION
Combine and remove duplicates
UNION ALL
Combine and keep duplicates (faster; prefer when
possible)
INTERSECT
Rows in both
EXCEPT ( MINUS in Oracle)
Rows in the first but not the second
11. Database Design Basics
11.1 Normalization (avoid duplicated data)
1NF: each cell holds one value; no repeating groups.
2NF: every non-key column depends on the whole key.
3NF: non-key columns depend only on the key, not on each other.
Plain English: store each fact once, in the right table, and link with keys.
11.2 Relationship types
One-to-many: one customer, many orders (FK on the "many" side).
Many-to-many: students and courses (needs a junction table).
One-to-one: user and profile.
11.3 Analytics designs
OLTP (apps, normalized, many small writes) vs OLAP (analytics, denormalized, big
reads).
Star schema: a central fact table (events: sales, clicks) surrounded by dimension
tables (who, what, when, where). Most warehouses use this.
12. Transactions and Safety
A transaction groups statements into one all-or-nothing unit.
Page 13 of 19
SQL Mastery Notes: From Zero to Analyst-Level
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
-- or ROLLBACK; to undo
ACID: Atomicity, Consistency, Isolation, Durability.
Also know: views ( CREATE VIEW saves a query as a virtual table) and stored procedures
exist, but analysts mostly consume them rather than build them.
13. Performance and Indexes
Index = book index. It lets the database find rows without scanning the whole table.
CREATE INDEX idx_orders_customer ON orders(customer_id);
Index columns used in: WHERE , JOIN ... ON , and ORDER BY on large tables. Indexes
speed up reads but slow writes and use storage.
Query-writing habits that keep things fast:
Select only the columns you need (no SELECT * in production).
Filter early; reduce rows before joining when possible.
Avoid functions on indexed columns in WHERE ( WHERE YEAR(date) = 2026 blocks
index use; use a date range instead).
Prefer UNION ALL to UNION when duplicates are impossible or acceptable.
Prefer EXISTS over IN for large subqueries.
Use EXPLAIN (or EXPLAIN ANALYZE ) to see the query plan. Look for full table scans on
big tables.
In cloud warehouses (BigQuery, Snowflake), cost often depends on data scanned.
Filter on partition columns and avoid SELECT * .
Page 14 of 19
SQL Mastery Notes: From Zero to Analyst-Level
14. Analyst Patterns You Will Use Constantly
14.1 Deduplication
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC)
AS rn
FROM users
)
SELECT * FROM ranked WHERE rn = 1;
-- latest row per email
14.2 Find duplicates
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
14.3 Month-over-month growth
WITH m AS (
SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue
FROM orders GROUP BY 1
)
SELECT month, revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS
growth_pct
FROM m;
14.4 Cohort retention (simplified)
WITH first_order AS (
SELECT customer_id, MIN(DATE_TRUNC('month', order_date)) AS cohort_month
FROM orders GROUP BY customer_id
)
SELECT f.cohort_month,
DATE_TRUNC('month', o.order_date) AS activity_month,
COUNT(DISTINCT o.customer_id) AS active_customers
FROM orders o
JOIN first_order f ON f.customer_id = o.customer_id
GROUP BY 1, 2
ORDER BY 1, 2;
Page 15 of 19
SQL Mastery Notes: From Zero to Analyst-Level
14.5 Funnel conversion
SELECT
COUNT(DISTINCT CASE WHEN step = 'visit'
THEN user_id END) AS visits,
COUNT(DISTINCT CASE WHEN step = 'signup'
THEN user_id END) AS signups,
COUNT(DISTINCT CASE WHEN step = 'purchase' THEN user_id END) AS purchases
FROM events;
14.6 Gaps and islands, consecutive days (trick)
SELECT user_id, MIN(day) AS streak_start, MAX(day) AS streak_end, COUNT(*) AS
days
FROM (
SELECT user_id, day,
day - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) *
INTERVAL '1 day' AS grp
FROM logins
) t
GROUP BY user_id, grp;
14.7 Pivot with CASE
SELECT product,
SUM(CASE WHEN month = 'Jan' THEN sales END) AS jan,
SUM(CASE WHEN month = 'Feb' THEN sales END) AS feb
FROM monthly_sales
GROUP BY product;
15. Habits of a Senior Analyst
1. Know the grain. Before writing a query, say out loud: "One row in this result represents
___."
2. Start small. Build the query step by step, checking each stage with LIMIT 10 .
3. Validate. Compare totals with a known number (dashboard, finance report). Check
row counts before and after joins.
4. Format for humans. Uppercase keywords, one clause per line, meaningful aliases,
comments for tricky logic.
5. Prefer readable over clever. CTEs beat deep nesting.
Page 16 of 19
SQL Mastery Notes: From Zero to Analyst-Level
6. Beware of edge cases: NULLs, duplicates, time zones, test data, canceled or refunded
orders, inclusive vs exclusive date ranges.
7. Ask the business question first. SQL is a tool; the real skill is turning a vague question
("are customers happy?") into a precise metric.
8. Document your logic. Future you (and your teammates) will thank you.
16. Common Mistakes Checklist
Mistake
Fix
Using = NULL
Use IS NULL
Alias in WHERE
Repeat the expression or use a CTE
Aggregates in WHERE
Use HAVING
Non-grouped column in SELECT
Add to GROUP BY or aggregate it
Forgetting WHERE on UPDATE / DELETE
Test with SELECT first; use transactions
Duplicated rows after join
Check join keys and grain
COUNT(col) when you meant COUNT(*)
Remember COUNT(col) skips NULLs
Integer division ( 1/2 = 0 )
Multiply by 1.0 or cast
BETWEEN with timestamps missing the last day
Use >= start AND < next_day
NOT IN with NULLs
Use NOT EXISTS
UNION instead of UNION ALL slowing queries
Use UNION ALL when safe
17. Practice Plan
Daily routine (45 min):
1. 10 min: review one concept from these notes.
2. 25 min: solve 2 to 3 problems.
3. 10 min: rewrite yesterday's hardest query more cleanly.
Page 17 of 19
SQL Mastery Notes: From Zero to Analyst-Level
Where to practice: LeetCode (Database), HackerRank (SQL), StrataScratch, DataLemur,
SQLBolt, Mode SQL Tutorial, SQLZoo, Select Star SQL.
Three portfolio projects:
1. E-commerce analysis: revenue trends, top products, customer segments (RFM),
repeat purchase rate.
2. User behavior: funnel, retention cohorts, DAU/WAU/MAU.
3. HR or finance dataset: rankings, running totals, year-over-year comparison.
Publish them (GitHub or a short write-up) with the question, the query, and the insight.
Level-check self-test. You are job-ready when you can, without help:
Join 4 tables and explain why the row count is what it is.
Write a top-N-per-group query with a window function.
Compute month-over-month growth and a 7-day moving average.
Build a retention cohort table.
Find and remove duplicates.
Read an EXPLAIN plan and suggest an index.
Page 18 of 19
SQL Mastery Notes: From Zero to Analyst-Level
18. One-Page Cheat Sheet
WITH step1 AS (
SELECT ...
),
step2 AS (
SELECT ...
)
SELECT
a.col1,
b.col2,
COUNT(*)
AS n,
SUM(CASE WHEN ... THEN 1 END)
AS flagged,
ROW_NUMBER() OVER (PARTITION BY a.col1 ORDER BY b.col2 DESC) AS rn
FROM
step1 a
LEFT JOIN step2 b ON a.id = b.id
WHERE
a.date >= '2026-01-01'
GROUP BY a.col1, b.col2
HAVING
COUNT(*) > 5
ORDER BY n DESC
LIMIT
100;
Remember:
Execution order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT
WHERE filters rows; HAVING filters groups.
LEFT JOIN + IS NULL finds missing matches.
Window functions keep rows; GROUP BY collapses them.
Know the grain, check the counts, keep it readable.
Master these 18 sections and you will be stronger at SQL than most working analysts.
Consistency beats intensity: one query a day for 60 days beats a weekend binge.
Page 19 of 19
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )