SQL for data analysis comes down to a handful of ideas: filter rows, group them, join tables, and compare groups over time. This tutorial teaches them by running real queries on a real database and showing the exact output of every one. You do not need to install a database server. Everything runs in SQLite, which ships with Python.
The data is the Chinook sample database, the sales records of a fictional digital music store: github.com/lerocha/chinook-database. It is a teaching database, not company data, so read the results as exercises, not business facts. Every query below was run on 20 November 2026 with SQLite 3.53.1.
Set up: run SQL from Python in three lines
import sqlite3
import pandas as pd
con = sqlite3.connect("chinook.sqlite")
def q(sql):
return pd.read_sql(sql, con)Download the Chinook_Sqlite.sqlite file from the repository’s ChinookDatabase/DataSources folder and save it as chinook.sqlite. The same SQL also works in the sqlite3 command line, DB Browser for SQLite or any SQL notebook. If you would rather start from your own CSV, the CSV to SQL tool turns a file into CREATE TABLE and INSERT statements.
The tables we use: Invoice (412 rows, one per order), InvoiceLine (2,240 rows, one per track bought), Customer (59), Track (3,503) and Genre (25).
1. Start with the shape of the data
Before any analysis, count rows and check the date range. COUNT, MIN, MAX and SUM are aggregate functions: they collapse many rows into one.
SELECT COUNT(*) AS invoices,
MIN(InvoiceDate) AS first,
MAX(InvoiceDate) AS last,
ROUND(SUM(Total), 2) AS revenue
FROM Invoice;invoices | first | last | revenue
412 | 2021-01-01 00:00:00 | 2025-12-22 00:00:00 | 2328.6Five years, 412 invoices, 2,328.60 in revenue. Now we know what a typical total looks like before we start slicing it.
2. GROUP BY: revenue per country
GROUP BY splits the rows into groups and runs the aggregate once per group. ORDER BY ... DESC puts the biggest first.
SELECT BillingCountry,
COUNT(*) AS invoices,
ROUND(SUM(Total), 2) AS revenue
FROM Invoice
GROUP BY BillingCountry
ORDER BY revenue DESC
LIMIT 5;BillingCountry | invoices | revenue
USA | 91 | 523.06
Canada | 56 | 303.96
France | 35 | 195.1
Brazil | 35 | 190.1
Germany | 28 | 156.48The USA and Canada account for 827.02 of the 2,328.60 total, about 36%. The chart shows the same five countries.

3. WHERE filters rows, HAVING filters groups
WHERE runs before grouping and sees single rows. HAVING runs after grouping and sees the aggregates. Use it to drop countries with too little data to trust:
SELECT BillingCountry, COUNT(*) AS invoices
FROM Invoice
GROUP BY BillingCountry
HAVING COUNT(*) >= 10
ORDER BY invoices DESC;Of the 24 billing countries, only 9 have 10 or more invoices: USA 91, Canada 56, France 35, Brazil 35, Germany 28, United Kingdom 21, Portugal 14, Czech Republic 14 and India 13. The other 15 countries have fewer than 10 invoices each and together bring in 604.30 of revenue, so a “best country” ranking built on them is mostly noise.
4. JOIN: revenue by genre
Genre lives in another table, so we join InvoiceLine to Track to Genre through their keys.
SELECT g.Name AS genre,
COUNT(*) AS tracks_sold,
ROUND(SUM(il.UnitPrice * il.Quantity), 2) AS revenue
FROM InvoiceLine il
JOIN Track t ON t.TrackId = il.TrackId
JOIN Genre g ON g.GenreId = t.GenreId
GROUP BY g.Name
ORDER BY revenue DESC
LIMIT 5;genre | tracks_sold | revenue
Rock | 835 | 826.65
Latin | 386 | 382.14
Metal | 264 | 261.36
Alternative & Punk | 244 | 241.56
TV Shows | 47 | 93.53Rock earns 826.65, which is 35.5% of the 2,328.60 total. Note TV Shows: only 47 sales but 93.53 in revenue, because those tracks cost 1.99 each instead of 0.99.
5. The mistake that quietly inflates revenue
This is the most common SQL error in analysis. Invoice.Total is stored once per invoice. If you join invoices to their lines and then sum Total, every invoice is counted once for each line it has:
SELECT ROUND(SUM(i.Total), 2) AS wrong_revenue
FROM Invoice i
JOIN InvoiceLine il ON il.InvoiceId = i.InvoiceId;wrong_revenue
20848.62That is 20,848.62 against the true 2,328.60, nearly nine times too high, and the query runs without any error. The habit that catches it: after every join, compare a total to a number you already trust, such as the one from section 1. Fix it by summing at the grain you joined on (il.UnitPrice * il.Quantity, as in section 4) or by aggregating before you join.
6. Dates, CTEs and LAG: yearly growth
A WITH clause (common table expression) names an intermediate result so the next query reads top to bottom. LAG is a window function: it looks at the previous row without collapsing the data.
WITH yearly AS (
SELECT strftime('%Y', InvoiceDate) AS year,
SUM(Total) AS revenue
FROM Invoice
GROUP BY year
)
SELECT year,
ROUND(revenue, 2) AS revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY year))
/ LAG(revenue) OVER (ORDER BY year), 1) AS growth_pct
FROM yearly;year | revenue | growth_pct
2021 | 449.46 | None
2022 | 481.45 | 7.1
2023 | 469.58 | -2.5
2024 | 477.53 | 1.7
2025 | 450.58 | -5.6Revenue is flat: 449 to 481 over five years, with no growth trend. The first year has no previous row, so LAG returns NULL (shown as None by pandas). Date functions differ by database: strftime is SQLite, PostgreSQL uses EXTRACT(YEAR FROM ...) or date_trunc, and MySQL uses YEAR(...).
7. Window functions: rank and share of total
SELECT BillingCountry,
ROUND(SUM(Total), 2) AS revenue,
RANK() OVER (ORDER BY SUM(Total) DESC) AS rnk,
ROUND(100.0 * SUM(Total) / SUM(SUM(Total)) OVER (), 1) AS share_pct
FROM Invoice
GROUP BY BillingCountry
ORDER BY rnk
LIMIT 5;BillingCountry | revenue | rnk | share_pct
USA | 523.06 | 1 | 22.5
Canada | 303.96 | 2 | 13.1
France | 195.1 | 3 | 8.4
Brazil | 190.1 | 4 | 8.2
Germany | 156.48 | 5 | 6.7SUM(SUM(Total)) OVER () is the grand total repeated on every row, which is what lets one query give each country’s share. SQLite documents the full window-function syntax in its window functions guide.
8. Test a common claim: do the top customers drive revenue?
Many businesses assume the top 20% of customers bring most of the revenue. NTILE(5) splits customers into five equal groups by spend, so we can check:
WITH spend AS (
SELECT CustomerId, SUM(Total) AS s
FROM Invoice
GROUP BY CustomerId
),
ranked AS (
SELECT CustomerId, s, NTILE(5) OVER (ORDER BY s DESC) AS quint
FROM spend
)
SELECT quint,
COUNT(*) AS customers,
ROUND(SUM(s), 2) AS revenue,
ROUND(100.0 * SUM(s) / (SELECT SUM(s) FROM spend), 1) AS share_pct
FROM ranked
GROUP BY quint
ORDER BY quint;quint | customers | revenue | share_pct
1 | 12 | 533.44 | 22.9
2 | 12 | 475.44 | 20.4
3 | 12 | 455.44 | 19.6
4 | 12 | 451.44 | 19.4
5 | 11 | 412.84 | 17.7Here the claim fails. The top fifth of customers brings 22.9% of revenue, barely above an even 20%. The biggest single customer spent 49.62 against about 39 on average, so there are no whales in this data. Real stores usually look very different: in our retail data project the top 20% of customers brought 75% of revenue. Checking beats assuming.
9. Check the answer in pandas
A good habit is to reproduce one SQL result another way. This pandas query of the same table gives the same top five countries to the cent (pandas 3.0.5):
inv = q("SELECT BillingCountry, Total FROM Invoice")
print(inv.groupby("BillingCountry").Total.sum().nlargest(5).round(2))In practice, SQL is better for filtering and aggregating inside the database, and pandas is better for what comes after: modelling and charts. See data manipulation with pandas and exploratory data analysis in Python.
10. Why indexes matter
Ask SQLite how it would run a query with EXPLAIN QUERY PLAN:
EXPLAIN QUERY PLAN
SELECT * FROM Invoice WHERE CustomerId = 5;SEARCH Invoice USING INDEX IFK_InvoiceCustomerId (CustomerId=?)The word SEARCH means the database jumps straight to the matching rows through an index. Without that index it would print SCAN and read all 412 rows, which is harmless here and painful on 400 million. Index the columns you filter and join on.
Quick reference
SELECT what to return
FROM which table
JOIN which other tables, on which keys
WHERE which rows (before grouping)
GROUP BY what to group by
HAVING which groups (after grouping)
ORDER BY sort order
LIMIT how many rowsSQL runs these in a different order than you write them: FROM and JOIN first, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY and LIMIT. That is why you cannot use a SELECT alias inside WHERE.
If you work in spreadsheets today, the same ideas appear in Excel for data analysis. For where this skill leads, see the data science career guide.
Frequently asked questions
Is SQL enough for data analysis?
It is enough for a large part of it: pulling, cleaning, aggregating and comparing data. Most analysts pair it with a spreadsheet or Python for charts and statistics.
Which SQL should I learn first?
Learn standard SQL on SQLite or PostgreSQL. Everything in this tutorial transfers; only date functions and a few details differ between databases.
How long does it take to learn?
The ten queries above cover most daily analyst work. Working through them with your own data usually takes a few evenings, and practice with joins and window functions is what takes longer.
