SQL for Data Science Cheat Sheet
Reference for SQL aggregations, window functions, joins, and CTEs commonly used to analyze and reshape data during exploratory data science work.
2 PagesBeginnerMar 20, 2026
Aggregations & GROUP BY
Summarize rows into group-level statistics.
sql
SELECT region, COUNT(*) AS num_orders, SUM(amount) AS total_revenue, AVG(amount) AS avg_order_value, MIN(order_date) AS first_order, MAX(order_date) AS last_orderFROM ordersWHERE order_date >= '2024-01-01'GROUP BY regionHAVING SUM(amount) > 10000ORDER BY total_revenue DESC;
Window Functions
Compute per-row values across a related set of rows.
sql
SELECT customer_id, order_date, amount, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS order_seq, RANK() OVER (ORDER BY amount DESC) AS amount_rank, SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total, LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_amountFROM orders;
Joins & CTEs
Combine tables and structure multi-step queries.
sql
-- INNER JOIN: only matching rowsSELECT o.order_id, c.customer_nameFROM orders oINNER JOIN customers c ON o.customer_id = c.customer_id;-- LEFT JOIN: all rows from orders, matched customers or NULLSELECT o.order_id, c.customer_nameFROM orders oLEFT JOIN customers c ON o.customer_id = c.customer_id;-- Common table expression (CTE)WITH monthly_sales AS ( SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS total FROM orders GROUP BY 1)SELECT month, total FROM monthly_sales WHERE total > 50000;
Key Concepts
Terminology every data scientist writing SQL should know.
- GROUP BY- Aggregates rows sharing the same value(s) into summary rows
- HAVING vs WHERE- WHERE filters rows before aggregation, HAVING filters groups after aggregation
- Window functions- Compute values across a set of related rows without collapsing them, via the OVER clause
- CTE (WITH clause)- Named temporary result set that improves readability of multi-step queries
- NULL handling- Use COALESCE(col, default) to substitute NULLs; NULL = NULL is never TRUE, use IS NULL instead
- Subquery vs JOIN- Correlated subqueries can often be rewritten as JOINs or CTEs for better performance
- Index- Speeds up WHERE/JOIN/ORDER BY lookups on the indexed column(s) at the cost of write speed
Pro Tip
When debugging a complex query, build it up incrementally with CTEs and SELECT * at each stage - it's much easier to spot where a JOIN is duplicating or dropping rows than to debug the final nested query.
Was this cheat sheet helpful?
Explore Topics
#SQLForDataScience#SQLForDataScienceCheatSheet#DataScience#Beginner#AggregationsGROUPBY#WindowFunctions#JoinsCTEs#KeyConcepts#Functions#Databases#MachineLearning#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance