How SQL and Python Work Together in Data Analysis
Why two tools if both work with data? Run one small relay and watch each hand off to the other.
| SQL | Python |
|---|---|
| Asks questions of data in a database | Connects the database to everything around it |
| Filter, join, group, total | Fetch, automate, model, chart |
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])| Result | Meaning |
|---|---|
7 | Rows in chart_songs |
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.
--. Python comments start with #.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])| Result | Meaning |
|---|---|
7 | Tracks now in api_tracks |
The replies hold numbers as text, so int() converts them. The ? marks pass values safely into SQL.
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)| artist | track | Plays per listener |
|---|---|---|
| Juno Vale | Night Ferry | 8.2 |
| Maple Static | Back Stairs | 7.0 |
LEFT JOINwithc.title IS NULLkeeps tracks that found no partner.LOWERletsorbitmatchOrbit. SQLite's built-in version changes only A to Z.* 1.0matters: SQLite divides two integers as an integer.- The 1,000 listener floor removes Tiny Demo: 15 plays per listener, but only 60 people.
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))| artist | track | plays_per_listener |
|---|---|---|
| Juno Vale | Night Ferry | 8.2 |
| Maple Static | Back Stairs | 7.0 |
A BI tool such as Tableau or Power BI can take over here instead.
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.
| Tool | What happened | Count |
|---|---|---|
| Data | Weekly Billboard Hot 100 rows in the database, August 1958 to July 11, 2026 | 354,500 |
| SQL | Artists with 5 or more charted songs, using HAVING | 1,570 |
| Python | Tracks fetched from Last.fm, up to 50 per artist, saved as a CSV | 78,335 |
| SQL | Tracks with 1,000+ listeners and 6+ plays per listener | 13,090 |
| SQL | Songs with no chart match, after a LEFT JOIN and grouping repeats | 7,574 |
| SQL | Of those, songs under 200,000 listeners, labeled hidden gems | 4,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.
What did SQL do before Python ran?
Which tool to reach for7 common jobs
| You need to | Start with | Why |
|---|---|---|
| Filter, join or total database tables | SQL | The work happens where the data is |
| Get data from a web API | Python | It has libraries for web requests |
| Combine many files in a folder | Python | It can loop over files and fix each one |
| Define a metric others can review | SQL | A saved query shows the rule |
| Forecast or build a model | Python | Libraries such as scikit-learn |
| Repeat a job on a schedule | Python + SQL | A scheduler runs the script |
| Chart or report the result | Python or BI | It 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.
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,JOINandGROUP BYanswer 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.
Your job is cleaning 40 spreadsheets every week. A good first tool?
Cheat sheetThe handoff in six lines
| Job | Code |
|---|---|
| Open a file | sqlite3.connect("my.db") |
| Run SQL | conn.execute(query) |
| Get rows | .fetchall() |
| Pass a value | ? in the query |
| Read JSON text | json.loads(text) |
| To pandas | pd.read_sql_query(q, conn) |
Keep one habit
Before writing code, say where the data is now and where it needs to end up.
SQL Kit and Python Kit
Work through lessons in your browser.
Analyst Prep Kit · All guides · Portfolio Projects
Version 2.0