While machine learning frameworks and deep learning libraries get much of the spotlight, Structured Query Language (SQL) remains the true workhorse of real-world data science.
Before any model can be trained or any metric visualized, data must be extracted, filtered, joined, and aggregated from relational databases. Modern data science platforms like Snowflake, BigQuery, and Databricks rely heavily on SQL for data wrangling at scale.
Here are the fundamental SQL queries, techniques, and patterns every data scientist must master.
1. The Core Execution Order
Understanding the logical order in which SQL executes a query is critical for writing efficient, error-free code:
2. Basic Filtering and Aggregations
Aggregations allow data scientists to summarize millions of raw records into meaningful metrics like averages, totals, and distributions.
3. Combining Tables with JOINs
Data science datasets are rarely contained in a single table. Joining related entities across primary and foreign keys is an everyday task.
4. Subqueries and CTEs (Common Table Expressions)
Complex analytical queries become unreadable when deeply nested. Common Table Expressions (CTEs) using the WITH clause break queries into modular, step-by-step logic blocks.
5. Window Functions (Advanced Analytics)
Unlike standard GROUP BY queries that collapse individual rows, Window Functions compute aggregate or ranking metrics across a subset of rows (“window”) while preserving every raw detail row.
Must-Know Window Functions
-
ROW_NUMBER(): Assigns a unique sequential integer to each row.
-
DENSE_RANK(): Ranks rows without skipping rank values in case of ties.
-
LEAD() / LAG(): Accesses values from the next or previous row, essential for calculating period-over-period growth rates.
6. Categorical Transformations with CASE WHEN
Feature engineering often requires bucketing continuous numerical features into discrete categorical segments.
Summary SQL Reference Checklist
| Technique |
Function / Syntax |
Practical Data Science Use Case |
| Aggregations |
SUM(), AVG(), COUNT(), HAVING |
Summarizing KPI performance |
| Joining Tables |
LEFT JOIN, INNER JOIN, COALESCE() |
Merging features across disparate tables |
| Modular Queries |
WITH table_name AS (...) |
Structuring multi-stage data pipelines |
| Ranking Windows |
ROW_NUMBER(), DENSE_RANK() |
Deduplicating records & identifying top-$N$ items |
| Time Series Windows |
LAG(), LEAD() |
Calculating growth rates and time differences |
| Conditional Logic |
CASE WHEN ... THEN ... END |
Binning continuous features for ML modeling |
Key Takeaway
Writing clean, modular SQL using CTEs and window functions accelerates exploratory analysis and feature engineering. Focus on understanding query execution order, mastering window functions like LAG/LEAD, and utilizing CTEs to build robust data pipelines.