Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
SQL

How to learn SQL for data analysis: a beginner's roadmap

· 10 min read

You've been asked a simple question at work: "How did sales change month by month, and which marketing channel brings our best customers?" The data is in a database. A spreadsheet export would take an hour of copying and pivoting. Five lines of SQL would answer it in seconds, if you knew which five lines.

This guide is a roadmap for learning SQL for data analysis, in the order the skills build on each other. Each step has a real query and its real result, run in SQLite, so you can see what you'll be able to do. It's written for complete beginners and for spreadsheet users who want to move to SQL.

Why analysts use SQL

Most company data lives in databases, not spreadsheets. SQL lets you ask questions of that data directly, on millions of rows, and the same query gives the same answer next month, which makes your reports repeatable. Spreadsheets are still great for the last step, a chart or a quick look. SQL is how you get the right numbers into them.

The good news for beginners: analysis uses only a part of SQL. You mostly read data. You rarely create tables or change data, which removes a lot of what developers need to learn.

The dataset we'll use

Every query below uses two small tables from an imaginary online shop: orders, and customers with the channel they signed up through.

setup.sql
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, city TEXT, order_date TEXT, amount REAL);
INSERT INTO orders (customer, city, order_date, amount) VALUES
  ('Alex', 'Lisbon', '2026-09-03', 42.50), ('Sam', 'Berlin', '2026-09-05', 18.00),
  ('Alex', 'Lisbon', '2026-09-20', 30.00), ('Mia', 'Berlin', '2026-10-02', 75.25),
  ('Sam', 'Berlin', '2026-10-11', 22.00), ('Noah', 'Dublin', '2026-10-15', 12.75),
  ('Mia', 'Berlin', '2026-10-28', 40.00), ('Alex', 'Lisbon', '2026-11-01', 55.00);

CREATE TABLE customers (name TEXT PRIMARY KEY, signup_channel TEXT);
INSERT INTO customers VALUES ('Alex', 'newsletter'), ('Sam', 'search'),
  ('Mia', 'search'), ('Noah', 'friend'), ('Lena', 'newsletter');

Paste this into any SQLite tool, and you can follow along.

Step 1: Select, filter and sort

Every analysis starts with getting the right rows. SELECT chooses the columns, WHERE filters the rows, ORDER BY sorts them:

sql
SELECT customer, amount
FROM orders
WHERE amount > 40
ORDER BY amount DESC;
Result
customer  amount
--------  ------
Mia       75.25
Alex      55.0
Alex      42.5

What to learn in this step:

  • Comparisons: =, <>, >, <=, and BETWEEN.
  • Combining conditions with AND, OR and brackets.
  • IN ('Berlin', 'Lisbon') for lists, and LIKE 'Al%' for text patterns.
  • IS NULL for missing values. = NULL never works, a classic beginner trap.
  • LIMIT to look at a sample before you run a big query.

If a query fails with a message about a column, our article on SQLite: no such column explains the usual causes.

Step 2: Summarise with aggregates and GROUP BY

Analysis is mostly summarising. COUNT, SUM, AVG, MIN and MAX turn many rows into one number:

sql
SELECT ROUND(AVG(amount), 2) AS avg_order FROM orders;
Result
avg_order
---------
36.94

GROUP BY does the same per group. This is the single most important step for an analyst:

sql
SELECT city, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
GROUP BY city
ORDER BY revenue DESC;
Result
city    orders  revenue
------  ------  -------
Berlin  4       155.25
Lisbon  3       127.5
Dublin  1       12.75

If you know pivot tables, this is the same idea: rows grouped by city, with values summarised. To filter groups rather than rows, use HAVING. Customers with at least two orders:

sql
SELECT customer, COUNT(*) AS orders
FROM orders
GROUP BY customer
HAVING COUNT(*) >= 2
ORDER BY orders DESC;
Result
customer  orders
--------  ------
Alex      3
Sam       2
Mia       2

The difference between WHERE and HAVING causes some of the most confusing SQL errors. Our article on GROUP BY errors walks through them.

Step 3: Work with dates

Almost every business question has a time in it: per month, last week, year over year. Dates are where databases differ the most. In SQLite, dates are often stored as text like 2026-10-02, so you can take the first seven characters to get the month:

sql
SELECT substr(order_date, 1, 7) AS month,
       COUNT(*) AS orders,
       ROUND(SUM(amount), 2) AS revenue
FROM orders
GROUP BY month
ORDER BY month;
Result
month    orders  revenue
-------  ------  -------
2026-09  3       90.5
2026-10  4       150.0
2026-11  1       55.0

PostgreSQL uses date_trunc('month', order_date) and MySQL uses DATE_FORMAT, but the idea is the same: turn each date into a month, then group by it. When you start at a company, find out which database it uses and learn its date functions early.

Step 4: Join tables

Real data is spread across tables. Orders don't store the signup channel; customers do. A JOIN connects them. Here's revenue by signup channel, which answers the second half of the question at the top:

sql
SELECT c.signup_channel,
       COUNT(o.id) AS orders,
       ROUND(COALESCE(SUM(o.amount), 0), 2) AS revenue
FROM customers c
LEFT JOIN orders o ON o.customer = c.name
GROUP BY c.signup_channel
ORDER BY revenue DESC;
Result
signup_channel  orders  revenue
--------------  ------  -------
search          4       155.25
newsletter      3       127.5
friend          1       12.75

Two things worth noticing:

  • LEFT JOIN keeps every customer, even Lena, who has never ordered. With a plain JOIN, she'd disappear, and you wouldn't know your newsletter brought a customer who never bought.
  • COUNT(o.id) counts orders, not customers. COUNT(*) would count Lena's empty row as one.

The same pattern finds customers with no orders at all:

sql
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer = c.name
WHERE o.id IS NULL;
Result
name
----
Lena

Joins are where analysts make their most expensive mistakes. A join on the wrong column, or one where a customer matches several rows, can quietly multiply your totals. Always check the row count before and after a join.

Step 5: Break big questions into steps with WITH

Complex analysis is easier in steps. A common table expression (CTE), written with WITH, gives a name to a query so the next query can use it like a table. Here's revenue per month, with the change from the month before:

sql
WITH monthly AS (
  SELECT substr(order_date, 1, 7) AS month, SUM(amount) AS revenue
  FROM orders
  GROUP BY month
)
SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly;
Result
month    revenue  change
-------  -------  ------
2026-09  90.5     NULL
2026-10  150.0    59.5
2026-11  55.0     -95.0

The first month has no previous month, so the change is NULL. (November looks like a drop, but our data ends on 1 November. Checking whether the last period is complete is a habit every analyst needs.)

Step 6: Window functions

LAG above is a window function: it looks at other rows without collapsing them into groups. Window functions answer questions like running totals, rankings and "compared with the previous order". A running total per customer:

sql
SELECT customer, order_date, amount,
       SUM(amount) OVER (PARTITION BY customer ORDER BY order_date) AS running_total
FROM orders
WHERE customer = 'Alex';
Result
customer  order_date  amount  running_total
--------  ----------  ------  -------------
Alex      2026-09-03  42.5    42.5
Alex      2026-09-20  30.0    72.5
Alex      2026-11-01  55.0    127.5

Learn these after GROUP BY and joins feel natural, not before. They build on both.

Mistakes that give wrong numbers

The dangerous mistakes in analysis aren't the ones that cause errors. They're the ones that run and return a believable, wrong number. Four to watch for, all checked in SQLite:

  • A join that multiplies rows. If you join orders to a table that has several rows per customer, such as a table of website visits, every order is repeated once per visit. In our test, a customer with two orders totalling 30 and three visits showed a total of 90 after the join. Count rows before and after every join.
  • Whole-number division. In SQLite, 7 / 2 gives 3, not 3.5, because both numbers are integers. Write 7 * 1.0 / 2 or 7 / 2.0 when you want decimals. Percentages are the usual victim.
  • Missing values and averages. AVG ignores NULL. For the values 10, 20 and a missing one, AVG gives 15.0, while SUM divided by COUNT(*) gives 10. Decide which one your question needs.
  • Comparing with NULL. NULL = NULL isn't true; it's NULL, so WHERE x = NULL finds nothing. Use IS NULL.

None of these produce an error message, which is why checking your numbers is a habit, not an extra step.

A realistic timeline

At one focused session a week, with short practice in between, a beginner can expect roughly this (our estimate):

  • Weeks 1 to 2: step 1, filtering and sorting.
  • Weeks 3 to 5: step 2, aggregates and GROUP BY.
  • Weeks 6 to 8: steps 3 and 4, dates and joins.
  • Months 3 to 4: step 5, CTEs, on real questions.
  • After that: window functions, and lots of practice on messy data.

For a broader view of the timeline, see how long it takes to learn SQL.

How to practise

  • Use real questions. "Which month was best?" teaches more than "write a query with GROUP BY".
  • Check your numbers. Count rows before and after every join. Compare one total with a quick calculation by hand.
  • Find public datasets. Government open data portals and public dataset collections have CSV files you can load into SQLite.
  • Write the question first, in words, as a comment above the query. If you can't write the question clearly, the query won't be clear either.

What comes after SQL

SQL gets you the right numbers. The next skills for an analyst are usually:

  • A spreadsheet or reporting tool to present results.
  • Python with a library like pandas, for analysis that's awkward in SQL, like statistics or cleaning messy text.
  • Basic statistics: averages versus medians, and why a small sample can mislead.

If you're deciding between Python and SQL as a starting point, our comparison of which programming language to learn first can help.

Frequently asked questions

How much SQL do I need for a data analyst job?

Comfortable use of steps 1 to 4 (filtering, GROUP BY, dates and joins) covers most daily work. CTEs and window functions are often asked about in interviews for analyst roles.

Should I learn SQL or Python first for data analysis?

For most analysts, SQL first. It's smaller, and it's how you get data out of company databases. Python comes next, for the work SQL does badly.

Which database should I practise on?

SQLite is the easiest to start with: one file, no server. The core of what you learn works in PostgreSQL, MySQL and others too. Date functions are the main difference.

Can I learn SQL for data analysis without a technical background?

Yes. If you can build a pivot table or a SUMIF in a spreadsheet, you already think the way GROUP BY works.

Do I need to learn database design?

Only the basics: what a primary key and a foreign key are, so you know how to join tables correctly. Designing databases is more a developer's job.

A quick checklist

  1. Learn filtering and sorting until you don't need to look anything up.
  2. Master GROUP BY and HAVING before anything else advanced.
  3. Learn your database's date functions.
  4. Check row counts before and after every join.
  5. Break big questions into steps with WITH.
  6. Add window functions last.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

SQL

SQLite error: no such table, and how to fix it

Why SQLite says no such table (sqlite3.OperationalError: no such table): a typo, a table never created, or the wrong database file, often a new empty one. How to check and fix each, with real output.

Error explained · · 9 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right