Prep Kit
Guide · SQL and Python

How SQL and Python Work Together in Data Analysis

By , implementation analyst · Updated

Why two tools if both work with data? Run one small relay and watch each hand off to the other.

The short answer
SQLPython
Asks questions of data in a databaseConnects the database to everything around it
Filter, join, group, totalFetch, automate, model, chart

A rule of thumb. The two overlap.

Pick by location: data already in a database, start with SQL. Data on the web or scattered in files, start with Python.
Practice data · made-up artists and plays

Run this first. Then run the other boxes in order, in the same Python session or one file. No download or API key needed.

import json
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE chart_songs (artist TEXT, title TEXT)")
conn.executemany("INSERT INTO chart_songs VALUES (?, ?)", [
    ("Maple Static", "Porch Light"),
    ("Maple Static", "Slow Tide"),
    ("Maple Static", "Paper Map"),
    ("Juno Vale", "Orbit"),
    ("Juno Vale", "Glass Hour"),
    ("Juno Vale", "Northbound"),
    ("The Low Fields", "Harvest Moon Diner"),
])

# Saved replies that stand in for a web API
saved_replies = {
    "Maple Static": """{"toptracks": {"track": [
        {"name": "Porch Light", "playcount": "9000", "listeners": "3000"},
        {"name": "Slow Tide", "playcount": "15000", "listeners": "2000"},
        {"name": "Back Stairs", "playcount": "8400", "listeners": "1200"},
        {"name": "Tiny Demo", "playcount": "900", "listeners": "60"}
    ]}}""",
    "Juno Vale": """{"toptracks": {"track": [
        {"name": "orbit", "playcount": "14000", "listeners": "2000"},
        {"name": "Night Ferry", "playcount": "20500", "listeners": "2500"},
        {"name": "Kitchen Window", "playcount": "4000", "listeners": "1600"}
    ]}}""",
}
print(conn.execute("SELECT COUNT(*) FROM chart_songs").fetchone()[0])
ResultMeaning
7Rows in chart_songs

Results shown come from Python 3.13.18 with SQLite 3.53.1. The one optional pandas box used pandas 3.0.5.

The steps

SQL asks the first questionWho has 3 or more charted songs?

SQL asks questions of tables: filter, join, group, summarize. Here the tables are already loaded, so SQL starts.

roster_query = """
SELECT artist, COUNT(*) AS songs_charted
FROM chart_songs
GROUP BY artist
HAVING COUNT(*) >= 3   -- SQL comment: keep busy artists
ORDER BY artist
"""
# Python comment: run the SQL, keep the names
roster = [row[0] for row in conn.execute(roster_query)]
print(roster)
Result
['Juno Vale', 'Maple Static']

HAVING filters groups. The Low Fields has one charted song, so it drops out.

The SQL sits inside a Python string. sqlite3 comes with the standard Python installers and carries the query to the database.

SQL comments start with --. Python comments start with #.
Quick check

Which clause removes artists with too few songs?

Python goes and gets data7 tracks from saved API replies

An API is a web address that answers requests with data. Standard SQL has no command for calling one, so Python is the usual choice.

Build the request address (nothing is sent)

from urllib.parse import urlencode

params = urlencode({
    "method": "artist.gettoptracks",
    "artist": "Juno Vale",
    "api_key": "YOUR_KEY",
    "format": "json",
    "limit": 50,
})
print("https://ws.audioscrobbler.com/2.0/?" + params)

It prints one long address. With your own Last.fm API key, urllib.request.urlopen(url, timeout=30) sends it. Keep real keys out of code you share.

Read the replies and load a table

def fetch_reply(artist):
    # Practice version: returns saved text, no internet needed
    return saved_replies[artist]

conn.execute("DROP TABLE IF EXISTS api_tracks")
conn.execute("""CREATE TABLE api_tracks
    (artist TEXT, track TEXT, playcount INTEGER, listeners INTEGER)""")

for artist in roster:
    data = json.loads(fetch_reply(artist))
    for t in data["toptracks"]["track"]:
        conn.execute(
            "INSERT INTO api_tracks VALUES (?, ?, ?, ?)",
            (artist, t["name"], int(t["playcount"]), int(t["listeners"])),
        )
conn.commit()
print(conn.execute("SELECT COUNT(*) FROM api_tracks").fetchone()[0])
ResultMeaning
7Tracks now in api_tracks

The replies hold numbers as text, so int() converts them. The ? marks pass values safely into SQL.

With a real API, pause between requests and read its terms. One failed request should be logged, not end the whole run.
Quick check

Why does the script call int()?

SQL finds the answer2 loved songs with no chart match

Both tables are in the database now. SQL joins them and keeps the tracks with no chart match.

gem_query = """
SELECT a.artist,
       a.track,
       ROUND(a.playcount * 1.0 / a.listeners, 1) AS plays_per_listener
FROM api_tracks AS a
LEFT JOIN chart_songs AS c
  ON LOWER(a.artist) = LOWER(c.artist)
 AND LOWER(a.track) = LOWER(c.title)
WHERE c.title IS NULL
  AND a.listeners >= 1000
  AND a.playcount * 1.0 / a.listeners >= 6
ORDER BY plays_per_listener DESC
"""
gems = conn.execute(gem_query).fetchall()
for row in gems:
    print(row)
artisttrackPlays per listener
Juno ValeNight Ferry8.2
Maple StaticBack Stairs7.0
  • LEFT JOIN with c.title IS NULL keeps tracks that found no partner.
  • LOWER lets orbit match Orbit. SQLite's built-in version changes only A to Z.
  • * 1.0 matters: SQLite divides two integers as an integer.
  • The 1,000 listener floor removes Tiny Demo: 15 plays per listener, but only 60 people.
Quick check

Remove both LOWER calls. What happens?

Python hands over the resultA CSV file someone can open

The answer is small now. Python writes it to a file.

import csv

with open("gems.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["artist", "track", "plays_per_listener"])
    writer.writerows(gems)

print(len(gems), "rows written to gems.csv")
Result
2 rows written to gems.csv

Optional: the same handoff with pandas

If pandas is installed, one call turns a query into a table you can chart or reshape.

import pandas as pd

gems_df = pd.read_sql_query(gem_query, conn)
print(gems_df.to_string(index=False))
artisttrackplays_per_listener
Juno ValeNight Ferry8.2
Maple StaticBack Stairs7.0

A BI tool such as Tableau or Power BI can take over here instead.

Quick check

Where did the filtering and joining happen?

A real project with both toolsFinding songs that never charted

My music hidden gems project asks which tracks by artists with a chart history get replayed a lot but have no chart match. It runs the same relay.

ToolWhat happenedCount
DataWeekly Billboard Hot 100 rows in the database, August 1958 to July 11, 2026354,500
SQLArtists with 5 or more charted songs, using HAVING1,570
PythonTracks fetched from Last.fm, up to 50 per artist, saved as a CSV78,335
SQLTracks with 1,000+ listeners and 6+ plays per listener13,090
SQLSongs with no chart match, after a LEFT JOIN and grouping repeats7,574
SQLOf those, songs under 200,000 listeners, labeled hidden gems4,473

The Python is one fetch script: it reads the artist list with a SQL query, pauses 0.25 seconds between requests, and records failed artists. The SQL file holds the queries. The project also has later Python scripts for extra details.

The Hot 100 combines sales, streaming and radio airplay. A missing chart match does not show that radio ignored a song, and a spelling difference can also cause one.
Quick check

What did SQL do before Python ran?

Which tool to reach for7 common jobs
You need toStart withWhy
Filter, join or total database tablesSQLThe work happens where the data is
Get data from a web APIPythonIt has libraries for web requests
Combine many files in a folderPythonIt can loop over files and fix each one
Define a metric others can reviewSQLA saved query shows the rule
Forecast or build a modelPythonLibraries such as scikit-learn
Repeat a job on a schedulePython + SQLA scheduler runs the script
Chart or report the resultPython or BIIt happens after the query

These are starting points, not limits. Some databases reach further: DuckDB can query CSV files in a folder or at a web address. pandas can also filter, join and group.

When the data already lives in a database, filter and total it there. Bring Python the smaller result.
Quick check

You need yesterday's total sales from a company database. Start with?

Which to learn firstMy suggestion: SQL

I suggest SQL first for analyst work:

  • It is a narrower language than Python, built for asking questions of data.
  • SELECT, WHERE, JOIN and GROUP BY answer many everyday questions.
  • Python is easier to aim once you know what you need it for, such as data that is not in a database yet.

Start with Python instead if your work today is mostly files, web data or repeated cleanup. Check the job postings you care about for what they ask.

Practice writing queries in SQL Drill: thirteen queries, each adding one thing to the last.

Quick check

Your job is cleaning 40 spreadsheets every week. A good first tool?

Cheat sheetThe handoff in six lines
JobCode
Open a filesqlite3.connect("my.db")
Run SQLconn.execute(query)
Get rows.fetchall()
Pass a value? in the query
Read JSON textjson.loads(text)
To pandaspd.read_sql_query(q, conn)

Keep one habit

Before writing code, say where the data is now and where it needs to end up.

Practice

SQL Kit and Python Kit

Work through lessons in your browser.

Open the SQL Kit · Open the Python Kit · Open SQL Drill

Free guide

Python for Analysts

A longer guide to Python for analyst work.

Download the free guide