SQL for Data Science: The Complete Guide (2026)
SQL is the single most reused skill in data science — more than any modelling library. This guide walks through exactly what you need, in the order you will actually use it, with the real queries you will write in your first job.
By Khalid Hussain · Published July 1, 2026 · 16 min read
Khalid Hussain is the founder of Review Publically, where he writes and maintains the Data Science and Machine Learning learning tracks. He holds a Master's degree in Computer Science and holds Google Advanced Data Analytics certification. This guide is reviewed for technical accuracy and updated as SQL tooling evolves.
Why SQL Matters in Data Science
If you ask ten working data scientists which skill they use every single day, more will say SQL than will name any machine learning library. That surprises beginners because most courses lead with Python and treat SQL as an afterthought. In practice the order is backwards — the job always starts with getting the data out.
Before you can clean a dataset, explore it, or train a model on it, the data has to come from somewhere. For the overwhelming majority of companies that somewhere is a relational database: customer records, transaction logs, product catalogues, web events — all of it typically lives in tables inside PostgreSQL, MySQL, or a cloud warehouse like Snowflake or BigQuery. SQL (Structured Query Language) is the language you use to ask that database for exactly the slice of data you need.
Without SQL you are dependent on someone else — a data engineer, an analyst — to hand you a CSV export every time you need information. With SQL you pull it yourself, filtered and shaped the way you need it, in seconds. That independence is why job postings for data scientist and data analyst roles list SQL as a required skill more consistently than any single Python library.
SQL vs Python: Different Jobs, Not Competing Tools
A common beginner question is whether to learn SQL or Python first, as if you have to pick one. They are not competitors — they solve different problems, and most real workflows use both in the same afternoon.
| Task | Better tool | Why |
|---|---|---|
| Pulling data from a company database | SQL | Databases are built to be queried in SQL natively — faster than loading everything into Python first |
| Statistical modelling and machine learning | Python | SQL has no native support for model training or advanced statistics |
| Aggregating millions of rows | SQL | Databases aggregate at the source, avoiding memory limits |
| Custom visualisations | Python | SQL has no plotting capability |
| Automating recurring pipelines | Both | SQL extracts and shapes; Python schedules and automates |
A typical real-world pattern: write a SQL query to pull and pre-aggregate exactly the data you need, then bring that smaller, cleaner result into Python (via Pandas) for the modelling or visualisation step. Trying to do everything in Python alone wastes both your time and your machine's memory.
SELECT: The Command You Will Type Every Day
Every SQL query for retrieving data starts with SELECT. It tells the database which columns you want. FROM tells it which table to pull from.
SELECT customer_id, order_date, order_total
FROM orders;
That query returns three columns from the orders table — every single row. To return every column without typing them all out you can use the wildcard SELECT *. In practice, experienced practitioners avoid it on large tables because it pulls more data than you need, slows the query, and makes downstream code harder to read.
Filtering and Sorting Results
WHERE narrows your results to rows that match a condition — this is where most of your actual analytical thinking happens. You can chain conditions with AND / OR, check ranges with BETWEEN, and match patterns with LIKE.
SELECT customer_id, order_total
FROM orders
WHERE order_total > 100
AND order_date >= '2026-01-01'
ORDER BY order_total DESC
LIMIT 10;
Use ORDER BY to sort results and LIMIT to cap the number of rows returned. Both are essential when exploring a large table — you want a preview, not a million-row download.
Aggregation: GROUP BY and HAVING
Aggregate functions (COUNT, SUM, AVG, MIN, MAX) summarise data across rows. GROUP BY tells the database which column to group by. Together they answer real business questions directly — "which region generates the most revenue?" in a single query.
SELECT region, SUM(order_total) AS total_revenue
FROM orders
GROUP BY region
HAVING SUM(order_total) > 1000000
ORDER BY total_revenue DESC;
WHERE to filter on a SUM() or COUNT() always throws an error. Use HAVING after GROUP BY instead — it runs after aggregation; WHERE runs before it.
JOINs: Combining Data Across Tables
Real databases almost never store everything in one table. A JOIN stitches related tables together on a shared ID column. Four types — one is used most of the time.
SELECT c.customer_name, o.order_total, o.order_date
FROM customers AS c
INNER JOIN orders AS o
ON c.customer_id = o.customer_id
WHERE o.order_total > 500;
Subqueries and CTEs
A subquery is a query nested inside another query. A Common Table Expression (CTE) — written with the WITH keyword — is the more readable version that professionals reach for once a query gets complex. CTEs break a complicated query into named, readable steps — much easier for someone else (or future you) to debug.
WITH big_spenders AS (
SELECT customer_id, SUM(order_total) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(order_total) > 1000
)
SELECT c.customer_name, b.total_spent
FROM customers AS c
JOIN big_spenders AS b
ON c.customer_id = b.customer_id
ORDER BY b.total_spent DESC;
Window Functions: The Skill That Separates Levels
Window functions calculate something across a set of rows without collapsing them the way GROUP BY does. This is consistently the most tested topic in data science SQL interviews because it signals you can write production-grade analytical SQL, not just textbook queries.
SELECT
customer_id,
order_date,
order_total,
RANK() OVER (
PARTITION BY customer_id
ORDER BY order_total DESC
) AS spend_rank,
SUM(order_total) OVER (
PARTITION BY customer_id
ORDER BY order_date
) AS running_total,
LAG(order_total) OVER (
PARTITION BY customer_id
ORDER BY order_date
) AS previous_order
FROM orders;
Common window functions: RANK() and DENSE_RANK() for rankings, LAG() and LEAD() for period-over-period comparisons, SUM() OVER for running totals, and ROW_NUMBER() for deduplication.
RANK() vs DENSE_RANK() for a specific scenario signals production experience, not just textbook knowledge.
Query Optimization: Writing Queries That Do Not Crawl
A query that works on a 10,000-row practice table can time out on a 50-million-row production table. These habits matter once data gets large.
Avoid SELECT * on wide tables — only pull the columns you actually need.
Filter early with WHERE before joining, so you are not joining unnecessary rows.
Index columns used frequently in WHERE and JOIN conditions — ideally with help from whoever manages the database.
Use EXPLAIN ANALYZE (PostgreSQL) to see how the database plans to execute your query before running something expensive.
Prefer CTEs over deeply nested subqueries — the query planner handles them better and colleagues can read them.
Which SQL Database Should You Actually Learn?
Core SQL is nearly identical across all systems. Differences appear at the edges — specific functions and how each handles scale.
| System | Best for | Notes |
|---|---|---|
| PostgreSQL | General learning, most production apps | Free, close to SQL standard — best default for beginners |
| MySQL | Web applications | Extremely common; slightly different syntax in places |
| BigQuery | Large-scale analytics at cloud companies | Google Cloud's warehouse; SQL dialect with useful extensions |
| Snowflake | Enterprise data warehousing | Increasingly the standard at mid-to-large companies |
| SQLite | Local practice, embedded apps | Zero setup; perfect for learning before connecting to a real DB |
Start with PostgreSQL. Skills transfer to BigQuery and Snowflake with minor adjustments. Install it locally or use the free tier of Supabase or Neon to practice immediately without setup friction.
What This Looks Like in a Real Job
A marketing manager asks: "Which customer segment had the biggest drop in repeat purchases last quarter versus the quarter before?" There is no dataset sitting ready for that — you have to build it.
The typical workflow: write a CTE that defines "repeat purchase" by counting orders per customer per quarter, join against a customer segment table, use a window function to compare quarter-over-quarter, pull the result into Pandas, plot it, write up the finding. SQL does the heavy lifting of shaping and aggregating at the source; Python handles the final visualisation. That division of labour is the normal shape of a real data science task — not the exception.
SQL Topic Cluster: All 15 Supporting Articles
This pillar connects to 15 cluster articles that build complete SQL topical authority. Publish in order — fundamentals before advanced — so internal links are live when each piece is indexed.
Common Beginner Mistakes
- Confusing WHERE and HAVING — WHERE filters rows before aggregation; HAVING filters after
- Not checking for duplicate joins — a join on a non-unique key can silently inflate SUM and COUNT results
- Over-relying on SELECT * — slows queries and obscures which columns actually matter
- Skipping NULL handling — NULL values behave differently in comparisons and aggregates than most beginners expect
- Memorising syntax instead of understanding execution order — SQL does not run top to bottom; FROM and WHERE execute before SELECT
- Running untested queries on production tables — always use LIMIT or EXPLAIN before running a new query against a large live table
SQL in Data Science Interviews
SQL interview questions cluster around a few recurring patterns: a JOIN across two or three tables, a metric calculated with GROUP BY and a conditional aggregate, and at least one window function question for ranking or running totals. Interviewers are testing whether you can reason about data — not whether you have memorised syntax.
Frequently Asked Questions
Do data scientists need to know SQL?
Should I learn SQL or Python first for data science?
Is SQL harder than Python?
Can I learn SQL in a week?
Which SQL database should I learn for data science?
What is a CTE in SQL?
What are SQL window functions used for?
How is SQL used in machine learning?
Summary: SQL Is the Starting Point, Not the Afterthought
SQL is the single most reused skill in data science — more than any modelling library, more than any specific Python package. Every real project starts here: pulling the right data, from the right tables, shaped the way analysis needs it.
Master SELECT, WHERE, GROUP BY, and JOIN first. Layer in CTEs, window functions, and optimisation as the complexity of your work grows. That order maps directly to how the skill gets used on the job — and to the 15 cluster articles above, each of which goes deeper on one piece of this guide.
Khalid Hussain
Founder of Review Publically. Holds a Master's degree in Computer Science with professional training in Google Advanced Data Analytics, Python, NumPy, and Seaborn. Writes and maintains the site's Data Science and Machine Learning learning tracks, testing every concept against real workflows before publishing.
// related reads
Data Science: The Complete Guide
Full pillar — where SQL fits in the bigger picture
Descriptive Statistics in Data Science
What to do with the data after you have queried it
Inferential Statistics in Data Science
Hypothesis testing and confidence intervals — the next step