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 blockTypical questionLesson
GROUP BY with SUM, COUNT, AVGHow much revenue per month, per category, per customer?GROUP BY, HAVING
JOINWhich customer and which product sit behind each order?SQL JOIN, LEFT JOIN
CASE WHENHow many small, medium and large orders are there?CASE WHEN
Date functionsHow is revenue trending month by month? How long since the last order?date functions
Window functionsWhat 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;
monthordersrevenue
2026-0131304.7
2026-0221557.6
2026-0333249.25
2026-042229.85
2026-051378.8
2026-0652333.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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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;
categoryrevenuepct_of_total
Furniture282331.2
Paper2213.9324.5
Electronics193221.3
Printer supplies1588.617.5
Writing263.852.9
Filing232.732.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);
sizeordersrevenue
small487.33
medium51585.03
large77381.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_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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;
monthrevenuechangerunning_total
2026-011304.7NULL1304.7
2026-021557.6252.92862.3
2026-033249.251691.656111.55
2026-04229.85-3019.46341.4
2026-05378.8148.956720.2
2026-062333.911955.119054.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_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

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;
namelast_orderdays_since
Lakeview Hotel Ltd2026-03-17105
Maple Grove High School2026-03-3092
Olivia Brooks2026-04-0784
Westbrook Dental Clinic2026-04-2269
Riverside County Office2026-05-0655

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:

DatabaseMonth as YYYY-MMDays between two dates
SQLite (these exercises)strftime('%Y-%m', order_date)julianday(b) - julianday(a)
MySQLDATE_FORMAT(order_date, '%Y-%m')DATEDIFF(b, a)
PostgreSQLto_char(order_date, 'YYYY-MM') or date_trunc('month', order_date)b - a for columns of type date
SQL ServerDATETRUNC(month, order_date) from SQL Server 2022DATEDIFF(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 atNot so good at
SQLworking on data right where it lives, large and related tables, queries that run the same way every monthcharts, statistics beyond basic metrics, quick manual fixes
Excelsmall lists, quick what-ifs, PivotTables, charts, sharing with colleagueslarge data (a worksheet tops out at 1,048,576 rows), tracing many manual steps
Pythonstatistics, forecasting, automation, pulling from many sourcesgetting 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

  1. Level 1, Getting started (free): SELECT, WHERE, sorting, NULL and calculations. After that you can pull any list out of a table.
  2. Level 2, Summarizing data: COUNT, SUM, GROUP BY, HAVING, CASE, text and dates. The core of every analysis.
  3. Level 3, Joining tables: JOIN, LEFT JOIN, subqueries and EXISTS.
  4. Level 4, Changing data: INSERT, UPDATE and DELETE, building tables, views and transactions.
  5. Level 5, Advanced queries: CTEs, window functions, running totals, LAG and LEAD, pivoting and duplicates.
  6. 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.

Go to the intensive course

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.

Start analyzing

Level 1 is free and lays the groundwork. Then GROUP BY and joins take you to your first real analyses.

Go to the SQL course Intensive course for analysts

Write to us

Choose language

Select your preferred language