Review Publically — Header (standalone)
SQL for Data Science: The Complete Guide (2026)
sql-for-data-science.md — reviewpublically.com
SQL for Data Science: The Complete Guide — The full 15-article roadmap, start to finish
pillar / data-science / sql

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.

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.

MSc Computer Science Google Data Analytics SQL & Python Updated 2026
00

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.

// KEY INSIGHT
SQL is not a "nice to have" add-on to data science — it is usually the very first step in the data science lifecycle, before cleaning, before exploration, before any model gets trained.
01

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.

TaskBetter toolWhy
Pulling data from a company databaseSQLDatabases are built to be queried in SQL natively — faster than loading everything into Python first
Statistical modelling and machine learningPythonSQL has no native support for model training or advanced statistics
Aggregating millions of rowsSQLDatabases aggregate at the source, avoiding memory limits
Custom visualisationsPythonSQL has no plotting capability
Automating recurring pipelinesBothSQL 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.

02

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.

basic_select.sql
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.

03

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.

filtering.sql
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.

04

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.

aggregation.sql
SELECT region, SUM(order_total) AS total_revenue
FROM orders
GROUP BY region
HAVING SUM(order_total) > 1000000
ORDER BY total_revenue DESC;
// COMMON MISTAKE
Using 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.
05

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.

TYPE 01
INNER JOIN
Only rows that match in both tables. The most common default — use it when you only want records that exist on both sides.
TYPE 02
LEFT JOIN
Every row from the left table, plus matches from the right where they exist. Rows with no match get NULL on the right side. Useful for finding customers with zero orders.
TYPE 03
RIGHT JOIN
Mirror of LEFT JOIN. Rarely used — you can always flip the table order and use LEFT JOIN instead.
TYPE 04
FULL OUTER JOIN
Everything from both tables, matched where possible. Used for data reconciliation, not day-to-day queries.
inner_join.sql
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;
// WATCH OUT
Joining on a non-unique key silently multiplies your row count and inflates any SUM or COUNT downstream. Always check row counts before and after a join when a result looks wrong.
06

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.

cte_example.sql
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;
07

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.

window_functions.sql
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.

// INTERVIEW TIP
Being able to explain why you chose RANK() vs DENSE_RANK() for a specific scenario signals production experience, not just textbook knowledge.
08

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.

09

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.

SystemBest forNotes
PostgreSQLGeneral learning, most production appsFree, close to SQL standard — best default for beginners
MySQLWeb applicationsExtremely common; slightly different syntax in places
BigQueryLarge-scale analytics at cloud companiesGoogle Cloud's warehouse; SQL dialect with useful extensions
SnowflakeEnterprise data warehousingIncreasingly the standard at mid-to-large companies
SQLiteLocal practice, embedded appsZero 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.

10

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.

// REAL WORKFLOW PATTERN
SQL → shape and aggregate at the database → Python → model, visualise, communicate. Most production ML pipelines follow exactly this structure.
11

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.

FUNDAMENTALS — publish first
queued
SQL SELECT Statement: A Complete Guide
sql-select-statement/
queued
SQL Data Types Explained
sql-data-types/
INTERMEDIATE
queued
SQL GROUP BY and HAVING: Full Guide
sql-group-by-having/
queued
SQL Subqueries vs CTEs: When to Use Each
sql-subqueries-vs-cte/
ADVANCED
APPLIED & CAREER
queued
PostgreSQL vs MySQL vs BigQuery vs Snowflake
postgresql-vs-mysql-bigquery/
12

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
13

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.

// INTERVIEW TIP
If you can confidently explain why you chose a LEFT JOIN over an INNER JOIN for a specific scenario, you are already ahead of most candidates who can write the syntax but cannot justify the choice.
14

Frequently Asked Questions

Do data scientists need to know SQL?
Yes. SQL is the most consistently required skill in data science job postings because most company data lives in relational databases that SQL is built to query. A data scientist who cannot write SQL is bottlenecked on every project from the start.
Should I learn SQL or Python first for data science?
Learn SQL first. It is simpler, immediately useful in any real company environment, and is the skill you will use before any Python code runs. Python adds the modelling and automation layer on top once you have SQL.
Is SQL harder than Python?
No. Most beginners find SQL easier to start with. Its syntax reads close to plain English and you can become productive with SELECT, WHERE, GROUP BY, and basic JOINs in a few days rather than weeks.
Can I learn SQL in a week?
You can learn SELECT, WHERE, GROUP BY, and basic JOINs in about a week of focused practice. Window functions and query optimisation take longer to feel natural but are not required to start applying for junior data roles.
Which SQL database should I learn for data science?
PostgreSQL is the best default — it is free, close to the ANSI SQL standard, and skills transfer easily to cloud warehouses like BigQuery and Snowflake. MySQL is also common for web-application roles.
What is a CTE in SQL?
A Common Table Expression (CTE) is a named temporary result set defined with the WITH keyword before the main query. CTEs break complex queries into readable, named steps and are the professional standard alternative to deeply nested subqueries.
What are SQL window functions used for?
Window functions calculate a value across a set of rows related to the current row without collapsing them the way GROUP BY does. Common uses include ranking (RANK, DENSE_RANK, ROW_NUMBER), running totals (SUM OVER), and period-over-period comparison (LAG, LEAD).
How is SQL used in machine learning?
SQL is used in the data retrieval and feature engineering stages of ML workflows — pulling and shaping training data from relational databases or cloud warehouses before it enters Python for modelling. Most ML teams use SQL daily alongside Python.
15

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.

// NEXT STEPS
Install PostgreSQL (free), work through the 15 cluster articles in the order listed above, and practice on a real dataset — not a toy tutorial example. The PostgreSQL Official Tutorial and Mode Analytics SQL Tutorial are both excellent starting points.
references
reviewpublically.com/sql-for-data-science/ · Part of the Data Science learning track · © 2026 Review Publically