SQL for data analysis: the parts you actually need
A lot of business data lives in databases, and SQL is the direct way in. For analysis you don't need the whole language, just six building blocks that come up again and again. Here they are, applied to real questions about a small online store, with actual results and exercises.
In short: JOIN brings together what's spread across tables, GROUP BY condenses it, CASE sorts values into bands, and date functions give you months and time gaps. Window functions add shares, rankings and month-over-month changes, and CTEs keep long analyses readable. Together they answer most questions from sales, finance and marketing.
The six building blocks of analysis
| Building block | Typical question | Lesson |
|---|---|---|
GROUP BY with SUM, COUNT, AVG | How much revenue per month, per category, per customer? | GROUP BY, HAVING |
JOIN | Which customer and which product sit behind each order? | SQL JOIN, LEFT JOIN |
CASE WHEN | How many small, medium and large orders are there? | CASE WHEN |
| Date functions | How is revenue trending month by month? How long since the last order? | date functions |
| Window functions | What share, which rank, how much more than last month? | window functions, LAG and LEAD |
WITH (CTE) | How do I build an analysis in steps someone else can follow? | CTEs |
Underneath it all you need the Level 1 basics: SELECT, WHERE, ORDER BY and handling NULL.
Example 1: revenue and orders per month
The practice database holds orders from January to June 2026. Revenue lives in the order items (quantity times unit price), status lives in the orders. So: join, drop the cancelled orders, and condense by month. The month is the first seven characters of the date, which is stored as YYYY-MM-DD:
SELECT substr(o.order_date, 1, 7) AS month,
COUNT(DISTINCT o.order_id) AS orders,
ROUND(SUM(i.quantity * i.unit_price), 2) AS revenue
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
| month | orders | revenue |
|---|---|---|
| 2026-01 | 3 | 1304.7 |
| 2026-02 | 2 | 1557.6 |
| 2026-03 | 3 | 3249.25 |
| 2026-04 | 2 | 229.85 |
| 2026-05 | 1 | 378.8 |
| 2026-06 | 5 | 2333.91 |
Note the COUNT(DISTINCT o.order_id). After the join, each order appears once per line item, so COUNT(*) would count items, not orders. Details like this decide whether a report is right.
Try condensing data yourself with a simpler question:
Task Purchasing wants to see how wide the product range is. Return one row per category with category and the number of products in that category.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
Example 2: each category's share of revenue
A share needs two totals: the category's and the overall one. A window function with nothing inside OVER works across the whole result, so it puts the grand total next to every group:
SELECT p.category,
ROUND(SUM(i.quantity * i.unit_price), 2) AS revenue,
ROUND(100.0 * SUM(i.quantity * i.unit_price)
/ SUM(SUM(i.quantity * i.unit_price)) OVER (), 1) AS pct_of_total
FROM order_items AS i
JOIN products AS p ON p.product_id = i.product_id
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY p.category
ORDER BY revenue DESC;
| category | revenue | pct_of_total |
|---|---|---|
| Furniture | 2823 | 31.2 |
| Paper | 2213.93 | 24.5 |
| Electronics | 1932 | 21.3 |
| Printer supplies | 1588.6 | 17.5 |
| Writing | 263.85 | 2.9 |
| Filing | 232.73 | 2.6 |
SUM(SUM(...)) OVER () looks odd at first, but it reads naturally: the inner SUM works per category, the outer one adds up those category totals across every row of the result. Writing 100.0 rather than 100 keeps the division in decimals.
Example 3: sorting orders by size
Each order needs its value first, then a band. A CTE lets you write that as two readable steps:
WITH order_values AS (
SELECT o.order_id, SUM(i.quantity * i.unit_price) AS value
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id
)
SELECT CASE WHEN value < 100 THEN 'small'
WHEN value < 500 THEN 'medium'
ELSE 'large' END AS size,
COUNT(*) AS orders,
ROUND(SUM(value), 2) AS revenue
FROM order_values
GROUP BY size
ORDER BY MIN(value);
| size | orders | revenue |
|---|---|---|
| small | 4 | 87.33 |
| medium | 5 | 1585.03 |
| large | 7 | 7381.75 |
The headline for management: seven large orders bring in over 80 percent of revenue, while four small ones don't reach 100 between them. CASE checks its conditions top to bottom, so value < 500 is enough for "medium"; anything under 100 was already caught. ORDER BY MIN(value) sorts the bands by size instead of alphabetically.
Task Large orders worth more than 1000 get a thank-you card. Use WITH to build a helper table order_totals with order_id and total (the sum of quantity * unit_price per order, from order_items). From it, show order_id and total for every order with a total above 1000.
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
Example 4: month-over-month change and running total
A monthly report puts the change and the year-to-date total next to every month. Window functions on top of Example 1 handle both:
WITH months AS (
SELECT substr(o.order_date, 1, 7) AS month, SUM(i.quantity * i.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY month
)
SELECT month,
ROUND(revenue, 2) AS revenue,
ROUND(revenue - LAG(revenue) OVER (ORDER BY month), 2) AS change,
ROUND(SUM(revenue) OVER (ORDER BY month), 2) AS running_total
FROM months
ORDER BY month;
| month | revenue | change | running_total |
|---|---|---|---|
| 2026-01 | 1304.7 | NULL | 1304.7 |
| 2026-02 | 1557.6 | 252.9 | 2862.3 |
| 2026-03 | 3249.25 | 1691.65 | 6111.55 |
| 2026-04 | 229.85 | -3019.4 | 6341.4 |
| 2026-05 | 378.8 | 148.95 | 6720.2 |
| 2026-06 | 2333.91 | 1955.11 | 9054.11 |
January has no previous month, hence NULL. It's also worth reading the numbers before reporting them: the April slump comes from two small orders, not from a trend. With this few orders a month, revenue swings a lot. An analysis isn't finished until you've put it in context.
Task Management wants to see how the annual payroll grew with each new hire. Show last_name, hire_date and salary for every employee, plus a fourth column, payroll: the running total of salaries up to and including that person. Sort by hire_date, earliest hire first.
employees 10 rows, 7 columns
| employee_id | first_name | last_name | department | salary | hire_date | manager_id |
|---|---|---|---|---|---|---|
| 1 | Karen | Mitchell | Management | 93600 | 2018-01-02 | NULL |
| 2 | Tom | Bradley | Sales | 62400 | 2019-04-01 | 1 |
| 3 | Julia | Reyes | Sales | 46800 | 2021-06-15 | 2 |
| 4 | Marcus | Allen | Sales | 49200 | 2020-09-01 | 2 |
| 5 | Sarah | Long | Warehouse | 39600 | 2022-02-01 | 1 |
| 6 | Felix | Turner | Warehouse | 35400 | 2024-03-18 | 5 |
| 7 | Nina | Cooper | Accounting | 52800 | 2019-10-01 | 1 |
| 8 | David | Ross | Customer service | 38400 | 2023-05-02 | 2 |
| 9 | Laura | Hughes | Customer service | NULL | 2025-09-01 | 2 |
| 10 | Paul | Ward | Accounting | 43200 | 2022-11-14 | 7 |
Example 5: who hasn't ordered in a while?
For a win-back campaign, what matters is the time since each customer's last order. SQLite's julianday turns dates into day numbers, so the difference is a count of days. The reference date here is the end of the data, 30 June 2026:
SELECT c.name,
MAX(o.order_date) AS last_order,
CAST(julianday('2026-06-30') - julianday(MAX(o.order_date)) AS INTEGER) AS days_since
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.status <> 'cancelled'
GROUP BY c.customer_id, c.name
ORDER BY days_since DESC
LIMIT 5;
| name | last_order | days_since |
|---|---|---|
| Lakeview Hotel Ltd | 2026-03-17 | 105 |
| Maple Grove High School | 2026-03-30 | 92 |
| Olivia Brooks | 2026-04-07 | 84 |
| Westbrook Dental Clinic | 2026-04-22 | 69 |
| Riverside County Office | 2026-05-06 | 55 |
Customers whose only order was cancelled don't appear, because the inner join with the status filter never finds them. Whether they belong on the list is a business call, not a SQL one. A LEFT JOIN would bring them in with an empty date.
Months and date gaps in MySQL, PostgreSQL and SQL Server
Joins, GROUP BY, CASE, CTEs and the window functions above are written the same way in all four databases. The differences are mostly in date functions:
| Database | Month as YYYY-MM | Days between two dates |
|---|---|---|
| SQLite (these exercises) | strftime('%Y-%m', order_date) | julianday(b) - julianday(a) |
| MySQL | DATE_FORMAT(order_date, '%Y-%m') | DATEDIFF(b, a) |
| PostgreSQL | to_char(order_date, 'YYYY-MM') or date_trunc('month', order_date) | b - a for columns of type date |
| SQL Server | DATETRUNC(month, order_date) from SQL Server 2022 | DATEDIFF(day, a, b) |
MySQL has supported window functions since version 8.0, SQLite since 3.25.0. Sources: MySQL Reference Manual (Date and Time Functions, What Is New in MySQL 8.0), PostgreSQL documentation (Date/Time Functions and Operators, Data Type Formatting Functions), Microsoft Learn (DATETRUNC, DATEDIFF), sqlite.org (Date And Time Functions, Window Functions).
SQL, Excel or Python?
Honestly, plenty of analysts use all three, each for what it does best.
| Good at | Not so good at | |
|---|---|---|
| SQL | working on data right where it lives, large and related tables, queries that run the same way every month | charts, statistics beyond basic metrics, quick manual fixes |
| Excel | small lists, quick what-ifs, PivotTables, charts, sharing with colleagues | large data (a worksheet tops out at 1,048,576 rows), tracing many manual steps |
| Python | statistics, forecasting, automation, pulling from many sources | getting started: learning to code and setting up an environment takes time up front |
A common day-to-day flow: SQL fetches and condenses the data, then Excel or Python takes it from there. If you already know Excel, a lot will feel familiar: GROUP BY does what a PivotTable does, and a JOIN replaces VLOOKUP. More in SQL for Excel users. For the Excel side of things, see data analysis in Excel.
Your path through the course
- Level 1, Getting started (free): SELECT, WHERE, sorting, NULL and calculations. After that you can pull any list out of a table.
- Level 2, Summarizing data: COUNT, SUM, GROUP BY, HAVING, CASE, text and dates. The core of every analysis.
- Level 3, Joining tables: JOIN, LEFT JOIN, subqueries and EXISTS.
- Level 4, Changing data: INSERT, UPDATE and DELETE, building tables, views and transactions.
- Level 5, Advanced queries: CTEs, window functions, running totals, LAG and LEAD, pivoting and duplicates.
- Level 6: real-work projects and the final test.
For analysts, levels 2, 3 and 5 matter most. Each ends with a project where you combine several building blocks into a real report. If you mainly need SQL to check requirements against data and pin down KPIs, see SQL for business analysts.
SQL for data analysts, the intensive course: once the basics are solid, it carries on with cases from an analyst's working week: a KPI overview, an order funnel, ABC analysis, time series, cohorts and data quality checks, with a certificate of its own.
FAQ
Is SQL enough for a data analyst job?
SQL covers getting at the data and condensing it. For presenting results you'll usually add Excel or a BI tool, and sometimes Python for statistics. It's still a great first step, because it means you can get the data yourself instead of waiting for exports.
Which database should I learn for analysis?
The queries on this page work with small tweaks in MySQL, PostgreSQL, SQL Server and SQLite. Learn the concepts; you can look up the date-function differences once you know which database your team uses.
How long does it take to learn SQL for data analysis?
That depends on how often you practice. The building blocks on this page are spread across levels 2, 3 and 5 of the course. Solving a few exercises regularly and doing the projects gets you there step by step.
Do I need to install anything?
No. Every exercise runs in your browser against a real SQLite database on our server. The examples on this page come from that same database.